1. Home
  2. Blog
  3. Test Automation

Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

A pytest conftest.py file shares fixtures, hooks and custom options with every test in its directory, with no imports. Learn how discovery works, fixture scope and teardown, overriding fixtures per folder, autouse fixtures, custom command-line options and markers, and how to keep conftest files tidy, with a suite we ran.

9 min read
Pytest conftest.py explained: shared fixtures, hooks and overrides

Key takeaways

  • A pytest conftest file makes its fixtures and hooks available to every test in the same directory and below, with no import statement.
  • Nested conftest.py files can override a parent fixture by defining the same name; the closest one wins.
  • Hooks such as pytest_addoption and pytest_configure add command-line options and markers for the whole suite.
  • Our 6-test suite ran in 0.02 s, and --setup-show confirmed the session database opened once and closed once.

As a test suite grows, the same setup appears in many files: a database connection, a logged-in API client, a temporary directory, test users. Copying it is fragile, and importing fixtures between test modules gets messy. A pytest conftest file solves that: it is a plugin local to a directory, and pytest loads it automatically.

We built a small suite and ran it with Python 3.13.6 and pytest 9.2.0; every output below is from those runs. If fixtures themselves are new, read our pytest fixtures guide first.

What is conftest.py in pytest?

conftest.py is a special file name. When pytest collects tests, it loads every conftest.py on the path from the root directory down to each test file, before importing the tests. Everything defined there, fixtures, hooks and plugin registrations, applies to that directory and all subdirectories. There can be one per directory, and they stack.

Our project layout

tests/
  conftest.py          # shared: env option, db, clean_db, base_url, user, marker
  unit/
    test_users.py
  api/
    conftest.py        # API-only: overrides user, adds autouse api_headers
    test_orders.py

Running the whole suite:

pytest -q tests
6 passed in 0.02s

Sharing fixtures across files

# tests/conftest.py
import pytest, sqlite3

@pytest.fixture
def user():
    return {"name": "asha", "role": "viewer"}

# tests/unit/test_users.py
def test_user_role(user):
    assert user["role"] == "viewer"

The test file has no import, yet user is available. pytest matches the argument name with a fixture it found in a visible conftest.py. That keeps test files focused on behaviour and puts setup in one place.

Scope and teardown with yield

@pytest.fixture(scope="session")
def db():
    print("\n[session] open db")
    con = sqlite3.connect(":memory:")
    con.execute("CREATE TABLE users(name TEXT)")
    yield con
    print("\n[session] close db")
    con.close()

Code before yield is setup; code after is teardown, which runs even if tests fail. With scope="session" the database is created once for the whole run. --setup-show made the lifetimes visible:

SETUP    S db
        SETUP    F clean_db (fixtures used: db)
        TEARDOWN F clean_db
        SETUP    F clean_db (fixtures used: db)
        TEARDOWN F clean_db
        SETUP    F user
        TEARDOWN F user
TEARDOWN S db

S marks session scope and F function scope. The expensive connection was opened once, while the cheap per-test fixtures were recreated for each test. Other scopes are class, module and package. Under parallel runs with pytest-xdist, “session” means once per worker.

Fixtures that use other fixtures

@pytest.fixture
def clean_db(db):
    db.execute("DELETE FROM users")
    return db

def test_insert(clean_db):
    clean_db.execute("INSERT INTO users VALUES ('asha')")
    assert clean_db.execute("SELECT COUNT(*) FROM users").fetchone()[0] == 1

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

A function-scoped fixture can depend on a session-scoped one. Here every test shares one connection but starts with an empty table, so test_isolated passes regardless of what test_insert did. This is the standard pattern for fast yet independent database tests. The reverse is not allowed: a session fixture cannot request a function fixture, and pytest reports a ScopeMismatch error.

Overriding fixtures per folder

# tests/api/conftest.py
@pytest.fixture
def user():
    return {"name": "api-bot", "role": "admin"}

# tests/api/test_orders.py
def test_override(user):
    assert user["role"] == "admin"

