import pytest
setup_calls = {
'function': 0,
'class': 0,
'module': 0,
'session': 0
}
@pytest.fixture(scope='function')
def func_scope_fixture():
setup_calls['function'] += 1
print('Setup function')
yield
@pytest.fixture(scope='class')
def class_scope_fixture():
setup_calls['class'] += 1
print('Setup class')
yield
@pytest.fixture(scope='module')
def module_scope_fixture():
setup_calls['module'] += 1
print('Setup module')
yield
@pytest.fixture(scope='session')
def session_scope_fixture():
setup_calls['session'] += 1
print('Setup session')
yield
# Test functions using function and module scope
def test_func1(func_scope_fixture, module_scope_fixture, session_scope_fixture):
assert setup_calls['function'] >= 1
assert setup_calls['module'] == 1
assert setup_calls['session'] == 1
def test_func2(func_scope_fixture, module_scope_fixture, session_scope_fixture):
assert setup_calls['function'] >= 2
assert setup_calls['module'] == 1
assert setup_calls['session'] == 1
# Test class using class and module scope
class TestClass:
def test_method1(self, class_scope_fixture, module_scope_fixture, session_scope_fixture):
assert setup_calls['class'] == 1
assert setup_calls['module'] == 1
assert setup_calls['session'] == 1
def test_method2(self, class_scope_fixture, module_scope_fixture, session_scope_fixture):
assert setup_calls['class'] == 1
assert setup_calls['module'] == 1
assert setup_calls['session'] == 1
This test script defines four fixtures with different scopes: function, class, module, and session.
Each fixture increments a counter and prints a setup message when it runs.
Test functions and a test class use these fixtures to verify how many times each setup runs.
Assertions check that function-scoped fixture runs before each test function, class-scoped fixture runs once per class, module-scoped fixture runs once per module, and session-scoped fixture runs once per entire test session.
This approach uses counters and assertions to confirm fixture scope behavior clearly and simply.