Test Overview
This test checks that a fixture defined in conftest.py is properly shared and used in a test file. It verifies that the fixture runs and provides the expected value to the test.
This test checks that a fixture defined in conftest.py is properly shared and used in a test file. It verifies that the fixture runs and provides the expected value to the test.
import pytest # conftest.py @pytest.fixture def sample_fixture(): return "hello from fixture" # test_sample.py def test_using_fixture(sample_fixture): assert sample_fixture == "hello from fixture"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | pytest starts test discovery and finds test_using_fixture in test_sample.py | pytest environment ready, conftest.py fixture available | — | PASS |
| 2 | pytest loads conftest.py and registers sample_fixture fixture | fixture sample_fixture is ready to be injected | — | PASS |
| 3 | pytest runs test_using_fixture and injects sample_fixture | test_using_fixture receives 'hello from fixture' as sample_fixture value | assert sample_fixture == 'hello from fixture' | PASS |
| 4 | pytest completes test run and reports results | test_using_fixture passed successfully | — | PASS |
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