Test Overview
This test uses a shared fixture defined in conftest.py to provide a sample user dictionary. It verifies that the test function receives the correct data from the fixture.
This test uses a shared fixture defined in conftest.py to provide a sample user dictionary. It verifies that the test function receives the correct data from the fixture.
import pytest # conftest.py @pytest.fixture def sample_user(): return {"name": "Alice", "age": 30} # test_user.py def test_user_name(sample_user): assert sample_user["name"] == "Alice"
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | PyTest discovers the fixture 'sample_user' in conftest.py | PyTest test runner ready to run tests in test_user.py | — | PASS |
| 2 | PyTest starts test 'test_user_name' and injects 'sample_user' fixture | Test function receives dictionary {"name": "Alice", "age": 30} | — | PASS |
| 3 | Test asserts that sample_user["name"] equals "Alice" | sample_user["name"] is "Alice" | assert sample_user["name"] == "Alice" | PASS |
| 4 | Test completes successfully | Test runner marks test as passed | — | PASS |
conftest.py file in pytest?conftest.pyconftest.py file is used to define fixtures that can be shared across multiple test files without needing explicit imports.conftest.py for sharing across test files?@pytest.fixture to be recognized by pytest.conftest.py fixture and test file, what will be the output when running pytest?
-- conftest.py --
import pytest
@pytest.fixture
def number():
return 5
-- test_sample.py --
def test_double(number):
assert number * 2 == 10
def test_triple(number):
assert number * 3 == 15
number returns 5 and is shared automatically via conftest.py.conftest.py as follows:
import pytest
@pytest.fixture
def data():
return [1, 2, 3]
In your test file, you wrote:
def test_sum(data):
assert sum(data) == 10
What is the problem and how to fix it?data returns the list [1, 2, 3].conftest.py:
import pytest
@pytest.fixture(scope="session")
def db_connection():
conn = create_connection()
yield conn
conn.close()
What is the best reason to use scope="session" here?Pass the test and this pattern moves unknown