简体   繁体   中英

python unittests with multiple test classes

I am working on Python unittests. I want to segregate my test cases based on the pages/modules. When working with unittest.TestCase, every class need to have a setUp method to initialize my page instance. This causes a new instance of browser to open with each test case class run. What can I do to run all the testcase classes under the same browserinstance once after the other?

logintests.py

browser_input = input("Select a Browser: Firefox, Chrome, IE\n").lower()
class LoginTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls):

        browser = BrowserMachine(cls)
        cls.driver = browser.open_browser(cls, browser_input)
        cls.LoginPage = LoginPage(cls.driver)
        cls.HomePages = HomePages(cls.driver)

    def testcaseA(self):

homepagetests.py

class HomepageTests(unittest.TestCase):

    @classmethod
    def setUpClass(cls):

        browser = BrowserMachine(cls)
        cls.driver = browser.open_browser(cls, LT.browser_input)
        cls.LoginPage = LoginPage(cls.driver)
        cls.HomePages = HomePages(cls.driver)

    def testcaseB(self):

Make BrowserMachine into a global variable (module-level; you might create a separate module for that. Both classes should then use it.

The BrowserMachine then will not be able to refer to the class ( cls ) but you want only one BrowserMachine anyone, not one per class.

How about creating a main BrowserPage or BrowserMachine class that is a unittest.TestCase and have every other page class inherit that.

That way you can declare all your methods or properties (like defining individualized find_by , click_by , scroll_to etc... actions) in the BrowserPage class. Your page classes will be able to call those methods and properties or override them (something like click_login for your LoginTests class, that uses your BrowserPage 's click_by method on a specific login string), have indivudual SetUp and TearDown.

If you declare your driver in the main classe's setUpClass and quit it in it's tearDownClass, you should be able to use the same webppage across your tests. Unless you need to spawn new instances of it in other page classes (to perform some action in the background for example, while your main test is running).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM