pytest fixtures supply the data, configuration, or resources a test needs. A test requests a fixture by name; pytest resolves its dependencies, provides its value, and manages its configured lifecycle. Fixtures are therefore more than reusable setup functions: they make a test’s prerequisites and resource ownership explicit. By the end of this walkthrough of pytest fixtures, you will be able to choose fixture scope, share setup without leaking mutable state, verify cleanup after failures, and run a complete local SQLite suite. All examples use synthetic data, not client implementations.
Related Blogs
Pytest BDD vs Behave: Pick the Best Python BDD Framework
Streamlining Automated Testing with GitHub Actions
Prerequisites: Familiarity with Python functions, imports, decorators, and assert. The inventory examples use a stock-keeping unit (SKU) as a product identifier.
Companion release v2: Complete examples and execution evidence · Browsable file index. Extract the example archive into a working folder so the referenced files remain available.
Quick route: First fixture → Complete SQLite example → Troubleshooting.
Table of Content
- What Are pytest Fixtures?
- Create and Run Your First Fixture
- Share pytest Fixtures with conftest.py
- Choose a Scope for pytest Fixtures and Understand Execution Order
- Handle Setup and Teardown Safely
- Choose Explicit Fixtures, usefixtures, or autouse
- Parametrize Fixtures and Build Test-Data Factories
- Use Built-in pytest Fixtures for Isolation and Evidence
- Build a Complete SQLite Fixture Example
- Debug Fixture Failures and Prepare for Parallel Runs
- pytest Fixtures Design Checklist
- Conclusion
What Are pytest Fixtures?
Fixtures as reusable test context
Think of a test as arrange, act, assert. A fixture handles reusable prerequisites in the arrange phase; the test performs the behavior and checks the result. A fixture might supply an empty inventory, a configured environment, or a database connection. pytest fixtures can depend on other fixtures, letting a complex prerequisite be assembled from smaller pieces.
For this tutorial, use a practical distinction: setup should establish the starting condition; assertions about the feature under test should remain visible in the test body. A failed connection during setup and an incorrect stock quantity are different problems and should be easy to distinguish.
Fixtures versus helper functions and setup methods
Prefer a fixture when pytest should manage availability, dependencies, reuse, or cleanup. Prefer an ordinary helper for a calculation or transformation with no test lifecycle to manage. A function that formats a product code does not need to become a fixture merely because several tests call it.
For new tests in this walkthrough, favor explicit fixture dependencies over a large shared setup method. This is a design recommendation, not a requirement to rewrite an existing suite. Do not call a decorated fixture as an ordinary function; request it as a parameter, or put reusable construction logic in a separate helper.
Create and Run Your First Fixture
Prepare the environment and project files
Start in the extracted pytest-fixtures-walkthrough-v2/ directory. The following project map lists every application, teaching, failure-demonstration, and verification file; the linked index also exposes every captured evidence file. Create a virtual environment with a suitable Python interpreter.
Verification matrix:
| S. No | Path or version | Status for this revision | Evidence / limitation |
|---|---|---|---|
| 1 | pytest 9.0.2; Python 3.13.5; SQLite 3.46.1; Linux | Executed | 33 application cases; 47 total; warnings-as-errors and reversed order; five lifecycle checks. |
| 2 | pytest 9.2.0; Python 3.10+ requirement | Documentation-reviewed only | Release metadata checked; package retrieval failed in this runtime. No 9.2.0 execution is claimed. |
| 3 | Other Python/OS versions; pytest-xdist | Not executed | Re-run on the intended environment before claiming compatibility or parallel safety. |
Versions used: The reference release is pytest 9.2.0 (27 October 2026). The executed-version path below matches the recorded 9.0.2 runner; fresh installation was not verified here. Inspect the execution record in the companion index.
Project map (files are listed in the companion index):
pytest-fixtures-walkthrough-v2/
inventory.py
pytest.ini
requirements.txt / requirements-reference.txt
requirements-verified.txt / requirements-executed-lock.txt
README.md / RELEASE.txt / index.html / SHA256SUMS.txt
tests/
conftest.py
test_inventory.py
examples/
test_first.py
test_dependencies.py
test_corrected_scope.py
test_finalizer.py
test_activation.py
test_autouse.py
test_builtins.py
sharing/tests/
conftest.py
test_default.py
special/
conftest.py
test_override.py
fault_demos/
test_lifecycle.py
test_finalizer_failure.py
test_scope_mismatch.py
tools/
verify_all.py
verify_lifecycle.py
verify_manifest.py
evidence/
captured-2026-11-29/ # Reports, JUnit XML, node IDs
pytest920-install.txt
pytest920-official-install.txt
python -m venv .venv
For bash or zsh:
source .venv/bin/activate
For Windows PowerShell:
.\.venv\Scripts\Activate.ps1
Executed-version path: Install the pinned runner used in the supplied evidence, then confirm the versions in your own environment:
python -m pip install -r requirements-verified.txt python --version python -m pytest --version
Reference-version path (not executed here): Use a separate virtual environment for python -m pip install -r requirements-reference.txt, which pins pytest 9.2.0. Do not merge evidence from different environments. The archive also records the exact installed dependency versions in requirements-executed-lock.txt.
Define a fixture and request it in a test
Copy now, complete file: examples/test_first.py
import pytest
@pytest.fixture
def inventory_data():
return {"sku": "SKU-100", "quantity": 5}
def test_stock_is_available(inventory_data):
assert inventory_data["sku"] == "SKU-100"
assert inventory_data["quantity"] > 0
Run it from the project root:
python -m pytest -q examples/test_first.py
The fixture’s name matches the test parameter. pytest supplies the returned dictionary; the test does not call inventory_data(). The expected result is one passing test. Its two assertions verify both the selected item and the stock precondition.
Run commands from the project root. examples/ contains the teaching tests, tests/ exercises inventory.py, and fault_demos/ contains deliberate failures. The default suite excludes those failure demonstrations; verification tools run them separately. Copy-now labels identify complete files; excerpt labels identify fragments whose prerequisites are linked.
Share pytest Fixtures with conftest.py
Share fixtures across test modules
Use conftest.py to provide pytest fixtures to tests in its directory and descendants. Tests do not need to import these fixtures. Discovery follows the requesting test’s location; a fixture in a sibling directory is not automatically available.
The sharing demonstration uses this layout:
examples/sharing/tests/
conftest.py
test_default.py
special/
conftest.py
test_override.py
Copy now, complete file: examples/sharing/tests/conftest.py
import pytest
@pytest.fixture
def app_config():
return {"warehouse": "main", "currency": "INR"}
Copy now, complete file: examples/sharing/tests/test_default.py. This assertion identifies the selected configuration:
def test_default_warehouse(app_config):
assert app_config == {"warehouse": "main", "currency": "INR"}
Override fixtures for a specific test directory
Copy now, complete file: examples/sharing/tests/special/conftest.py
import pytest
@pytest.fixture
def app_config(app_config):
return {**app_config, "warehouse": "overflow"}
Here, the override requests the parent fixture with the same name, then returns a new dictionary. The nested test asserts {"warehouse": "overflow", "currency": "INR"}. The parent test retains its original expectation. This makes the override’s boundary observable. Directory-level overrides are a supported fixture pattern.
Copy now, complete file: examples/sharing/tests/special/test_override.py
def test_local_warehouse(app_config):
assert app_config == {"warehouse": "overflow", "currency": "INR"}
Visibility is not lifetime: Moving a fixture into conftest.py does not make it session-scoped. Organization and resource reuse are separate decisions.
Choose a Scope for pytest Fixtures and Understand Execution Order
Compare function, class, module, package, and session scopes
The default scope for pytest fixtures is function. The table summarizes lifecycle boundaries; the suggested uses are design recommendations. Parametrization can cause additional fixture instances within a scope, so these are not unconditional creation-count guarantees.
| S. No | Scope | Lifetime boundary | Suggested use | Main caution |
|---|---|---|---|---|
| 1 | function | One test invocation | Mutable records and isolated database state | Repeated expensive setup |
| 2 | class | Tests in a class | A deliberately shared class-level resource | One method changes another’s starting state |
| 3 | module | Tests in a module | Read-only module test data | Hidden coupling between tests |
| 4 | package | Relevant test package, including descendants | Package-specific infrastructure | Verify the actual package boundary |
| 5 | session | Test session in the process | Stable configuration or expensive infrastructure | Shared state and parallel-worker assumptions |
For package scope, establish the intended Python package structure, normally with __init__.py; do not assume every folder creates a separate package lifetime. A broader-scoped connection does not require shared mutable test data. Prefer sharing expensive infrastructure while creating isolated mutable state for each test.
Understand caching and mutable state
The same fixture instance can be requested through several dependency paths without being reconstructed for each request in a test. This is reuse, not copying. Mutable values therefore remain shared by the consumers of that instance.
Copy now, complete file: examples/test_dependencies.py
import pytest
@pytest.fixture
def events():
return []
@pytest.fixture
def prepared(events):
events.append("prepared")
return events
@pytest.fixture
def ready(prepared):
prepared.append("ready")
return prepared
def test_dependency_chain(ready, events):
assert ready is events
assert events == ["prepared", "ready"]
def test_fresh_state(events):
assert events == []
ready is events checks object identity. The event list proves that the dependency chain established prepared before ready. The second test checks fresh function-scoped state. Changing this list to session scope would change that isolation contract.
Declare dependencies and avoid scope mismatches
Execution order follows scope, dependencies, and autouse behavior. It is not a promise about fixture names, declaration order, or the order of arguments in the test signature. Make a required ordering relationship a dependency.
A session-scoped fixture cannot depend on a function-scoped fixture. pytest reports ScopeMismatch because the requested resource has a shorter lifetime than its consumer.
Intentional failure, complete file: fault_demos/test_scope_mismatch.py
import pytest
@pytest.fixture(scope="function")
def per_test():
return {}
@pytest.fixture(scope="session")
def shared(per_test):
return per_test
def test_invalid_scope(shared):
assert shared == {}
In the corrected example, set shared to function scope. Do not promote mutable per-test data to session scope merely to silence the error. Copy now, complete file: examples/test_corrected_scope.py.
import pytest
@pytest.fixture(scope="function")
def per_test():
return {}
@pytest.fixture(scope="function")
def shared(per_test):
return per_test
def test_correct_scope(shared):
assert shared == {}
Handle Setup and Teardown Safely
Use return or yield according to resource ownership
Use return for a value that needs no fixture-owned cleanup. Use a yielding fixture when setup acquires a resource that must later be released. pytest resumes a successfully yielding fixture during teardown, even when the test assertion fails. Dependent fixtures are finalized before the resources they depend on.
For the SQLite example, the database fixture owns the connection; the repository object borrows it. Keeping those responsibilities separate makes the cleanup location obvious.
Protect resources when setup fails
A failure before yield prevents pytest from reaching ordinary post-yield teardown in that fixture. Previously established fixtures still receive teardown.
Excerpt, requires inventory.py and tests/conftest.py in the complete SQLite example. Protect fallible initialization immediately after acquiring the resource; this is not a separate runnable file:
conn = sqlite3.connect(target, isolation_level="DEFERRED")
try:
create_schema(conn)
yield conn
finally:
conn.close()
Python’s finally block runs when initialization raises inside the try, including before the generator reaches yield. In this pattern, cleanup therefore covers both the setup-error path and normal fixture finalization. It cannot guarantee cleanup after a forcibly terminated process.
The alternative below registers cleanup immediately after successful acquisition. Copy now, complete file: examples/test_finalizer.py. Prerequisite: inventory.py in the complete example supplies create_schema.
import sqlite3
import pytest
from inventory import create_schema
@pytest.fixture
def finalized_db(request):
conn = sqlite3.connect(":memory:")
request.addfinalizer(conn.close)
create_schema(conn)
return conn
def test_finalized_db(finalized_db):
result = finalized_db.execute("SELECT COUNT(*) FROM inventory")
assert result.fetchone() == (0,)
The finalizer is registered before schema creation. pytest will call a registered finalizer even if later fixture setup raises; register it only after there is a resource to release.
Verify cleanup without hiding errors
For SQLite, with conn: manages a transaction; it does not close the connection. Explicit connection ownership remains necessary.
Do not treat a printed “closed” message as sufficient evidence. The lifecycle demonstration later attempts a query after closure and expects sqlite3.ProgrammingError. Its evidence marker is written only after that assertion succeeds. Avoid swallowing cleanup exceptions with except Exception: pass: a green test body must not conceal a broken teardown.
Choose Explicit Fixtures, usefixtures, or autouse
Request a value or activate setup-only behavior
An explicit parameter exposes a fixture value. usefixtures activates setup without injecting that value into the test body. Apply this marker to tests or test classes; when a fixture needs another fixture, declare the dependency in its signature.
Copy now, complete file: examples/test_activation.py
import os
import pytest
@pytest.fixture
def configured_env(monkeypatch):
monkeypatch.setenv("WAREHOUSE", "test")
return "test"
def test_explicit_value(configured_env):
assert os.environ["WAREHOUSE"] == configured_env
@pytest.mark.usefixtures("configured_env")
def test_setup_only():
assert os.environ["WAREHOUSE"] == "test"
The first test uses the returned value. The second checks the environment side effect. They illustrate different needs rather than two mandatory ways to write every test.
Keep autouse behavior narrow and predictable
An autouse fixture is automatically activated for tests that can see it. Keep broad side effects out of a top-level conftest.py unless every affected test genuinely needs them.
Copy now, complete file: examples/test_autouse.py
import os
import pytest
@pytest.fixture(autouse=True)
def test_warehouse(monkeypatch):
monkeypatch.setenv("WAREHOUSE", "test")
def test_uses_module_default():
assert os.environ["WAREHOUSE"] == "test"
This fixture affects the tests in that module, not the unrelated environment-negative tests elsewhere. monkeypatch restores its environment modification afterward. Prefer an explicit fixture when the dependency is important for understanding an individual test.
| S. No | Activation | Fixture value available directly? | Recommended use |
|---|---|---|---|
| 1 | Test parameter | Yes | A test uses the resource or configuration |
| 2 | usefixtures | No | A test needs a setup side effect only |
| 3 | autouse=True | Only if also explicitly requested | A narrowly scoped, universal test prerequisite |
Parametrize Fixtures and Build Test-Data Factories
Use fixture parameters, request.param, and readable IDs
A fixture supplies context; parametrization varies test cases. For shared resource variants, use fixture parameters. The complete db fixture runs against memory and temporary-file SQLite databases. Conceptual excerpt, requires tests/conftest.py:
@pytest.fixture(params=["memory", "file"], ids=["memory", "file"])
The full fixture appears below. It reads the current variant from request.param. Each dependent test runs for each fixture variant; explicit IDs make the selected resource visible in collected test names.
Two database modes combined with three quantities produce six invocations of test_add_and_read. To inspect this after creating the complete application files, run:
Command, complete project required:
python -m pytest --collect-only -q tests/test_inventory.py::test_add_and_read
Captured node IDs from the release v2 run:
tests/test_inventory.py::test_add_and_read[memory-zero] tests/test_inventory.py::test_add_and_read[memory-one] tests/test_inventory.py::test_add_and_read[memory-ten] tests/test_inventory.py::test_add_and_read[file-zero] tests/test_inventory.py::test_add_and_read[file-one] tests/test_inventory.py::test_add_and_read[file-ten]
Each bracketed ID combines a resource mode and a quantity label. These six lines are an excerpt of the captured collection report; the timing line is omitted because this is not a benchmark.
Choose direct or indirect parametrization
Conceptual excerpt, requires the complete SQLite example. Direct parametrization sends input values straight to the test:
@pytest.mark.parametrize("quantity", [0, 1, 10], ids=["zero", "one", "ten"])
def test_add_and_read(inventory, quantity):
inventory.add("SKU-1", quantity)
assert inventory.quantity("SKU-1") == quantity
assert inventory.count() == 1
Conceptual excerpt, same prerequisites. Indirect parametrization sends a value through the db fixture before the test receives the connection:
@pytest.mark.parametrize("db", ["file"], indirect=True, ids=["file-only"])
def test_file_backed_database(db):
databases = db.execute("PRAGMA database_list").fetchall()
assert databases[0][2].endswith("inventory.sqlite3")
Without indirect=True, the test would receive the string "file" instead of the fixture-created connection. Resource construction remains in fixture setup.
Parameter objects are passed as supplied, not automatically copied. Avoid sharing one mutable dictionary across cases and assuming that parametrization isolates its mutations. Prefer immutable parameters or construct fresh data within a fixture.
| S. No | Task | Choose | Why |
|---|---|---|---|
| 1 | Vary ordinary inputs | @pytest.mark.parametrize | The test receives values such as quantities directly. |
| 2 | Configure a resource | Fixture params, or indirect parametrization | The fixture turns a mode or configuration into a usable resource. |
| 3 | Create several records in one test | Factory fixture | Call the returned builder repeatedly for independent objects. |
Create several independent objects with a factory fixture
A factory fixture returns a callable rather than one finished record. Conceptual excerpt, copied from the complete tests/conftest.py: each call below returns a fresh dictionary.
@pytest.fixture
def record_factory():
def make_record(sku: str, quantity: int = 0) -> dict:
return {"sku": sku, "quantity": quantity}
return make_record
The factory test creates two records, mutates the first, and checks that the second remains unchanged. It then persists both through the repository. This particular factory owns only dictionaries; the database fixture still owns persistence cleanup. For a factory that creates external resources, design cleanup for every successfully created resource, including partial-batch failures.
Use Built-in pytest Fixtures for Isolation and Evidence
Use tmp_path and tmp_path_factory
tmp_path supplies a pathlib.Path unique to a test invocation. tmp_path_factory is session-scoped and can create broader-lived temporary directories. Temporary-path isolation does not mean immediate deletion: pytest’s retention settings can preserve files from recent runs. Never put credentials in test artifacts or point --basetemp at a directory containing valuable files.
One file, shown in three labeled parts: examples/test_builtins.py. Copy all three parts into that file once. Part 1 (imports, shared seed, and private-copy test):
import logging
import os
import pytest
LOGGER = logging.getLogger("inventory.demo")
@pytest.fixture(scope="session")
def shared_seed_file(tmp_path_factory):
path = tmp_path_factory.mktemp("seed") / "stock.csv"
path.write_text("sku,quantity\nSKU-1,5\n", encoding="utf-8")
return path
def test_private_file_copy(shared_seed_file, tmp_path):
local = tmp_path / "stock.csv"
local.write_bytes(shared_seed_file.read_bytes())
assert local.read_text(encoding="utf-8").splitlines()[1] == "SKU-1,5"
local.write_text("changed", encoding="utf-8")
assert "SKU-1,5" in shared_seed_file.read_text(encoding="utf-8")
Treat the shared seed as read-only by convention, not as filesystem-enforced protection. The test mutates its private copy and asserts that the seed retains its content. This is the intended reuse/isolation boundary.
Control configuration with monkeypatch
Part 2, append to examples/test_builtins.py. The helper rejects missing configuration; both the negative and positive paths are explicit:
def warehouse_from_env() -> str:
value = os.getenv("WAREHOUSE")
if not value:
raise ValueError("WAREHOUSE is required")
return value
def test_missing_configuration(monkeypatch):
monkeypatch.delenv("WAREHOUSE", raising=False)
with pytest.raises(ValueError, match="WAREHOUSE is required"):
warehouse_from_env()
def test_environment_configuration(monkeypatch):
monkeypatch.setenv("WAREHOUSE", "test")
assert warehouse_from_env() == "test"
delenv(..., raising=False) makes the negative case independent of whether the developer already has that variable set. The positive case supplies a known value. pytest reverses monkeypatch-managed changes during cleanup.
Assert output and logs with capsys and caplog
Use capsys for Python sys.stdout/sys.stderr, capfd when output is written to file descriptors 1 and 2 (for example, by native code or subprocesses), and caplog for logging records. Set the relevant log level explicitly.
Part 3, append to examples/test_builtins.py. This uses the imports and LOGGER declaration from Part 1:
def report_stock(sku: str, quantity: int) -> None:
print(f"{sku}: {quantity}")
LOGGER.info("stock_reported sku=%s quantity=%s", sku, quantity)
def test_output_and_log(capsys, caplog):
with caplog.at_level(logging.INFO, logger="inventory.demo"):
report_stock("SKU-1", 5)
captured = capsys.readouterr()
assert captured.out == "SKU-1: 5\n"
assert captured.err == ""
assert (
"inventory.demo", logging.INFO,
"stock_reported sku=SKU-1 quantity=5",
) in caplog.record_tuples
This checks the exact console output, absence of stderr, logger name, level, and message. It is more informative than checking only whether a string appeared somewhere in a combined log file. Avoid logging secrets or personal data merely to make tests easier to assert.
Build a Complete SQLite Fixture Example
Connect the application, fixtures, and tests
The minimum application uses the files below. Earlier conceptual excerpts become complete here; avoid pasting both copies into the same module. Open the complete release v2 archive or its source index.
pytest-fixtures-walkthrough-v2/
inventory.py
pytest.ini
tests/
conftest.py
test_inventory.py
The release also contains every earlier teaching test, failure demonstrations, both verification tools, dependency pins, and captured evidence. Run commands from the project root with python -m pytest; that invocation adds the current directory to Python’s import path.
Copy now, complete file: inventory.py
import sqlite3
MAX_QUANTITY = (1 << 63) - 1
def create_schema(conn: sqlite3.Connection) -> None:
conn.execute(
"CREATE TABLE inventory ("
"sku TEXT PRIMARY KEY NOT NULL, "
"quantity INTEGER NOT NULL CHECK(quantity >= 0))"
)
conn.commit()
class Inventory:
def __init__(self, conn: sqlite3.Connection) -> None:
self.conn = conn
def add(self, sku: str, quantity: int) -> None:
if not isinstance(sku, str) or not sku.strip():
raise ValueError("sku must be a non-empty string")
if type(quantity) is not int or not 0 <= quantity <= MAX_QUANTITY:
raise ValueError(
f"quantity must be a non-negative integer <= {MAX_QUANTITY}"
)
with self.conn:
self.conn.execute(
"INSERT INTO inventory VALUES (?, ?)",
(sku, quantity),
)
def quantity(self, sku: str) -> int:
row = self.conn.execute(
"SELECT quantity FROM inventory WHERE sku = ?",
(sku,),
).fetchone()
if row is None:
raise KeyError(sku)
return row[0]
def count(self) -> int:
return self.conn.execute(
"SELECT COUNT(*) FROM inventory"
).fetchone()[0]
Input contract: sku must be a non-empty string. quantity must be a built-in integer from 0 through 9,223,372,036,854,775,807, inclusive (2**63 - 1 is the maximum); booleans and floats are rejected. Larger integers raise ValueError before SQL executes, rather than leaking a binding OverflowError. The range matches the non-negative portion of SQLite’s signed 64-bit INTEGER domain. Bound parameters remain in use.
Transaction baseline: The Python 3.10-compatible connect(..., isolation_level="DEFERRED") call is retained. In the executed Python 3.13 environment it uses default legacy transaction control; on Python 3.12+, isolation_level has effect only with autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL. The autocommit keyword was added in 3.12, so do not add it while promising 3.10-compatible syntax. Python recommends autocommit for new code targeting newer versions; choose and retest that policy deliberately. The connection context manager manages each write transaction, not connection closure.
Copy now, complete file: tests/conftest.py
import sqlite3
import pytest
from inventory import Inventory, create_schema
@pytest.fixture(params=["memory", "file"], ids=["memory", "file"])
def db(request, tmp_path):
if request.param == "memory":
target = ":memory:"
elif request.param == "file":
target = str(tmp_path / "inventory.sqlite3")
else:
raise ValueError(f"Unknown database mode: {request.param}")
conn = sqlite3.connect(target, isolation_level="DEFERRED")
try:
create_schema(conn)
yield conn
finally:
conn.close()
@pytest.fixture
def inventory(db):
return Inventory(db)
@pytest.fixture
def record_factory():
def make_record(sku: str, quantity: int = 0) -> dict:
return {"sku": sku, "quantity": quantity}
return make_record
Setup follows tmp_path → db → inventory; teardown releases dependents before dependencies. The repository borrows the connection; db closes it. Temporary-path retention is managed separately by pytest and does not imply immediate deletion. Every test case receives a new connection and schema; file mode uses its own directory.
Copy now, complete file: pytest.ini
[pytest] testpaths = tests examples addopts = -ra
The default command collects the passing test directories. Run intentional failure files only through their dedicated commands or verification harness.
Test successful operations, invalid inputs, and boundaries
Copy now, complete file: tests/test_inventory.py
import sqlite3
import pytest
from inventory import MAX_QUANTITY
@pytest.mark.parametrize("quantity", [0, 1, 10], ids=["zero", "one", "ten"])
def test_add_and_read(inventory, quantity):
inventory.add("SKU-1", quantity)
assert inventory.quantity("SKU-1") == quantity
assert inventory.count() == 1
def test_maximum_quantity_round_trips(inventory):
inventory.add("SKU-MAX", MAX_QUANTITY)
assert inventory.quantity("SKU-MAX") == MAX_QUANTITY
assert inventory.count() == 1
def test_quantity_above_maximum_does_not_write(inventory):
with pytest.raises(ValueError, match="non-negative integer"):
inventory.add("SKU-OVER", MAX_QUANTITY + 1)
assert inventory.count() == 0
def test_duplicate_does_not_overwrite(inventory):
inventory.add("SKU-1", 4)
with pytest.raises(sqlite3.IntegrityError):
inventory.add("SKU-1", 99)
assert inventory.quantity("SKU-1") == 4
inventory.add("SKU-2", 2)
assert inventory.count() == 2
@pytest.mark.parametrize("quantity", [-1, True, 1.5])
def test_invalid_quantity_does_not_write(inventory, quantity):
with pytest.raises(ValueError, match="non-negative integer"):
inventory.add("SKU-1", quantity)
assert inventory.count() == 0
@pytest.mark.parametrize("sku", ["", " ", None])
def test_invalid_sku_does_not_write(inventory, sku):
with pytest.raises(ValueError, match="non-empty string"):
inventory.add(sku, 1)
assert inventory.count() == 0
def test_missing_record(inventory):
with pytest.raises(KeyError, match="missing"):
inventory.quantity("missing")
@pytest.mark.parametrize("attempt", [1, 2], ids=["first", "second"])
def test_each_case_starts_empty(inventory, attempt):
assert inventory.count() == 0
inventory.add("same-sku", attempt)
assert inventory.quantity("same-sku") == attempt
def test_independent_factory_records(inventory, record_factory):
first = record_factory("SKU-A", 2)
second = record_factory("SKU-B", 3)
first["quantity"] = 9
assert second["quantity"] == 3
assert first is not second
inventory.add(**first)
inventory.add(**second)
assert inventory.quantity("SKU-A") == 9
assert inventory.quantity("SKU-B") == 3
@pytest.mark.parametrize("db", ["file"], indirect=True, ids=["file-only"])
def test_file_backed_database(db):
databases = db.execute("PRAGMA database_list").fetchall()
assert databases[0][2].endswith("inventory.sqlite3")
Run the complete repository example:
python -m pytest -q tests
The revised application run produced 33 passing cases. The maximum quantity round-trips; the first out-of-range value raises ValueError and leaves the database empty. Both checks run in memory and file mode. The duplicate test verifies that a rejected insert preserves existing data and that another insert succeeds afterward. Inspect the captured application report.
The repeated isolation test deliberately reuses "same-sku" across separate cases. Each case first asserts an empty database; it does not depend on another test running first. The factory test asserts both object independence and persisted values.
The verification matrix in the setup section defines the execution boundary. Concurrency, lock timeouts, production integration, and other database engines need separate tests when they are relevant to your application.
Verify lifecycle behavior and failure evidence
Intentional failure, complete file: fault_demos/test_lifecycle.py
import os
import sqlite3
from pathlib import Path
import pytest
@pytest.fixture(params=["pass", "assertion", "setup"])
def resource(request):
evidence = Path(os.environ["FIXTURE_EVIDENCE"])
conn = sqlite3.connect(":memory:")
try:
if request.param == "setup":
raise RuntimeError("injected setup failure")
yield conn, request.param
finally:
conn.close()
with pytest.raises(sqlite3.ProgrammingError):
conn.execute("SELECT 1")
evidence.write_text("closed", encoding="utf-8")
def test_resource(resource):
conn, mode = resource
assert mode != "assertion", "injected assertion failure"
assert conn.execute("SELECT 1").fetchone() == (1,)
FIXTURE_EVIDENCE is an output-file path supplied by tools/verify_lifecycle.py. Run the command below instead of collecting this file as part of the passing suite. The harness starts each case in a fresh child process, checks exit status and JUnit phase, then inspects a fresh closure marker. It also checks the separate finalizer-failure example and scope mismatch.
python tools/verify_lifecycle.py
| S. No | Scenario and precondition | Action | Expected result | Evidence checked |
|---|---|---|---|---|
| 1 | Normal setup | Query the live connection | Test passes; connection closes | Exit 0 and closure assertion marker |
| 2 | Live fixture, failing test | Trigger the assertion failure | Test fails; teardown still closes | Exit 1, failure report, closure marker |
| 3 | Connection acquired, not yet yielded | Raise during setup | Setup error; test body does not run | Exit 1, error report, closure marker |
| 4 | Finalizer already registered | Raise during later initialization | Finalizer closes the resource | Separate error report and closure marker |
| 5 | Invalid scope dependency | Request session fixture using function fixture | Setup rejected | ScopeMismatch in the report |
All five lifecycle/diagnostic checks matched their expected outcomes. One child passes; the intentional assertion failure and three setup/scope errors remain negative outcomes. The harness succeeds only when those phases and cleanup evidence match. Inspect the lifecycle record.
Across the application and tutorial examples, 47 cases passed. The same 47 passed with warnings treated as errors and with collected node IDs reversed. To reproduce collection, all runs, diagnostic commands, and lifecycle checks without overwriting the supplied record, use tools/verify_all.py:
Command (writes a separate local-run report directory):
python tools/verify_all.py
The captured record is in evidence/captured-2026-11-29/; a new run defaults to evidence/local-run/. Reversed order is one deterministic order check, not a randomized-order or parallel guarantee. The manifest verifier checks file integrity without executing tests.
Optional exercise: Change the quantity IDs to more descriptive labels, run the six-case collection command again, and confirm that only identifiers change, not case count or assertions. Keep your exercise run separate from the supplied evidence.
Debug Fixture Failures and Prepare for Parallel Runs
Inspect discovery, dependencies, and setup
Use a specific test file to keep the output readable:
python -m pytest --fixtures tests/test_inventory.py python -m pytest --fixtures-per-test tests/test_inventory.py python -m pytest --setup-plan tests/test_inventory.py python -m pytest --setup-show -q tests/test_inventory.py
--fixtures lists available fixtures; --fixtures-per-test shows dependencies by test. --setup-plan plans fixture/test execution without running their bodies. --setup-show executes tests while showing lifecycle activity. Collection still imports test modules, so a planning command is not a sandbox for import-time side effects.
When investigating contamination, compare a failing test alone with the same test in its larger suite. Record the test node ID, resource variant, dependency trace, and setup/call/teardown phase before changing scopes.
Diagnose common fixture errors
| S. No | Symptom | First checks | Corrective direction |
|---|---|---|---|
| 1 | Fixture not found | Name, test location, applicable conftest.py, required plugin | Fix discovery rather than importing unrelated test modules |
| 2 | ScopeMismatch | Consumer and dependency lifetimes | Narrow the consumer or redesign resource ownership |
| 3 | Fixture called directly | Calls such as db() | Request the fixture; extract an ordinary helper when needed |
| 4 | Passes alone, fails in suite | Shared mutable state, environment leakage, reused identifiers | Recreate or explicitly reset owned state |
| 5 | Setup error rather than failed assertion | Fixture traceback and prerequisite availability | Fix initialization before diagnosing feature behavior |
| 6 | Teardown error | Cleanup traceback and resource ownership | Preserve the error; repair cleanup instead of suppressing it |
Why is my fixture not found? pytest could not resolve the requested name in the test’s accessible fixture set. Check the spelling, directory visibility, applicable conftest.py, and any required plugin before changing imports or scope.
Direct fixture calls are unsupported; missing fixtures and scope mismatches are handled by pytest’s fixture machinery. The other rows are diagnostic recommendations, not assertions that every similar symptom has the same cause.
Understand session scope under pytest-xdist
With pytest-xdist, different workers can instantiate their own session-scoped fixtures. Session scope does not mean “exactly once across every worker.” The plugin exposes identifiers such as worker_id and testrun_uid for coordinating or distinguishing resources.
For shared external services, consider names containing a run identifier, worker identifier, and test-specific component. Do not let one worker’s cleanup delete another worker’s records. Resource names alone do not create isolation: verify permissions, ownership, and deletion boundaries too.
Prefer independent resources where practical. A genuinely shared one-time setup needs explicit cross-process coordination and recovery; changing the scope string is not enough. The versions-used matrix marks this parallel guidance as documentation-reviewed, not executed.
pytest Fixtures Design Checklist
| S. No | Area | Checks before adoption |
|---|---|---|
| 1 | Dependencies | Can readers see what each test needs? Is setup order expressed by dependencies? |
| 2 | State | Is mutable state isolated? Is every broader scope justified by a real reuse need? |
| 3 | Cleanup | Does every acquired resource have an owner? Are assertion-failure and partial-setup cleanup verified? |
| 4 | Execution | Do assertions check behavior and recovery? Can tests run alone and in another order? For workers, are resource and deletion boundaries explicit? |
Conclusion
Start with small, function-scoped pytest fixtures. Introduce broader scope, automatic activation, or factory patterns when they solve a specific problem, and keep the resulting dependencies visible. Well-designed pytest fixtures make every test’s prerequisites, lifetimes, and cleanup responsibilities explicit. Choose scope deliberately, keep mutable state isolated, verify teardown after failures, and confirm parallel behavior before relying on it. As a software testing company, Codoid applies these same patterns when building Python test suites for API and backend testing and long-running QA outsourcing engagements.
For framework selection, see Pytest BDD vs Behave: Pick the Best Python BDD Framework. As an optional application of fixture/resource ownership in mobile automation, see Appium Hybrid App Testing: WebViews, Permissions, and Context Switching. These related articles are not pytest API authorities. Run the complete fixture example: Open companion release v2, follow README.md, then run python tools/verify_all.py. Inspect your own environment, test outcomes, and cleanup evidence before adapting the pattern.
Struggling with flaky Python tests? Let our experts build reliable pytest fixtures
Talk to a QA ExpertFrequently Asked Questions
-
What are pytest fixtures used for?
pytest fixtures supply the data, configuration, or resources a test needs, such as a database connection or a configured environment. A test requests a fixture by name, and pytest resolves its dependencies, provides its value, and manages its setup and cleanup.
-
What is the difference between a pytest fixture and a helper function?
Use a fixture when pytest should manage availability, dependencies, reuse, or cleanup. Use an ordinary helper for a calculation or transformation with no test lifecycle to manage. Never call a fixture directly as a function; request it as a test parameter instead.
-
What is the default scope of pytest fixtures?
The default scope is function, which means a new fixture instance is created for each test. You can also choose class, module, package, or session scope. Pick a broader scope only when you need to reuse something expensive, and keep mutable test data isolated per test.
-
Where should I put shared pytest fixtures?
Place shared fixtures in a conftest.py file. Tests in that directory and its subdirectories can use them without importing them. Moving a fixture into conftest.py changes where it is visible, not how long it lives; that still depends on its scope.
-
What is the difference between yield and return in pytest fixtures?
Use return when the fixture provides a value that needs no cleanup. Use yield when setup acquires a resource, such as a database connection, that must be released afterward. pytest runs the code after yield during teardown, even when the test assertion fails.
-
When should I use autouse fixtures?
Use autouse=True only for narrowly scoped prerequisites that every affected test needs. Avoid broad autouse fixtures in a top-level conftest.py, because they hide dependencies. Prefer an explicit fixture parameter when the dependency matters for understanding the test.
-
How can I see which fixtures a test uses?
Run python -m pytest --fixtures-per-test to see each test's fixture dependencies. Use --setup-plan to preview the fixture execution plan, or --setup-show to watch setup and teardown while the tests run.








Comments(0)