Shrini
Shrini

Reputation: 193

Quit driver instance in pytest after all the tests are executed

Below is the pytest class used to run 2 tests. Want to quit driver after both the tests are executed. used Teardown but it quits the driver after each test execution is completed

class FlightTest(unittest.TestCase):

        driver = webdriver.Chrome(direct_path+'/resources/chromedriver.exe')
        startup = StartUpPage(driver)
        register = RegisterPage(driver)

        def test_flight_registration(self):
            dat = self.json_reader.read_from_file("testdata.json")
            self.startup.navigate_to_url(dat['url'])\
                        .click_on_register_button()
            self.register.create_user(dat['uid'], dat['pwd'], dat['con_pwd'])

        def test_flight_sign_in(self,):
            dat = self.json_reader.read_from_file("testdata.json")
            self.startup.click_sign_in_link()

        def tearDown(self):
            self.driver.quit()

Upvotes: 1

Views: 2127

Answers (1)

hoefling
hoefling

Reputation: 66201

In unittest terms, you would need to use the setUpClass and tearDownClass class methods:

class FlightTest(unittest.TestCase):

    @classmethod
    def setUpClass(cls)
        cls.driver = webdriver.Chrome()
        cls.startup = StartUpPage(driver)
        cls.register = RegisterPage(driver)

    @classmethod
    def tearDownClass(cls):
        cls.driver.quit()

    ...

In pytest terms, you would create a class-scoped fixture:

import pytest

@pytest.fixture(scope="class")
def driver(request):
    # code before 'yield' is executed before the tests
    request.cls.driver = webdriver.Chrome()
    request.cls.startup = StartUpPage(request.cls.driver)
    request.cls.register = RegisterPage(request.cls.driver)
    yield
    # code after 'yield' is executed after the tests
    request.cls.driver.quit()


@pytest.mark.usefixtures('driver')
class FlightTest(unittest.TestCase):

    def test_spam(self):
        self.driver.get('https://www.google.de')

    def test_eggs(self):
        self.driver.get('https://www.facebook.com')

An even better solution would be using the context manager property of the webdriver so it is automatically closed no matter what:

import pytest

@pytest.fixture(scope="class")
def driver(request):
    with webdriver.Chrome() as driver:
        request.cls.driver = driver
        request.cls.startup = StartUpPage(driver)
        request.cls.register = RegisterPage(driver)
        yield


@pytest.mark.usefixtures('driver')
class FlightTest(unittest.TestCase):

    def test_spam(self):
        self.driver.get('https://www.google.de')

    def test_eggs(self):
        self.driver.get('https://www.facebook.com')

Upvotes: 3

Related Questions