jacobcan118
jacobcan118

Reputation: 9037

How to use pytest fixture and sharing variable between each testcase

I need to write some ui test with python3 and selenium webdriver. With the following testcase, test runs fine. However, my question is what is the better way for me to write the testcase and how i can pass "base" variable between each testcase and pytest fixture function I need to 1:open home page before each testcase, 2: reload home page after each testcase and reducing the code by sharing variable "base" between each testcase and pytest fixture function. import pytest from modules.base import Home

class TestLogin(object):

    def setup_method(self, method):
        self.driver = WebDriver(desired_capabilities=desired_capabilities, command_executor=command_executor)
        self.current_method_name = method.__name__

    def teardown_method(self, method):
        self.driver.close()
        self.driver.quit()

    @pytest.fixture(scope="function")
    def loadpage():
        self.base = Home(self.driver).open()

    def loadLogin():
        base.loadLogin()

    def test_a(self):
        base = Home(self.driver).open()
        assert True == base.dotesta()
        base.loadLogin()

    def test_b(self):
        base = Home(self.driver).open()
        assert True == base.dotestb()
        base.loadLogin()

    def test_c(self):
        base = Home(self.driver).open()
        assert True == base.dotestc()
        base.loadLogin()

    def test_d(self):
        base = Home(self.driver).open()
        assert True == base.dotestd()
        base.loadLogin()

Upvotes: 1

Views: 1311

Answers (1)

pr4bh4sh
pr4bh4sh

Reputation: 714

For your current requirement, you don't need to use the fixture. Here's your code with it.

class TestLogin(object):

    def setup_method(self, method):
        self.driver = WebDriver(desired_capabilities=desired_capabilities, command_executor=command_executor)
        self.current_method_name = method.__name__
        self.base = Home(self.driver).open()

    def teardown_method(self, method):
        self.base.loadLogin()
        self.driver.close()
        self.driver.quit()

    def test_a(self):
        assert True == self.base.dotesta()

    def test_b(self):
        assert True == self.base.dotestb()

    def test_c(self):
        assert True == self.base.dotestc()

    def test_d(self):
        assert True == self.base.dotestd()

Edit: For opening the page only once, replace the setup and teardown with

    def setup_class(cls):
        cls.driver = WebDriver(desired_capabilities=desired_capabilities, command_executor=command_executor)
        cls.current_method_name = method.__name__
        cls.base = Home(self.driver).open()

    def teardown_method(cls):
        cls.base.loadLogin()
        cls.driver.close()
        cls.driver.quit()

Details about cls.

Upvotes: 1

Related Questions