Reputation: 97
we are creating tests by implementing unittest and pytest in python. we want to use fixtures for doing setup and tear down at session and test level. How to use object created in setup session fixture to be used in setup of function fixture. Example I want to create a driver object like driver = webdriver.Chrome() of intializing the browser and using the driver object in test methods and function scope fixture.
conftest.py import pytest
@pytest.fixture(scope="session")
def setupsession():
print("Starting Session")
yield
print("Ending Session")
@pytest.fixture(scope="module")
def setupmodule(request):
print("starting module")
yield
print("Ending Module")
@pytest.fixture(scope="class")
def setupclass(request):
print("starting module")
yield
print("Ending Module")
Basetest.py import unittest
class BaseTest(unittest.TestCase):
def setUp(self):
print("inside Base setup")
def tearDown(self):
print("inside base teardown")
test.py import pytest from wav2.fixtures.base_test import BaseTest
@pytest.mark.usefixtures("setupsession", "setupmodule")
class TestSample(BaseTest):
def test1(self):
print("calling inside test test1")
self.assertTrue(False)
def test2(self):
print("calling inside test tes`enter code here`t2")
Upvotes: 3
Views: 4539
Reputation: 1562
A fixture can use other fixture too. That means you can use a session fixture inside a module fixture, you can use a module fixture inside a class fixture and so on. You can also use same scope fixture in other fixture. Only 2 limit is that you can not import a fixture backwards (like using a function level fixture in the class level fixture) and there can not be a circular dependency.
Please find the same example given in question with an additional fixture with scope=function
and using a fixture inside another fixture.
conftest.py
import pytest
import unittest
@pytest.fixture(scope="session")
def setupsession(request):
print("Starting Session")
yield "session_obj"
print("Ending Session")
@pytest.fixture(scope="module")
def setupmodule(request, setupsession):
print("starting module")
yield setupsession, "module_obj"
print("Ending Module")
@pytest.fixture(scope="class")
def setupclass(request, setupmodule):
print("starting class")
yield (*setupmodule, "class_obj")
print("Ending class")
@pytest.fixture(scope="function")
def setupmethod(request, setupclass):
print("starting method")
yield (*setupclass, "class_obj")
print("Ending method")
Note: As we have created setupmethod fixture, it is not necessary to create BaseTest with setUp
and tearDown
method. But, it's your choice depending on the structure of hte test cases.
test_file.py
@pytest.mark.usefixtures("setupmethod")
class TestSample(BaseTest):
def test1(self):
print("calling inside test test1")
self.assertTrue(False)
def test2(self):
print("calling inside test tes`enter code here`t2")
Reference: http://devork.be/talks/advanced-fixtures/advfix.html
Upvotes: 4