I'm new to using Pytest. I'm a little confused about what's the appropriate use of fixtures and dependency injection for my project. My framework is the following:
conftest.py
@pytest.fixture(scope="session")
def test_env(request):
//some setup here for the entire test module test_suite.py
@pytest.fixture(scope="function")
def setup_test_suite(test_env):
//some setup that needs to be done for each test function
//eventually parameterize? for different input configuration
test_suite.py
def test_function(setup_test_suite)
//some testing code here
The difference between a fixture in conftest.py
and in the local test module is visibility. The fixture will be visible to all test modules at the same levels and in modules below that level. If the fixture is set to autouse=True
it will be executed for all tests in these modules.
For more information, check What is the use of conftest.py files
If test_env
is session-based, it will be executed only once in the session, even if it is referenced in multiple tests. If it yields an object, the same object will be passed to all tests referencing it. For example:
@pytest.fixture(scope="session")
def global_fixt():
print('global fixture')
yield 42
@pytest.fixture(scope="function")
def local_fixt(global_fixt):
print('local fixture')
yield 5
def test_1(global_fixt, local_fixt):
print(global_fixt, local_fixt)
def test_2(global_fixt, local_fixt):
print(global_fixt, local_fixt)
Gives the output for pytest -svv
:
...
collected 2 items
test_global_local_fixtures.py::test_1 global fixture
local fixture
42 5
PASSED
test_global_local_fixtures.py::test_2 local fixture
42 5
PASSED
...
@pytest.fixture(scope="session", params=[100, 1, 42])
def global_fixt(request):
yield request.param
def test_1(global_fixt):
assert True
def test_2(global_fixt):
assert True
The tests will be executed in this order:
test_1 (100)
test_2 (100)
test_1 (1)
test_2 (1)
test_1 (42)
test_2 (42)
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.