Reliable Python tests do more than confirm that code works today: they make future changes safer to review, debug, and release. This pytest tutorial presents a reusable workflow for organizing tests, designing fixtures, covering edge cases, mocking external services, isolating database checks, and investigating failures without turning the test suite into a maintenance burden.
Overview
pytest is a practical choice for Python testing because it supports plain test functions, readable assertions, reusable fixtures, parametrized cases, and a broad plugin ecosystem. A maintainable suite begins with a clear testing boundary: test business rules directly, replace slow or unreliable dependencies at unit-test level, and reserve integration tests for the points where components must work together.
A simple project layout might look like this:
project/
├── app/
│ ├── pricing.py
│ └── client.py
├── tests/
│ ├── conftest.py
│ ├── test_pricing.py
│ └── test_client.py
├── pyproject.toml
└── requirements-dev.txtUse names beginning with test_ for test files and functions so pytest can discover them using its normal conventions. Keep tests close to the behavior they verify, but avoid copying production implementation details into every assertion. A good test describes an input, an expected result, and the reason that result matters.
For a larger development workflow, pair this local suite with a repeatable CI process. The GitHub Actions CI troubleshooting guide can help when a passing local test behaves differently in an automated job.
Checklist by scenario
1. Writing a focused unit test
- Identify one behavior rather than testing an entire module at once.
- Use descriptive names such as
test_discount_is_not_applied_to_expired_coupon. - Arrange the input, act by calling the function, and assert the observable result.
- Check error type and, when useful, an important part of the error message.
- Avoid assertions about private implementation details unless they are part of a deliberate contract.
from app.pricing import total_after_discount
def test_discount_is_applied_to_eligible_order():
result = total_after_discount(total=100, discount_percent=20)
assert result == 80
def test_negative_discount_is_rejected():
with pytest.raises(ValueError, match="discount"):
total_after_discount(total=100, discount_percent=-5)Import pytest when using its helpers:
import pytest2. Building reusable fixtures
Fixtures provide setup data or resources to tests. Start with the smallest useful fixture and give it a meaningful name. A fixture should make a test easier to read, not hide important behavior behind several layers of indirection.
import pytest
@pytest.fixture
def valid_user():
return {"id": 7, "email": "user@example.test", "active": True}
def test_active_user_can_log_in(valid_user):
assert valid_user["active"] is TrueUse yield when a fixture needs teardown:
@pytest.fixture
def temporary_setting(tmp_path):
path = tmp_path / "settings.txt"
path.write_text("mode=test")
yield path
if path.exists():
path.unlink()Choose fixture scope deliberately. Wider scopes can reduce repeated setup, but they may also increase coupling between tests or preserve state longer than intended.
| Scope | Typical use | Double-check |
|---|---|---|
function | Fresh data for each test; the safest default | Setup cost is acceptable |
class | Shared setup for tests in one test class | Tests do not mutate shared state |
module | Expensive resource shared by one test module | Cleanup and ordering are predictable |
session | Environment-level resources shared by a test run | Parallel or isolated runs will not conflict |
3. Covering edge cases with parametrization
Parametrization is useful when the same rule should be checked against several inputs. It keeps cases visible and avoids a long sequence of nearly identical test functions.
import pytest
@pytest.mark.parametrize(
("value", "expected"),
[
("", False),
("abc", True),
(" ", False),
],
)
def test_is_nonempty_text(value, expected):
assert is_nonempty_text(value) is expectedInclude boundary values, invalid types where the public API permits them, empty collections, duplicate values, and time-related boundaries. Give complex cases an id so a failure is easy to identify. Do not add cases merely to increase the count; each case should represent a meaningful rule or risk.
4. Mocking external services
Mock an external dependency when the test should focus on your code rather than a network, payment provider, clock, filesystem, or third-party API. Patch the name used by the module under test, not automatically the name where the dependency was originally defined.
from unittest.mock import Mock
def test_fetch_profile_returns_api_data():
api = Mock()
api.get_profile.return_value = {"name": "Ada"}
result = load_profile(api, user_id=3)
assert result["name"] == "Ada"
api.get_profile.assert_called_once_with(3)Use mocks to verify important collaboration, such as whether a dependency was called with the correct identifier. Avoid asserting every internal call when the same result could be tested through a stable public behavior. Excessive mocking can make tests pass while the real integration is broken, so retain a smaller set of integration tests for critical boundaries. For HTTP-specific cases, compare this approach with the reusable scenarios in the REST API testing guide.
5. Isolating database tests
- Use a temporary database or transaction strategy for tests that exercise persistence.
- Build only the records needed by the scenario.
- Clean up after each test unless the fixture explicitly owns a wider lifecycle.
- Keep pure validation and transformation tests independent of the database.
- Test constraints, transactions, migrations, and query behavior at the integration level rather than pretending they are pure unit tests.
When a query fails, inspect joins, null handling, aggregates, and returned rows separately. The SQL query debugging guide is a useful companion for that investigation.
6. Running coverage and the suite
Run the focused test first, then the relevant module, and finally the complete suite:
python -m pytest tests/test_pricing.py -q
python -m pytest tests/ -q
python -m pytest --cov=app --cov-report=term-missingCoverage reports show which lines or branches were exercised; they do not prove that the assertions are meaningful. Use missing-line output as a review prompt. Ask whether an uncovered path is important, deliberately unreachable, or better tested through an integration scenario. Avoid setting a target that encourages trivial assertions or tests written only to satisfy a number.
What to double-check
Before merging a test change, use this review list:
- Test isolation: Does the test pass alone, in a different order, and after the full suite?
- Determinism: Does it depend on the current time, random output, machine locale, environment variables, network access, or file ordering?
- Fixture ownership: Is setup and cleanup located in the fixture that creates the resource?
- Failure clarity: Does a failure identify the input and expected behavior without requiring a debugger?
- Mock boundary: Is the patched object the one actually looked up by the code under test?
- Async behavior: If the code is asynchronous, are async tests, fixtures, and mocks configured consistently with the project’s test setup?
- Compatibility: Do the pytest version, plugins, Python version, and coverage commands match the project’s supported environment?
- CI parity: Does the command run with the same environment assumptions locally and in continuous integration?
A compact failure-triage template can keep debugging objective: failure: what failed; input: which case triggered it; boundary: which dependency or layer is involved; first check: what changed most recently; reproduction: the smallest command that still fails; resolution: code fix, test correction, fixture correction, or environment fix.
Common mistakes
- One giant fixture: A fixture that creates users, database rows, clients, and configuration for every test makes dependencies difficult to see. Split it into composable fixtures.
- Shared mutable data: Reusing a list or dictionary across tests can leak mutations. Return fresh values or reset state explicitly.
- Testing the mock: Assertions that only confirm a mock returned its configured value provide little confidence. Assert the behavior produced by the system under test.
- Overusing snapshots or exact messages: Exact representations can make harmless formatting changes break many tests. Assert the contract that users or callers rely on.
- Ignoring negative paths: Happy-path tests rarely cover malformed input, missing records, permission failures, timeouts, or retries.
- Chasing coverage alone: More executed lines do not automatically mean better protection against regressions.
- Mixing test layers: A unit test that quietly calls a live service is slow and fragile. Mark or organize integration tests so their requirements are explicit.
- Leaving flaky tests unresolved: Rerunning until a test passes hides reliability problems. Find the uncontrolled clock, ordering, concurrency, resource, or environment dependency.
When to revisit
Use this checklist whenever you add a feature, fix a regression, refactor shared fixtures, change a database schema, introduce an external service, or prepare a release test run. Revisit the suite before seasonal planning cycles if your team uses those checkpoints, and whenever the Python version, pytest syntax, plugin set, async approach, or coverage command changes.
A practical maintenance routine is to review test duration and flaky failures during normal pull-request work, audit fixture scopes when setup becomes slow, and inspect coverage gaps after meaningful behavior changes. Refresh this guide and your project’s test instructions roughly every six months, or sooner after a major tool release or workflow change. Record the supported commands in the repository so a new contributor can run the same focused, full-suite, and coverage checks without guessing.
Finally, treat tests as executable documentation. Before opening a pull request, add or update the smallest test that captures the intended behavior, run it in isolation, run the relevant test group, then run the full suite and coverage command. For broader engineering review habits, pair this process with the Git branching and pull request workflow checklist.