1. Home
  2. Blog
  3. Test Automation

Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

Fixtures are how pytest prepares what a test needs and cleans up afterwards. Learn how they are found, how scope changes when they run, and the patterns that keep a growing suite fast and isolated.

9 min read
pytest fixtures explained: scope, yield teardown, conftest.py and factories

Key takeaways

  • A fixture is a function marked with @pytest.fixture that a test requests by naming it as a parameter.
  • Code after yield is teardown, and it runs even when the test fails.
  • Scope controls reuse: function (default), class, module, package or session.
  • Put shared fixtures in conftest.py, and use --setup-show to see exactly when each one runs.

Every test needs some setup: a database connection, a logged-in user, a temporary folder. Copying that setup into each test makes a suite long and fragile. pytest fixtures solve this with a simple idea. You write the setup once as a function, and any test that names it as a parameter receives the result.

We built a small suite and ran it with pytest 9.2 on Python 3.13. All outputs below come from that run. If pytest itself is new to you, start with our pytest tutorial.

What is a fixture?

A fixture provides a known, consistent starting point for a test. In pytest, it is a function decorated with @pytest.fixture. When pytest sees a test with a parameter called db, it looks for a fixture with that name, runs it, and passes in the value. This is a form of dependency injection, and fixtures can themselves request other fixtures.

Your first fixture

import pytest, sqlite3

@pytest.fixture
def db():
    conn = sqlite3.connect(":memory:")
    conn.execute("CREATE TABLE users (name TEXT)")
    return conn

def test_isolated(db):
    assert db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 0

The test never calls db() itself. pytest does that, and by default it creates a fresh value for every test function, so one test’s data cannot leak into another.

Teardown with yield

Most resources need cleaning up. Replace return with yield, and everything after it becomes teardown:

@pytest.fixture
def db(db_engine):
    conn = sqlite3.connect(":memory:")
    conn.execute("CREATE TABLE users (name TEXT)")
    print("[setup] fresh db")
    yield conn
    conn.close()
    print("[teardown] closed db")

We added a test that fails on purpose, assert 1 == 2, and ran the suite with -s to show the prints. The output for that test was:

[setup] fresh db
F
[teardown] closed db

The connection was closed even though the test failed. That guarantee is why yield fixtures are better than putting cleanup at the end of the test body, where a failing assert would skip it. If setup raises an exception before reaching yield, the teardown does not run, so keep setup steps small or nest fixtures so each one cleans up its own resource.

Fixture scope

Some setup is expensive, such as starting a browser, creating a database schema or launching a container. Scope lets pytest reuse one fixture value across many tests:

Scope Created once per Typical use
function (default) Test Anything tests might change
class Test class Shared state within a class
module Test file A file’s worth of related tests
package Test package A folder of tests
session Whole test run Expensive, read-only resources
@pytest.fixture(scope="session")
def db_engine():
    print("[setup] session engine")
    yield "engine"
    print("[teardown] session engine")

In our run, “session engine” was set up once at the start and torn down once at the very end, while the function-scoped db was created and closed around each test. One rule applies: a fixture can only request fixtures of the same or a wider scope. A session fixture cannot use a function fixture, because the function fixture would be gone before the session ends.

Tip: Wide scopes make suites faster but risk shared state. If a session-scoped object can be changed by tests, one test can break another, and failures will depend on test order. That is a common cause of flaky tests. Keep wide-scoped fixtures read-only, or reset them between tests.

Watching fixtures run

The --setup-show option prints each fixture’s setup and teardown. For two of our tests it showed:

SETUP    S db_engine
        SETUP    F db (fixtures used: db_engine)
        SETUP    F make_user (fixtures used: db)
        tests/test_users.py::test_add_user (fixtures used: db, db_engine, make_user) .
        TEARDOWN F make_user
        TEARDOWN F db
        SETUP    F db (fixtures used: db_engine)
        tests/test_users.py::test_isolated (fixtures used: db, db_engine) .
        TEARDOWN F db
TEARDOWN S db_engine

S marks session scope and F marks function scope. You can see the dependency chain, the reverse order of teardown, and the fresh db for each test. When a suite behaves strangely, this is the first view to check.

Sharing fixtures with conftest.py

Fixtures defined in a test file are available only in that file. Move them into a file named conftest.py, and every test in that folder and its subfolders can use them without importing anything. pytest discovers the file automatically.

tests/
  conftest.py          # db_engine, db, make_user
  test_users.py
  api/
    conftest.py        # fixtures only for API tests
    test_orders.py

A nested conftest.py can add fixtures for its folder or override a parent fixture with the same name. Run pytest --fixtures to list every fixture available and where it is defined. In our project it listed db, db_engine and make_user from tests\conftest.py, alongside the built-ins.

