Introduction
Conftest.py helps share setup code and fixtures across multiple test files easily.
Conftest.py helps share setup code and fixtures across multiple test files easily.
import pytest @pytest.fixture def my_fixture(): # setup code resource = None # define resource before yield yield resource # teardown code
Conftest.py is automatically discovered by pytest in the test directory.
Fixtures defined here can be used by any test in the same or subdirectories.
import pytest @pytest.fixture def sample_data(): return {'name': 'Alice', 'age': 30}
import pytest @pytest.fixture(scope='module') def db_connection(): conn = connect_to_db() yield conn conn.close()
This test uses a fixture from conftest.py to get a greeting message and checks it.
import pytest @pytest.fixture def greeting(): return 'Hello, world!' def test_greet(greeting): assert greeting == 'Hello, world!'
Do not import conftest.py directly; pytest finds it automatically.
Keep conftest.py simple and focused on shared fixtures or hooks.
Conftest.py shares setup code and fixtures across tests.
It helps avoid repeating code and keeps tests clean.
Pytest automatically finds and uses it in test folders.
conftest.py in pytest?conftest.pyconftest.py is used to hold fixtures and setup code that multiple test files can use.conftest.py.conftest.py?@pytest.fixture decorator followed by a function.@pytest.fixture and defines a function returning a value. Others either lack the decorator or are incorrect syntax.conftest.py fixture:
import pytest
@pytest.fixture
def number():
return 5
And this test file:
def test_double(number):
assert number * 2 == 10
What will be the test result when running pytest?number returns 5 and is automatically injected into the test function.number * 2 == 10, which is 5 * 2 == 10, true, so the test passes.conftest.py fixture:
import pytest
@pytest.fixture
def data():
return [1, 2, 3]
But your test fails with an error: fixture 'data' not found. What is the likely cause?conftest.py files in the test directory or its parents. If conftest.py is elsewhere, fixtures won't be found.conftest.py file is not in the same or parent directory of the test file -> Option Dconftest.py. Which approach best follows pytest best practices?yield allows setup before tests and cleanup after, ideal for resources like DB connections.conftest.py holding the connection without a fixture lacks cleanup and is not recommended. Use a class with static methods in conftest.py to manage the connection is more complex and less idiomatic.conftest.py that creates and yields the connection, then closes it after tests -> Option APass the test and this pattern moves unknown