Both conftest files define user. Tests under tests/api receive the admin version, while tests/unit still gets the viewer; both tests passed. pytest searches from the test file outwards and uses the closest definition. Use this to swap behaviour for one area, for example a different base URL or a mocked service for integration tests, without touching the rest of the suite.

Autouse fixtures

# tests/api/conftest.py
@pytest.fixture(autouse=True)
def api_headers(request):
    request.node.headers = {"Accept": "application/json"}

autouse=True runs the fixture for every test in scope without anyone requesting it. Here every API test got default headers, which test_slow_report asserted. Autouse is ideal for global guards, such as blocking real network calls with monkeypatch or resetting a cache, but keep autouse fixtures few and cheap, because they run everywhere and are invisible in test signatures.

Tip: put autouse fixtures in the most specific conftest that needs them. An autouse fixture in the root conftest affects every single test.

Adding custom command-line options

# tests/conftest.py
def pytest_addoption(parser):
    parser.addoption("--env", default="local", help="target environment")

@pytest.fixture(scope="session")
def env(request):
    return request.config.getoption("--env")

@pytest.fixture
def base_url(env):
    return {"local": "http://localhost:8000",
            "staging": "https://staging.example.com"}[env]
pytest -q tests --env staging -k base_url
1 passed, 5 deselected in 0.09s

pytest_addoption is a hook: pytest calls it at start-up so you can add options. A fixture then reads the value, and every test that needs a URL just asks for base_url. The same suite can now run against local, staging or a review app from CI. Note that option hooks belong in the root conftest, or a plugin, so they load before command-line parsing; values like these often come from environment variables too.

Registering custom markers

def pytest_configure(config):
    config.addinivalue_line("markers", "slow: marks tests as slow")

@pytest.mark.slow
def test_slow_report(base_url, request):
    assert request.node.headers["Accept"] == "application/json"
pytest -q tests -m "not slow"
5 passed, 1 deselected in 0.02s

Registering markers in pytest_configure documents them and avoids “unknown marker” warnings; with --strict-markers, unregistered markers become errors, which catches typos. Our pytest markers guide covers selection expressions in depth.

Other useful conftest hooks

Hook Use it to
pytest_addoption Add command-line options
pytest_configure Register markers, set up global state
pytest_collection_modifyitems Reorder, skip or mark collected tests
pytest_runtest_makereport Attach screenshots or logs to failures
pytest_sessionfinish Write summaries or clean up after the run
pytest_generate_tests Parametrize tests dynamically

Only the first two were run in our suite; the rest are documented hooks you will often see in larger projects. Dynamic parametrization is an alternative to pytest.mark.parametrize when values come from files or options.

Finding where a fixture comes from

pytest tests --fixtures
------------------- fixtures defined from conftest -------------------
db [session scope] -- tests\conftest.py:13
clean_db -- tests\conftest.py:22
base_url -- tests\conftest.py:27
user -- tests\conftest.py:31
env [session scope] -- tests\conftest.py:9
user -- tests\api\conftest.py:3
api_headers -- tests\api\conftest.py:7

--fixtures lists every available fixture with its file, line and scope, including both versions of user. Add -v to see private fixtures too. When a test receives an unexpected value, this is the fastest way to find which conftest supplied it.

Do not import from conftest.py

In our run, from conftest import user inside a test file actually worked, because pytest had put the tests directory on sys.path. It is still a bad idea: it depends on import mode and directory layout, it imports the fixture function rather than letting pytest manage it, and with several conftest.py files the name is ambiguous. If you need shared helper functions, put them in a normal module, such as tests/helpers.py, and import that.

Organising conftest files

  • Keep the root conftest for truly global things: options, markers, core fixtures.
  • Put area-specific fixtures in that area’s conftest, such as tests/api/conftest.py.
  • Keep narrow fixtures that one module uses in that test module.
  • When a conftest grows large, move fixtures into modules and load them with pytest_plugins = ["tests.fixtures.db"] in the root conftest.
  • Give fixtures descriptive names and docstrings; --fixtures shows the docstrings.

