How can I share one instance of webdriver in my test classes in a package? I am using Selenium2 and Python

My code looks like this:

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()) 

When I ran the package, both test classes started a new instance of firefox in the installation method. My question is, is it possible to make two test classes use the same instance of firefox? I do not want to combine them in one class.

Any ideas?

+6
source share
1 answer

You may have a setup function that applies to the entire module, and not just to the class, as described here .

In your case, it will be something like:

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

Note that DRIVER is a global variable in this case, so that it is available for objects of all classes.

Also note that the check order may cause the configuration functions of your module to be called several times, as described in the documentation:

The default order for tests created by unittest test loaders is to combine all tests from the same modules and classes. This will cause setUpClass / setUpModule (etc.) to be called exactly once for each class and module. If you randomized an order so that tests from different modules and classes are adjacent to each other, these common binding functions can be called several times in one run.

He believes that this example should be clear when each installation method / function is executed:

 import unittest def setUpModule(): print 'Module setup...' def tearDownModule(): print 'Module teardown...' class Test(unittest.TestCase): def setUp(self): print 'Class setup...' def tearDown(self): print 'Class teardown...' def test_one(self): print 'One' def test_two(self): print 'Two' 

The way out of this:

 $ 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 
+2
source

Source: https://habr.com/ru/post/902910/


All Articles