Factory fixtures

Sometimes a test needs several users, or users with different data. Instead of one fixture per variation, return a function:

@pytest.fixture
def make_user(db):
    def _make(name="Asha"):
        db.execute("INSERT INTO users VALUES (?)", (name,))
        return name
    return _make

def test_add_user(db, make_user):
    make_user("Ben")
    assert db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 1

The test decides how many records it needs and with what values, while the fixture still owns the details of creating them. Factories keep test data next to the test that depends on it, which makes failures easier to understand.

Parametrized fixtures

@pytest.fixture(params=["sqlite", "postgres"])
def backend(request):
    return request.param

def test_backend(backend):
    assert backend in {"sqlite", "postgres"}

Every test that uses backend runs once per parameter, so this one test counted as two passes in our results. In a real suite, the fixture would create a connection for each database, letting the same tests check both. Use @pytest.mark.parametrize on the test instead when only the input data changes.

Built-in fixtures

Fixture What it gives you
tmp_path A unique temporary folder as a pathlib.Path
monkeypatch Safe, auto-undone changes to environment variables, attributes and dicts
capsys Captured stdout and stderr
caplog Captured log records
request Information about the requesting test, including parameters
def test_tmp_path(tmp_path):
    f = tmp_path / "report.txt"
    f.write_text("ok")
    assert f.read_text() == "ok"

def test_env(monkeypatch):
    monkeypatch.setenv("APP_MODE", "test")
    assert os.environ["APP_MODE"] == "test"

Both passed, and pytest cleaned up the folder and restored the environment afterwards. monkeypatch pairs well with our guides to environment variables and mocking in Python.

Errors and debugging

A misspelt fixture name is reported as an error at setup, not a test failure:

def test_typo(dbb):
    pass

E       fixture 'dbb' not found
>       available fixtures: backend, capfd, ..., db, db_engine, ..., make_user, monkeypatch, ...

pytest helpfully lists every available name. Our final summary read 1 failed, 6 passed, 1 error: the deliberate assertion failure, six passing tests (including both backend runs), and the missing-fixture error.

Best practices

  • Name fixtures after what they provide, such as admin_user or empty_cart, not setup1.
  • Keep each fixture small and compose them, rather than one giant fixture that sets up everything.
  • Default to function scope and widen only for measured, expensive setup.
  • Always clean up with yield, even for things you think are harmless.
  • Use autouse=True sparingly. Fixtures that run invisibly make tests harder to understand.
  • Avoid hidden data. If a test’s assertion depends on a value, it should be visible in the test or passed to a factory.

Fixtures vs setUp and tearDown methods

If you come from unittest, JUnit or NUnit, you know setup and teardown methods that run around every test in a class. pytest still supports that style, but fixtures have clear advantages:

setUp / tearDown pytest fixtures
What runs Everything in setUp, for every test Only the fixtures a test asks for
Sharing Through class inheritance By name, through conftest.py
Reuse across scopes Separate class-level methods One scope argument
Composition Hard to mix and match Fixtures request other fixtures
Visibility Hidden in the class Listed in the test’s parameters

The biggest win is explicitness. Reading def test_checkout(logged_in_user, cart_with_items) tells you exactly what state the test starts from. With a setUp method, you have to scroll up and read it to find out, and every test pays for every step, even ones it does not need.

Two smaller tools are worth knowing. @pytest.mark.usefixtures("clean_cache") applies a fixture to a test or class when the test does not need its return value. And request.addfinalizer(func) registers cleanup from inside a fixture, which is useful when a fixture creates several resources and needs to register cleanup for each one as it goes.

Final thoughts

Fixtures turn repeated setup into small, named, reusable building blocks. Start with function-scoped yield fixtures in conftest.py, add factories when tests need varied data, and widen scope only where speed demands it. When in doubt, run --setup-show and watch what really happens.

Frequently asked questions

What is a fixture in pytest?

A fixture is a function decorated with @pytest.fixture that prepares something a test needs. A test requests it by using the fixture’s name as a parameter.

What is the default fixture scope?

Function scope. A new value is created for each test. Other scopes are class, module, package and session.

Does teardown run if a test fails?

Yes. Code after yield in a fixture runs even when the test fails. In our run, the database was closed after a failing test.

What is conftest.py used for?

It holds fixtures and hooks shared by all tests in its folder and subfolders. pytest loads it automatically, so no import is needed.

How do I see which fixtures a test uses?

Run pytest with –setup-show to see setup and teardown order, or pytest –fixtures to list all available fixtures.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →