如何在套件中的测试类中共享一个webdriver实例?我用硒和Python

2024-10-01 13:29:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码是这样的:

class class1(unittest.TestCase):
    def setUp(self):
        self.driver = webdriver.Firefox()

    def testListRolesTitle(self):
        driver=self.driver
        driver.get("www.google.com")

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)
        asert...


class class2(unittest.TestCase):

    def setUp(self):
        self.driver = webdriver.Firefox()

    def testListRolesTitle(self):
        driver=self.driver
        driver.get("www.google.com")
        assert...

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

def suite():
    s1 = unittest.TestLoader().loadTestsFromTestCase(class1)
    s2 = unittest.TestLoader().loadTestsFromTestCase(class2)

    return unittest.TestSuite([s1,s2])

if __name__ == "__main__":

    run(suite())

当我运行该套件时,两个测试类都在setup method中启动了一个新的firefox实例。 我的问题是,是否可以让两个测试类使用同一个firefox实例? 我不想把他们放在一个班里。在

有什么想法吗?在


Tags: selfcomgetdefwwwdrivergooglesetup
1条回答
网友
1楼 · 发布于 2024-10-01 13:29:04

您可以有一个应用于整个模块的setup函数,而不是像解释的那样只应用于类here。在

在你的情况下,应该是:

def setUpModule():
    DRIVER = webdriver.Firefox()

def tearDownModule():
    DRIVER.quit()

注意,DRIVER在本例中是一个全局变量,因此它对所有类的对象都可用。在

另外,请注意,测试用例排序可能会导致多次调用模块设置函数,如文档中所述:

The default ordering of tests created by the unittest test loaders is to group all tests from the same modules and classes together. This will lead to setUpClass / setUpModule (etc) being called exactly once per class and module. If you randomize the order, so that tests from different modules and classes are adjacent to each other, then these shared fixture functions may be called multiple times in a single test run.

它认为这个例子应该说明每个设置方法/函数的执行时间:

^{pr2}$

结果是:

$ python -m unittest my_test.py

Module setup...
Class setup...
One
Class teardown...
.Class setup...
Two
Class teardown...
.Module teardown...

                                   
Ran 2 tests in 0.000s

OK

相关问题 更多 >