I have a following structure of modules:
.
├── conftest.py
└── test
├── test_one.py
└── test_two.py
My conftest.py contains a single fixture:
import pytest
@pytest.fixture(scope='session')
def sophisticated_fixture():
print('\nFixture init')
yield 42
print('\nFixture kill')
My test_{one,two}.py
tests look like this:
from conftest import sophisticated_fixture
def test_a(sophisticated_fixture):
assert sophisticated_fixture == 42
def test_b(sophisticated_fixture):
assert sophisticated_fixture == 42
I would expect that running pytest -s
in the top-level directory would run all the tests using the same fixture, as I have defined it as session-level. However, this happens:
============================= test session starts ==============================
platform linux -- Python 3.6.6, pytest-4.0.2, py-1.7.0, pluggy-0.8.0
rootdir: /home/tomasz/example, inifile:
collected 4 items
test/test_one.py
Fixture init
..
test/test_two.py
Fixture init
..
Fixture kill
Fixture kill
=========================== 4 passed in 0.01 seconds ===========================
Clearly fixture function is called twice for every test module, and the fixture exits at the very end of the test run.
How can I make my fixture global for the duration of the entire test session?
You do not have to import the fixture in the test file(s). Fixtures are automatically discovered by pytest. Try after removing the below line from test files.
from conftest import sophisticated_fixture