Common conftest mistakes

  • A misspelled file name such as conftests.py, which pytest silently ignores.
  • Expensive work in function-scoped fixtures that should be session-scoped.
  • Session fixtures that keep mutable state between tests without a reset step.
  • Too many autouse fixtures, making tests slow and hard to understand.
  • Defining pytest_addoption in a nested conftest, where it may load too late.
  • Turning conftest into a dumping ground for unrelated helpers.

Final thoughts

A pytest conftest file is the backbone of a maintainable test suite. It shares fixtures without imports, controls their lifetime with scopes and yield teardown, lets subfolders override behaviour, and hosts hooks for options and markers. Keep each conftest focused on its directory, check sources with --fixtures and --setup-show, and your tests stay short while the setup stays in one place. For API suites built on these ideas, see API testing with Python.

Frequently asked questions

What is conftest.py used for in pytest?

It holds fixtures, hooks and plugin settings that pytest loads automatically for every test in the same directory and its subdirectories, so tests can use them without imports.

Can I have multiple conftest.py files?

Yes. Each directory can have its own conftest.py. They stack from the root down, and a fixture defined closer to a test overrides one with the same name defined higher up.

Do I need to import fixtures from conftest.py?

No. pytest discovers conftest fixtures automatically by name. Importing them is discouraged; put shared helper functions in a normal module instead.

Where should conftest.py be located?

Put shared fixtures in the root of your tests directory and area specific fixtures in a conftest.py inside that subfolder. Command line option hooks belong in the root conftest.

How do I add a custom command line option to pytest?

Define the pytest_addoption hook in the root conftest.py and call parser.addoption, then read the value in a fixture with request.config.getoption.

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

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
Software Development

301 vs 302 Redirect: Differences, SEO Impact, 307 and 308

301 vs 302 redirect: the differences, SEO impact, 307 and 308, method changes, redirect chains and loops, all tested on…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Databases & SQL

SQL Random Rows: How to Select Random Rows Fast and Fairly

SQL random rows: how to select random rows fast and fairly, timing ORDER BY RANDOM, offsets and ID jumps, and…

Read article →
Databases & SQL

SQL Median: 4 Ways to Calculate the Median, With Tested Queries

SQL median explained: four tested ways to calculate the median, including percentile functions, window ranks, offsets and per group medians.

Read article →
Software Development

JavaScript Regex Explained: Patterns, Flags, Groups and Pitfalls

JavaScript regex explained: literals, flags, groups, named groups, lookarounds, matchAll, replace and the catastrophic backtracking trap, tested in Node.

Read article →
Software Development

Python property: Getters, Setters, Validation and cached_property

Python property explained: getters, setters, deleters, validation, read-only and computed attributes, and cached_property, with tested code.

Read article →
Software Development

Python Enum Explained: auto, IntEnum, StrEnum, Flag and Best Practices

Python enum explained with tested examples: Enum, auto, IntEnum, StrEnum, Flag, aliases, unique, JSON serialisation and match statements.

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
Software Development

401 vs 403: Unauthorized vs Forbidden, and When to Use Each

401 vs 403 explained: authentication vs authorization, the WWW-Authenticate header, when to return 404 instead, client reactions and a tested…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →
Databases & SQL

SQL ROUND Function: Decimals, Ties, CEIL, FLOOR and Money

SQL ROUND explained with tested queries: decimals, tie rules, the 2.675 float trap, negative digits, CEIL, FLOOR, truncation and rounding…

Read article →
Databases & SQL

Recursive CTE in SQL: Hierarchies, Paths, Series and Cycles

Recursive CTE in SQL explained with tested queries: org charts with levels and paths, walking up a tree, team sizes,…

Read article →
Software Development

JavaScript Deep Copy: structuredClone vs JSON vs Spread, Tested

JavaScript deep copy compared: spread, Object.assign, the JSON trick, structuredClone and a custom copy, tested on Dates, Maps, Sets, BigInt…

Read article →
Artificial Intelligence

K Means Clustering Explained: How It Works, With Python Code

