Search code examples
firefoxtestingseleniumsequential

Running Selenium Tests Sequentially on Same Firefox Instance


I'm trying to set up some tests for a website that has a forum. As a result, many of these things need to be done in succession, including login, creating and removing threads, etc.

At the moment I've devised test cases using Selenium, and exported to Python with webdriver.

Is it possible to use only one webdriver instance between all tests so they can be executed in succession? I am rather new to python (coming from Java) so the only idea I had was to create a base class that would instantiate the webdriver, have all tests subclass the base, and have the webdriver passed to the tests. (I want to just do this in Java but I'm forcing myself to learn some Python).

Or is there another feature built into Selenium that will accomplish this?

Thanks for your time.


Solution

  • I managed to get it working by having a base class my tests would subclass. This base class would create a static driver that would be setup once by the setUp() method and returned to following tests.

    from selenium import webdriver
    import unittest, time, re
    
    class TestBase(unittest.TestCase):
    
        driver = None
        rand =  str(random.uniform(1,10))
        base_url = "desiredtestURLhere"
    
        def setUp(self):
             if (TestBase.driver==None):
                TestBase.driver = webdriver.Firefox()
                TestBase.driver.implicitly_wait(30)
             return TestBase.driver
    

    And then the two tests I ran...

    import unittest, time, re
    from testbase import TestBase
    
    class Login(TestBase):
    
        def test_login(self):
            driver = TestBase.driver
            base_url = TestBase.base_url
            driver.get(base_url)
            # etc
    

    Test #2 to be run in succession...

    import random
    import unittest, time, re
    from testbase import TestBase
    
    class CreateThread(TestBase):
    
        def test_create_thread(self):
            driver = TestBase.driver
            base_url = TestBase.base_url
            rand = TestBase.rand
            driver.get(base_url + "/forum.php")
            # etc
    

    My testsuite.py I would run...

    import unittest, sys
    # The following imports are my test cases
    import login
    import create_thread
    
    def suite():
        tsuite = unittest.TestSuite()
        tsuite.addTest(unittest.makeSuite(login.Login))
        tsuite.addTest(unittest.makeSuite(create_thread.CreateThread))
        return tsuite
    
    if __name__ == "__main__":
        result = unittest.TextTestRunner(verbosity=2).run(suite())
        sys.exit(not result.wasSuccessful())
    

    This is my first exposure to Python so if there are any glaring issues, I'd appreciate feedback.