I am learning pytest and studying the behavior of different fixture scopes. I am seeing unexpected behavior of class scoped fixtures when I run the tests. This is my project structure.
Pytest_Basics
│ conftest.py
└───pack1
test_a.py
test_b.py
Here are contents of each file.
conftest.py
import pytest
@pytest.fixture(scope='session', autouse=True)
def ses_fix():
print('In session fixture')
@pytest.fixture(scope='package', autouse=True)
def pak_fix():
print('In package fixture')
@pytest.fixture(scope='module', autouse=True)
def mod_fix():
print('In module fixture')
@pytest.fixture(scope='class', autouse=True)
def cls_fix():
print('In class fixture')
@pytest.fixture(scope='function', autouse=True)
def func_fix():
print('In functon fixture')
test_a.py
class TestA:
def test_a1(self):
assert True
def test_a2(self):
assert True
def test_a3(self):
assert True
test_b.py
def test_b1():
assert True
def test_b2():
assert True
def test_b3():
assert True
When I run the test using pytest -v -s
. I get below output.
pack1/test_a.py::TestA::test_a1 In session fixture
In package fixture
In module fixture
In class fixture
In functon fixture
PASSED
pack1/test_a.py::TestA::test_a2 In functon fixture
PASSED
pack1/test_a.py::TestA::test_a3 In functon fixture
PASSED
pack1/test_b.py::test_b1 In module fixture
In class fixture
In functon fixture
PASSED
pack1/test_b.py::test_b2 In class fixture
In functon fixture
PASSED
pack1/test_b.py::test_b3 In class fixture
In functon fixture
PASSED
I expected class scoped fixture will run only once as I have only one class in test_a.py
module. However, I am seeing it is running while executing tests in test_b.py
module.
What is causing this behavior? Is this a bug or I have limited understanding of class level fixtures.
Environment: Python - 3.9.5, Pytest - 6.2.4