K means clustering explained: the algorithm, a from-scratch NumPy version, choosing k with the elbow and silhouette methods, k-means++, scaling…

Read article →
DevOps

Git Log Explained: 15 Useful Commands and Pretty Formats

Git log explained with 15 tested commands: oneline, graph, filters by author, date, message and code, file history, stats, pretty…

Read article →
Test Automation

Pytest conftest.py Explained: Shared Fixtures, Hooks and Overrides

Pytest conftest.py explained with a tested suite: shared fixtures, scope and teardown, folder overrides, autouse, custom options, markers and useful…

Read article →
Software Testing

Usability Testing: Methods, Metrics, SUS Score and Checklist

Usability testing explained: methods, planning, writing tasks, running sessions, metrics, SUS scoring, how many users you need and a practical…

Read article →
Databases & SQL

SQL UPDATE Statement: Safe Updates, UPDATE With JOIN and RETURNING

The SQL UPDATE statement explained with tested examples: WHERE guards, CASE updates, UPDATE with JOIN, the subquery NULL trap, RETURNING…

Read article →
Databases & SQL

SQL COUNT: COUNT(*) vs COUNT(column) vs COUNT(DISTINCT) Explained

SQL COUNT explained: COUNT(*) vs COUNT(column) vs COUNT(DISTINCT), NULLs and empty strings, conditional counts, HAVING, the LEFT JOIN trap and…

Read article →
Artificial Intelligence

K Nearest Neighbors (KNN) Explained: How It Works, With Python Code

K nearest neighbors explained: the KNN algorithm, a from-scratch NumPy version, choosing k, feature scaling, distance metrics, regression and vector…

Read article →
DevOps

Git Rebase Interactive: Squash, Fixup, Reword and Autosquash

Git rebase interactive explained step by step: pick, reword, squash, fixup, edit, drop, autosquash, conflicts and undoing a rebase with…

Read article →
Software Testing

Alpha vs Beta Testing: Key Differences, Exit Criteria and Checklist

Alpha vs beta testing compared: who tests, what each phase finds, entry and exit criteria, how to run a beta,…

Read article →
Test Automation

Pytest Monkeypatch: 10 Tested Examples for Env Vars, Time and APIs

Pytest monkeypatch explained with 10 passing tests: environment variables, functions, config, time, sleeps, paths, blocking the network and the wrong-target…

Read article →
Artificial Intelligence

Softmax Function Explained: Formula, Python Code and Stable Version

The softmax function explained: formula, worked example, NumPy code, the stable version that avoids NaN, temperature, cross-entropy and softmax vs…

Read article →
DevOps

Git Diff Explained: Staged Changes, Branches and Commits

Git diff explained: read the output, compare unstaged and staged changes, commits and branches, two dots vs three dots, and…

Read article →
Test Automation

Pytest Xdist: Run Tests in Parallel and Cut Test Time

Run pytest tests in parallel with pytest-xdist: install, the -n option, distribution modes, real timings and how to fix shared-state…

Read article →
Software Testing

Verification vs Validation in Software Testing: Example and Table

Verification vs validation in software testing explained with a comparison table and a tested coupon example where every spec test…

Read article →
Artificial Intelligence

Levenshtein Distance: Formula, Worked Table and Python Code

Levenshtein distance explained: the edit operations, the dynamic programming table for kitten and sitting, Python code with two-row memory, normalised…

Read article →
DevOps

Gitignore: Patterns, Negation and Fixing Tracked Files

A tested gitignore guide: pattern rules, leading and trailing slashes, negation with !, the ignored parent folder trap, git check-ignore…

Read article →
Software Testing

Acceptance Criteria: Given When Then Examples and Checklist

How to write acceptance criteria testers can run: rule-based and Given When Then formats, a worked discount code example turned…

Read article →
Test Automation

Python Unittest: Assert Methods, setUp and Mocks With Examples

A practical Python unittest tutorial: TestCase, assert methods, setUp and tearDown, subTest, skips, expected failures and mock, with a test…

Read article →