- Learn
- Computer Science & IT
- Programming
- Intermediate Python
- Testing with pytest
Testing with pytest
assert statements, run them and read the report, and check that code raises the errors it should. Organize a growing test suite, share setup with fixtures, run one test over many inputs with parametrization, and replace slow or unpredictable dependencies with mocks. Finally, measure line and branch coverage, judge what a coverage figure really shows, and use test-driven development to add small features and fix bugs.IntermediateLesson 6 of 9 in Intermediate Python Course
What you will learn
- Turn expected behavior into test functions with plain
assertstatements, run them with pytest, read its report, and check that code raises the errors it promises.- Write test functions with assertWrite small test functions that call your code with chosen inputs and check the result with plain
assertstatements, including results that are floating-point numbers. - Run pytest and read its reportRun the whole test suite or chosen tests from the command line, read the progress line, failure details and summary, and use options that help you find and fix a failure quickly.
- Check that code raises the right exceptionsUse
pytest.raisesto check that invalid input raises the expected exception type and message, and inspect the exception object when the details matter.
- Write test functions with assert
- Arrange test files next to the code they test, configure pytest in one place, keep tests independent, and group, label and select tests so the suite stays easy to run as it grows.
- Lay out test files and configure pytestPut tests in a
testsfolder beside the code, make the code importable from the tests, keep settings in one configuration file and write tests that do not depend on each other. - Group, mark and select testsGroup related tests in classes, label tests with markers, skip tests or mark expected failures with a reason, and run only the subset you need.
- Lay out test files and configure pytest
- Use fixtures to give each test the data and objects it needs, clean up after tests, choose how widely a fixture is shared, and use pytest's built-in fixtures for files, output and logs.
- Create and request fixturesWrite fixture functions that build test data or objects, request them by name in tests, combine them, and share them through
conftest.py. - Clean up with yield and choose a fixture scopeWrite fixtures that tidy up after the test with
yield, and decide whether a fixture is created for each test or shared by a class, module or whole test session. - Use pytest's built-in fixturesRequest pytest's own fixtures to work with temporary files, captured printed output and log messages instead of writing that setup yourself.
- Create and request fixtures
- Run one test function over a table of inputs and expected results, give each case a readable ID, and combine parametrization with marks and fixtures.
- Run one test over many inputsUse
@pytest.mark.parametrizeto turn one test function into a separate test for each row of inputs and expected results, and choose rows that check every rule in the code. - Combine parametrization with marks and fixturesMark single cases with
pytest.param, test error cases in a table, and parametrize fixtures so the same tests run against several implementations.
- Run one test over many inputs
- Test code that depends on networks, clocks, environment settings or other slow or unpredictable parts by replacing those parts with stand-ins the test controls, and check how the code used them.
- Isolate code from its dependenciesRecognize dependencies that make tests slow or unreliable, replace them for one test with
monkeypatch, or design code so a test can pass a stand-in directly. - Create and check mock objectsUse
MockandMagicMockfromunittest.mockto stand in for objects, set their return values and side effects, check the calls they received and limit them to the real interface with a spec. - Patch the right name and mock with careUse
patchand themockerfixture to replace objects for one test, patch the name where the code looks it up, and keep mocks to the boundaries of the code.
- Isolate code from its dependencies
- Measure which lines and branches the tests run, judge what a coverage figure does and does not show, and use the red–green–refactor cycle of test-driven development to build small features and fix bugs.
- Measure line and branch coverageUse coverage.py through the
pytest-covplugin to see which lines and branches the tests ran, read its report, and set a minimum the suite must reach. - Judge what coverage showsUse coverage to find untested code, recognize why a high percentage does not prove the tests are good, and choose a sensible target.
- Follow the red–green–refactor cycleDevelop code test-first in small steps: write a failing test, make it pass with the simplest code, then improve the code while every test stays green.
- Apply test-driven development to features and bug fixesUse the cycle together with fixtures, parametrization and test doubles to add a small feature to existing code, and fix bugs by first writing a test that reproduces them.
- Measure line and branch coverage
Testing with pytest study guide
1Write and run tests with pytest
An automated test is an executable statement about behavior. You will write small checks, use their failure reports to find disagreements, and run selected tests while fixing code. Returned values are only part of a function's contract: invalid inputs may need to raise a particular exception. The examples move from a simple word counter to score validation, showing how to check both ordinary results and expected errors.
1.1 Write test functions with assert
A test turns a promise about your code into a check you can run after every edit. A unit test checks a small piece, often one function or method. Repeating these checks catches regressions, when a change breaks behavior that previously worked.
Write an expectation
Install pytest in your project's virtual environment with pip install pytest. Put tests in a file such as test_text_tools.py. A test is an ordinary function with a name beginning with test; it needs no class. Import the code you are testing. Import pytest itself only when you use one of its features.
from text_tools import word_count
def test_counts_three_words():
assert word_count("the cat sat") == 3
The assertion says exactly what the function should return. A false assertion raises AssertionError, which pytest reports as a failure. A test passes when its body finishes without a failed assertion or other unexpected exception. Simply calling the function checks that it runs, but leaves its returned value unchecked.
Arrange–Act–Assert gives a test a readable shape: prepare inputs, call the code, and check the result. Short tests can combine the call and assertion as above. Name each test for the behavior it checks, so the name also explains a failure.
Use a failure to find the bug
Suppose the implementation is:
def word_count(text):
return len(text.split(" "))
The three-word test passes. Add this independent behavior:
def test_empty_string_has_no_words():
assert word_count("") == 0
It fails because "".split(" ") produces ['']: one empty item. pytest rewrites assertions in test files and conftest.py, so the report shows the compared values, here assert 1 == 0. For collections it can also show differing items. Fix the behavior with return len(text.split()). With no separator argument, split() returns an empty list for an empty string and handles repeated whitespace.
Compare the right things
Work expected values out independently. A literal expected area of 12 is easier to audit than copying the production formula into the assertion. If both copies contain the same mistaken rule, they can agree while both are wrong. For singleton values, write checks such as assert result is None.
Binary floating point cannot represent most decimal fractions exactly: 0.1 + 0.2 is 0.30000000000000004. Use a tolerance for results where that small representation difference is acceptable:
import pytest
def test_adds_decimal_values():
assert 0.1 + 0.2 == pytest.approx(0.3)
By default, approx allows a relative tolerance of 1e-6, with an absolute tolerance of 1e-12 near zero. Set rel= or abs= when the calculation needs a different tolerance. It also compares lists and dictionaries of numbers.
Keep an assertion message outside the tested expression: assert count == 3, "wrong count". Writing assert (count == 3, "wrong count") instead creates a nonempty tuple. That tuple is truthy even when the comparison inside it is false, so the check cannot detect the wrong count.
Key Takeaways
- Name each test after one behavior and assert on its outcome.
- Read pytest's compared values to locate the disagreement.
- Work expected results out independently of the implementation.
- Use
pytest.approxfor floating-point comparisons that need a tolerance. - Write
assert condition, "message"without turning the condition into a tuple.
1.2 Run pytest and read its report
Running tests is a short feedback loop: collect the checks, read the first useful failure, make a small change, and rerun. The report tells you both what happened and how much of the suite actually ran.
Collect the tests
Run pytest or python -m pytest from the project folder. With no path argument, pytest searches configured testpaths, or otherwise the current folder and its subfolders. It collects test_*.py and *_test.py files, functions beginning with test, and test methods inside classes beginning with Test. Such classes must have no __init__ method.
The header identifies the Python and pytest versions, rootdir, chosen configuration file, and number of collected items. Check that number. If two functions in a file have the same name, Python replaces the first definition with the second before collection. The run can look successful while one intended test never ran.
Read outcomes and failures
| Symbol | Outcome |
|---|---|
. | Passed |
F | Failed in the test body |
E | Error in setup or teardown |
s | Skipped |
x | Expected failure occurred |
X | Expected failure unexpectedly passed |
An unexpected TypeError in a test body is a failure, just like an assertion failure. A fixture that cannot prepare an object produces an error. An import problem during collection normally interrupts the run before tests execute.
For a failure, start near the bottom of its block. Read the exception, compared values, and file and line number. The > marker points to the failing source line. Lines beginning with E inside this block show exception details; that letter there is formatting, not a separate setup-error outcome. A summary such as 2 failed, 5 passed counts the final results.
Select a useful rerun
A node ID names a specific test:
tests/test_text_tools.py::test_empty_string_has_no_words
tests/test_tasks.py::TestTaskList::test_add
Pass a folder, file, or node ID after pytest. Quote a parametrized node ID containing square brackets, because shells may interpret them. While fixing a failure, use a narrow selection; run the full suite again before finishing.
| Option | Effect |
|---|---|
-v / -q | More detail / less output |
-x / --maxfail=2 | Stop after one / two failures or errors |
-k "word and not empty" | Match names with a case-insensitive expression |
--lf / --ff | Run last failures only / first |
--co | List collected tests without running them |
-l / --tb=short | Show local variables / shorter tracebacks |
-ra | Summarize all outcomes other than passes |
--pdb | Open a debugger at a failure |
pytest normally captures printed output and shows it for failing tests. Use -s to see prints live while investigating; silence from a passing test does not mean its print was skipped.
Check the process result
The exit code lets another program recognize the outcome: 0 means success, 1 test failures, 2 interruption such as a collection error, 3 an internal pytest error, 4 a command-line usage error, and 5 no tests collected. With code 5, check discovery names first: tests_text.py and check_count miss the default patterns. A green-looking terminal is useful only when the intended tests were collected.
Key Takeaways
- Check collection counts as well as the final pass count.
- Distinguish a test-body failure from a setup or teardown error.
- Use a node ID or
--lffor a focused rerun, then run the full suite. - Use
--coto investigate discovery and-sto see prints live. - Exit code 5 means no tests were collected; it is not a successful test run.
- Read the exception and compared values before changing code.
1.3 Check that code raises the right exceptions
Invalid input has expected behavior too. A function may promise to reject an out-of-range value with a particular exception. A good test checks that rejection just as directly as it checks a returned result.
Expect a specific exception
This function rejects scores outside its valid range:
def grade(score):
if score < 0 or score > 100:
raise ValueError("score must be between 0 and 100")
if score >= 90:
return "A"
if score >= 75:
return "B"
return "C"
Use pytest.raises as a context manager around the operation that should fail:
import pytest
from grades import grade
def test_rejects_score_above_100():
with pytest.raises(ValueError):
grade(101)
The test passes when the call raises ValueError or a subclass. If it returns normally, pytest fails the test with DID NOT RAISE. A different exception, such as TypeError, escapes the context manager and fails the test. Use the most specific promised type. Catching Exception could let a programming error satisfy a test intended to check input validation.
Check the message and details
match= searches the message with a regular expression. A meaningful fragment is often enough:
def test_rejection_explains_the_range():
with pytest.raises(ValueError, match="between 0 and 100"):
grade(-1)
Regex punctuation matters. The pattern "price (in cents)" treats parentheses as grouping syntax, so it does not search for literal parentheses. For literal text, use match=re.escape("price (in cents)") after import re. Anchors such as ^ and $ can constrain a regex match; a plain fragment need not match the entire message.
To inspect the actual exception, save excinfo:
def test_rejection_message_is_exact():
with pytest.raises(ValueError) as excinfo:
grade(-1)
assert str(excinfo.value) == "score must be between 0 and 100"
After the block, excinfo.value holds the exception object and excinfo.type holds its class. Custom attributes can be checked here too, for example an error's numeric code.
Keep the block narrow
Put setup before with. Keep only the operation expected to raise inside it. If setup inside the block raises the same type accidentally, the test can pass without reaching the intended operation. Once an exception occurs, later lines in that block are skipped. Assertions on excinfo therefore belong after the block, dedented.
A try block with except ValueError: pass has a different weakness: it also finishes successfully when nothing raises. It needs an explicit failure path to detect missing validation. pytest.raises supplies that check. To test valid input, call the function and check its result normally: assert grade(100) == "A"; an unexpected exception already fails that test.
Warnings have a parallel tool. Use with pytest.warns(DeprecationWarning, match="use load_v2"): around a call expected to issue that warning. This checks the warning category and a matching message while allowing the function to continue.
Key Takeaways
- Use
pytest.raiseswith the specific promised exception type. match=is a regex search, so escape punctuation when matching literal text.- Keep only the raising operation inside the block; inspect
excinfo.valueafterward. - Use normal result assertions for valid inputs and
pytest.warnsfor expected warnings.
2Organize a test suite
A test suite stays useful when its files, imports, and settings are easy to understand. You will place tests beside an importable application package, share setup through pytest's discovery rules, and keep each test independent. Classes and markers then help group and select behavior without making tests depend on one another. Skips and expected failures record specific limitations while keeping the report informative.
2.1 Lay out test files and configure pytest
A growing suite needs a predictable home and a repeatable way to import application code. Its tests also need to work separately: selecting one test should not remove setup that another test happened to provide.
Give code and tests separate homes
A common src layout is:
project/
pyproject.toml
src/
shop/
__init__.py
grades.py
tasks.py
tests/
conftest.py
test_grades.py
test_tasks.py
Tests import the package normally, for example from shop.grades import grade. With a package configured for installation, pip install -e . installs the project in editable mode in the active virtual environment. Another option is adding src to pytest's pythonpath setting. A flat layout puts shop/ directly in the project folder.
python -m pytest adds the current folder to Python's import path. Plain pytest does not make that same addition. This can explain why a flat project imports successfully with one command and reports ModuleNotFoundError with the other. The reported rootdir organizes the run; it is not itself an instruction to make the application importable.
Keep settings together
Use one configuration file. This table in pyproject.toml works with pytest 7, 8, and 9:
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-ra --strict-markers"
markers = ["slow: tests that take more than a second"]
testpaths controls the default search locations, pythonpath adds import locations, and addopts supplies options for every run. pytest 9 also supports [tool.pytest] with native TOML values, such as a list for addopts. Choose one table, not both. pytest chooses one configuration file and does not merge settings; pytest.ini takes precedence over pyproject.toml. In pytest 9, a pytest.toml file takes still higher precedence. Check the configuration file named in the report header when a setting seems ignored.
Share fixtures through discovery
pytest automatically loads conftest.py. Fixtures in tests/conftest.py are available to tests in that folder and below it, without importing that file. A deeper folder can have its own conftest.py for local fixtures. Keep ordinary application helpers in normal modules; conftest.py is pytest's shared setup location.
The default prepend import mode can expose duplicate test-file names. Files in folders without __init__.py are imported by bare module name, so two files called test_utils.py can clash. Packaged test folders get full package names. Distinct file names, package folders with __init__.py, or --import-mode=importlib solve the clash; pytest recommends importlib mode for new projects.
Make every test self-sufficient
A module-level list that one test modifies leaks state into later tests. The suite may pass together and fail under -k, or pass individually and fail together. Give each test fresh mutable state, usually with a function-scoped fixture. Tests should pass alone, in a group, in any order, and on repeated runs. File order is not a substitute for explicit setup.
Key Takeaways
- Make the application importable through installation or an explicit path setting.
- Check the chosen configuration file; pytest does not merge configuration files.
- Share fixtures with
conftest.pywithout importing it into tests. - Use unique test module names, package folders, or importlib mode to avoid name clashes.
- Create fresh mutable state so tests pass independently.
2.2 Group, mark and select tests
Grouping and labeling help you run the right tests without changing their meaning. A class collects related behaviors; a marker adds information that pytest can use for selection or reporting.
Group related tests
A pytest test class begins with Test, needs no base class, and must not define __init__. Each test method takes self and can request fixtures as further parameters:
class TestTaskList:
def test_new_list_has_no_pending_tasks(self):
assert TaskList().pending() == []
def test_added_task_is_pending(self):
tasks = TaskList()
tasks.add("book room")
assert tasks.pending() == ["book room"]
pytest creates a fresh class instance for each test method. An attribute assigned to self in one method does not set up another method. A class with an __init__ constructor is not collected as an ordinary pytest test class.
Mark and select
Attach a custom label with @pytest.mark.slow. Register it under markers in the configuration. An unknown marker normally produces a warning; --strict-markers turns a typo into an error. Put that option in addopts to enforce it on every run. pytest 9 also accepts strict_markers = true and a broader strict setting; use the command-line option for compatibility with pytest 7 and 8.
pytest -m "not slow" selects tests by marker. In a suite of 40 tests with 3 slow tests, it runs 37 and reports 3 as deselected. -k instead matches broader name keywords, including file and class names and marker names. Use -m when selection should depend specifically on markers. Both support expressions with and, or, and not, but a marker label and a name fragment are different selection inputs.
A class decorator marks every method. At module level, pytestmark = pytest.mark.slow marks every test in the file. Run pytest --markers to inspect registered and built-in markers.
Distinguish skipping from expected failure
| Tool | When to use it | What runs |
|---|---|---|
skip | A test cannot usefully run here | No test body |
skipif(condition, reason=...) | A known condition prevents a useful run | Body runs only when the condition is false |
xfail(reason=...) | A known defect is expected to fail | Body normally runs |
For example, a platform-dependent test can use skipif(sys.platform == "win32", reason="uses POSIX file permissions"). Inside a test, pytest.skip("reason") stops it with a skipped outcome. pytest.importorskip("numpy") skips when an optional module cannot be imported. -rs shows skip reasons.
An ordinary xfail reports x if the test fails and X if it unexpectedly passes. Neither outcome fails the run by default. Use @pytest.mark.xfail(strict=True, reason="known rounding bug") to make an unexpected pass fail the run; the suite then calls attention to a marker that may need removal. The configuration setting xfail_strict = true applies that policy by default.
A skip is not a repair for failing behavior. Give each skip or xfail a reason that explains the actual limitation or known defect, and review it when circumstances change.
Key Takeaways
- Test classes group behaviors; each test method gets a new instance.
- Register custom markers and use
--strict-markersto catch typos. -mselects marker expressions;-kmatches broader name keywords, including marker-name keywords.- Skip when a test cannot run usefully; xfail when it should run against a known defect.
- A strict xfail turns an unexpected pass into a failure that needs review.
3Share setup with fixtures
Tests often need the same starting data, an open resource, or a place to write a temporary file. Fixtures prepare these things and let tests request them by name. You will build fresh objects, connect related setup, and keep cleanup next to resource creation. Choosing a lifetime controls whether data is recreated or shared. Built-in fixtures handle common file, print, and logging checks with little setup code.
3.1 Create and request fixtures
A fixture prepares something a test needs: data, an object, or a resource in a known state. It puts reusable arrange steps in one place while keeping the test focused on behavior.
Request setup by name
Use this small class for the examples:
class TaskList:
def __init__(self):
self._tasks = {}
def add(self, title):
self._tasks[title] = False
def complete(self, title):
if title not in self._tasks:
raise KeyError(title)
self._tasks[title] = True
def pending(self):
return [t for t, done in self._tasks.items() if not done]
A fixture is a function marked with @pytest.fixture. The test requests its value through a parameter with the same name:
import pytest
@pytest.fixture
def tasks():
task_list = TaskList()
task_list.add("write report")
task_list.add("book room")
return task_list
def test_completed_task_is_no_longer_pending(tasks):
tasks.complete("book room")
assert tasks.pending() == ["write report"]
pytest sees tasks in the test's parameter list, runs the fixture, and supplies the returned object. The test does not call tasks(). Inside the test, tasks already names the TaskList, not the fixture function.
Keep tests independent
The default scope is one test function. A second test requesting tasks receives a newly prepared list with both tasks pending. Completing a task in the first test cannot change the second test's starting state.
A fixture can request another fixture through its own parameters:
@pytest.fixture
def finished_tasks(tasks):
tasks.complete("write report")
return tasks
Within one test, pytest caches a requested fixture's value. If the test requests both tasks and finished_tasks, they share the same TaskList: one request does not create a second copy. This is useful for related setup, but the mutation in finished_tasks is visible through both names.
Return a factory for flexible data
A factory fixture returns a function that builds objects using values the test chooses:
@pytest.fixture
def make_task_list():
def make(*titles):
task_list = TaskList()
for title in titles:
task_list.add(title)
return task_list
return make
def test_builds_two_independent_lists(make_task_list):
first = make_task_list("draft")
second = make_task_list("review")
first.complete("draft")
assert second.pending() == ["review"]
Here the test calls the returned factory, which is an ordinary function. Each call creates a distinct object. This is different from directly calling a decorated fixture.
Put shared setup where pytest finds it
Use tests/conftest.py for fixtures shared across test files. A same-named fixture in a test file or deeper conftest.py overrides the outer fixture locally. pytest --fixtures lists available fixtures; --setup-show displays setup and teardown.
A misspelled parameter produces a fixture-not-found error before the test runs. A fixture missing its return supplies None. Keep one-off values in the test when that is clearer, and avoid long fixture chains that hide the starting state.
Key Takeaways
- Request a fixture through a parameter with the fixture's name.
- Function-scoped fixtures give separate tests fresh state.
- Repeated requests within one test share the cached fixture value.
- A factory fixture returns an ordinary callable for building several objects.
- Use local overrides when a group of tests needs different setup.
- Diagnose fixture names and missing return values before changing application code.
3.2 Clean up with yield and choose a fixture scope
Some setup creates resources that need cleanup. A yield fixture keeps their creation and cleanup together, and a fixture's scope controls how long one prepared resource is shared.
Clean up after a test
A temporary in-memory database can be a fixture:
import sqlite3
import pytest
@pytest.fixture
def db():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE tasks (title TEXT, done INTEGER)")
yield conn
conn.close()
def test_insert_task(db):
db.execute("INSERT INTO tasks VALUES ('book room', 0)")
assert db.execute("SELECT COUNT(*) FROM tasks").fetchone() == (1,)
Setup runs before yield. The yielded connection goes to the test. After the test finishes, pytest resumes the fixture and closes the connection, even if the test failed an assertion. Cleanup at the end of a test body would be skipped after a failure.
If setup raises before reaching yield, the test body does not run and that fixture's post-yield cleanup does not run. Design setup so resources are not left open when a later setup operation can fail. request.addfinalizer(function) is another way to register cleanup; a yield fixture is the usual readable starting point.
When fixtures depend on each other, pytest cleans them up in reverse setup order. A fixture is torn down before the fixtures it used, so a resource it depends on remains available during its cleanup.
Choose the lifetime
| Scope | Shared within |
|---|---|
function | One test; the default |
class | One test class |
module | One test module |
package | One test package |
session | The whole run |
Write @pytest.fixture(scope="module") to share an instance through a module. It is created when first needed and cleaned up at the end of that scope. Five tests using a function-scoped reference file load it five times. A module-scoped version loads it once for those tests and closes it once. --setup-show marks these lifetimes with letters such as F and M.
Balance speed with fresh state
A shared reference dataset can save time. A shared mutable task list can make later tests see earlier changes. Keep expensive shared data read-only, or place a function-scoped fixture on top that creates each test's fresh working data. Increasing scope is a behavior change in test setup, not just a speed setting.
A fixture may request dependencies of the same or wider scope. A session-scoped fixture cannot request function-scoped tmp_path: that path belongs to one test, while the requesting fixture would outlive it. pytest reports ScopeMismatch.
For a session-wide temporary folder, use the session-scoped factory:
@pytest.fixture(scope="session")
def reference_dir(tmp_path_factory):
return tmp_path_factory.mktemp("reference")
@pytest.fixture(autouse=True) runs a fixture for applicable tests without an explicit parameter request. This can reset a setting every test needs, but it also hides setup from readers. Prefer visible requests unless the automatic behavior serves the whole affected group.
Key Takeaways
- Code after
yieldcleans up after passing and failing tests. - A fixture that fails before
yielddoes not run its own post-yield cleanup. - Teardown follows reverse setup order.
- Choose wider scopes for safely shared resources, with fresh mutable data per test.
- A wide-scoped fixture cannot depend on a narrower-scoped fixture.
- Use
tmp_path_factoryfor a temporary folder shared beyond one test. - Use autouse sparingly because it hides setup from the test signature.
3.3 Use pytest's built-in fixtures
pytest supplies fixtures for common test needs. Request them by name, just like your own fixtures; no fixture import is needed. Each tool gives the test a controlled place to inspect an effect.
Write files in a temporary folder
tmp_path supplies a new, empty pathlib.Path directory for each test. Build paths with /, then use ordinary file methods:
def save_lines(path, lines):
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
def test_save_lines_writes_one_line_per_item(tmp_path):
target = tmp_path / "notes.txt"
save_lines(target, ["a", "b"])
assert target.read_text(encoding="utf-8") == "a\nb\n"
This checks what was written without touching real user files. A fixed project path can leave files behind or make tests interfere. Use tmp_path_factory.mktemp("data") when a wider-scoped fixture needs a shared directory.
Capture printed output
capsys captures standard output and standard error. readouterr() returns an object with .out and .err, containing text since the start of the test or the previous read:
def greet(name):
print(f"Hello, {name}!")
def test_greet_prints_a_greeting(capsys):
greet("Ana")
captured = capsys.readouterr()
assert captured.out == "Hello, Ana!\n"
assert captured.err == ""
The final newline is part of print's output. Reading capture twice does not give the same accumulated text twice: each read consumes the captured text available at that point. Keep the first result if you need to inspect it more than once.
Inspect log messages
Use caplog for Python logging. Its .text contains formatted output, while .records provides log-record objects for checks on fields such as the level or logger name.
import logging
def test_low_stock_is_logged(caplog):
with caplog.at_level(logging.WARNING):
logging.getLogger("shop").warning("low stock: %d", 3)
assert "low stock: 3" in caplog.text
A substring check avoids depending on a whole log format when only the message matters. Choose .records when the behavior requires a particular severity. Capturing prints and capturing logs serve different output mechanisms.
Inspect the request and control the surroundings
request describes the fixture request. In a function-scoped fixture, request.node.name gives the test name. In a module-scoped fixture, its node is the module, so the name is the test file name. request.param supplies the current value for a parametrized fixture.
monkeypatch temporarily changes attributes, environment variables, dictionary entries, or the current directory and restores them after the test. It is useful when those surroundings affect the function's behavior. pytest --fixtures lists these built-ins alongside available project fixtures.
Keep calculation and formatting logic in functions that return values when possible. Then most tests assert on the returned value directly; only the thin function responsible for printing needs output capture.
Key Takeaways
- Use
tmp_pathfor separate test files andtmp_path_factoryfor shared temporary directories. capsys.readouterr()returns new stdout and stderr since the previous read.- Include the newline when checking ordinary
printoutput. - Use
caplogfor log messages and record fields. request.nodereflects the fixture's scope;request.paramcarries a fixture parameter.
4Test many inputs with parametrization
A table of examples can make a rule easier to inspect than a collection of copied tests. Parametrization turns each row into its own reported result, so a failure points to a specific input. You will choose cases that distinguish the rules, give them useful names, and combine input tables with fixtures or case-specific marks. Knowing how the combinations expand helps you keep feedback fast as the suite grows.
4.1 Run one test over many inputs
When several inputs exercise the same behavior, a table can express the cases more clearly than copied test functions. Parametrization runs the same test separately for each row, with its own result and rerun target.
Turn rows into separate tests
The grade rules return "A" from 90, "B" from 75, and "C" below 75, with valid scores from 0 to 100. Write the values and expected results together:
import pytest
from grades import grade
@pytest.mark.parametrize("score, expected", [
(100, "A"),
(90, "A"),
(89, "B"),
(75, "B"),
(74, "C"),
(0, "C"),
])
def test_grade(score, expected):
assert grade(score) == expected
The first argument names parameters, either as a comma-separated string or a list. The second supplies cases. Each named parameter must appear in the function signature. A misspelling such as scor can stop collection with function uses no argument 'scor'; it does not create a new fixture.
pytest collects six test items here. A loop inside one ordinary test would collect only one item and stop at its first failed assertion. Separate parameter cases keep later results visible even when an earlier case fails.
Choose inputs that distinguish the rules
Typical values show ordinary behavior. Inputs at the change points show whether the comparisons include the right endpoint. The pairs 89/90 and 74/75 test both sides of the two grade thresholds. A mistaken score > 90 passes at 100 but fails at exactly 90.
Build expected results from the rule, independently of the implementation. Calling grade(score) to produce expected would make the test compare the function with itself. Do not add an internal if tree to make one test handle unrelated expectations: separate successful-result cases from exception cases.
Make failures easy to find
For simple parameter values, pytest builds IDs such as test_grade[90-A]. Rerun one case with:
pytest "tests/test_grades.py::test_grade[90-A]"
The quotes keep the shell from interpreting the square brackets. For a list or object parameter, a default ID may be a name plus a case number, such as items0. Supply ids=["empty", "one item"], an ID-producing function, or pytest.param(..., id="empty") when values alone make poor labels. IDs describe cases; they do not change what the test does.
Know when combinations multiply
Stacked decorators form every combination:
@pytest.mark.parametrize("x", [0, 1])
@pytest.mark.parametrize("y", [2, 3])
def test_commutative_addition(x, y):
assert x + y == y + x
This runs four times: each of the two x values pairs with each of the two y values. Two values and three values produce six cases. A decorator on a test class applies to each method in that class. Use rows in a single decorator when pairs belong together; use stacking when all combinations carry useful checks.
Key Takeaways
- Each parameter row becomes a separately reported test.
- Parameter names in the decorator must match the test signature.
- Test typical inputs and both sides of each threshold.
- Use readable IDs to identify and rerun individual cases.
- Stacked parametrization multiplies cases by taking every combination.
4.2 Combine parametrization with marks and fixtures
Parametrization can describe more than ordinary inputs. A row can carry a marker, and a fixture can select between implementations. These choices let shared checks keep their meaning while the surrounding setup varies.
Mark one case
pytest.param wraps a row so that its ID and marks stay with its values:
@pytest.mark.parametrize("text, expected", [
pytest.param("the cat sat", 3, id="simple"),
pytest.param("cat", 1, id="single word"),
pytest.param(
"the cat", 2, id="double space",
marks=pytest.mark.xfail(reason="splits on single spaces"),
),
])
def test_word_count(text, expected):
assert word_count(text) == expected
With the faulty text.split(" ") implementation, only "double space" is an expected failure. The other rows remain ordinary tests. After changing to text.split(), that row unexpectedly passes. Remove the obsolete mark; use strict xfail when an unexpected pass should fail the run.
Keep error cases readable
Several invalid inputs can share one exception test:
@pytest.mark.parametrize("score", [-1, 101, 250])
def test_rejects_scores_outside_0_to_100(score):
with pytest.raises(ValueError, match="between 0 and 100"):
grade(score)
Each row must cause the same promised rejection. Keep this table separate from the valid-score table so a reader can see one assertion strategy per test. This also avoids branches inside the test that decide whether to expect a return or an exception.
Vary the fixture's implementation
Suppose MemoryStore and FileStore both support saving a value and loading it by key. A fixture can provide either implementation:
@pytest.fixture(params=["memory", "file"])
def store(request, tmp_path):
if request.param == "memory":
return MemoryStore()
return FileStore(tmp_path / "store.json")
request.param is the selected fixture value. Every test that requests store runs once per implementation. A save/load check can use store.save("theme", "dark") followed by assert store.load("theme") == "dark". The classes must actually provide that interface; the fixture changes the implementation, not the promise being tested. Three tests using this two-value fixture yield six results.
Combine inputs and setup deliberately
A test can have a fixture parameter and ordinary parametrized arguments together. For example, a two-task fixture can supply fresh state while a title parameter selects which task to complete. The default function scope gives each title case its own object.
The total count is the product of the independent parameter lists. A three-value fixture combined with decorators containing four and five values yields 60 test items. Before adding a new axis, ask which rule each combination checks. Use pytest --co to inspect the expanded suite when the reported count surprises you. A long parameter product can slow feedback without adding distinct behavior checks.
Key Takeaways
- Use
pytest.paramfor a row-specific ID or marker. - Keep successful returns and expected exceptions in separate tables.
- Read fixture parameters through
request.param. - A parametrized fixture runs the same behavior tests for each supplied implementation.
- Multiply all independent parameter counts to predict collection size.
- Keep combinations that exercise useful differences in behavior.
5Replace dependencies with test doubles
A live service, changing clock, or environment setting can make a small behavior difficult to check repeatedly. Test doubles give you control over those inputs while the function's own logic still runs. You will supply prepared responses, inspect important interactions, and follow import lookups to place patches correctly. The goal is a test that detects wrong behavior and still tolerates improvements to internal code structure.
5.1 Isolate code from its dependencies
A function can be correct yet hard to test because it depends on a changing network response, today's date, or a real email service. A test double replaces such a dependency with a stand-in whose behavior the test controls.
Choose what the test needs to control
A dependency is something the code relies on outside the behavior being checked. Live services can be slow or unavailable; clocks and randomness can produce different results; real writes can change shared data.
| Double | Main purpose |
|---|---|
| Stub | Return a prepared answer |
| Mock | Record calls so the test can check interactions |
| Fake | Provide a small working implementation, such as an in-memory store |
A Mock object can serve both as a stub and as a call-recording mock. Choose the simplest stand-in that exposes the behavior the test needs.
Replace a service for one test
Suppose weather.py defines current_temp(city), which asks a web service, and this decision function:
def advice(city):
temp = current_temp(city)
return "Take a jacket" if temp < 15 else "No jacket needed"
Test the decision without asking for live weather:
import weather
def test_cold_weather_advises_a_jacket(monkeypatch):
monkeypatch.setattr(weather, "current_temp", lambda city: 10)
assert weather.advice("Oslo") == "Take a jacket"
The lambda accepts the same city argument and always returns 10 °C. advice still runs its real comparison and return logic. A separate test with 20 °C exercises the warm path. Patching advice itself would remove the very behavior the test is meant to check.
The built-in monkeypatch fixture restores changes when the test ends, including after a failure. Direct assignment such as weather.current_temp = fake leaves the replacement behind unless cleanup is added, which can make later tests depend on this test's position.
Control settings with the same fixture
Use monkeypatch.setenv("APP_MODE", "test") for an environment variable, or delenv("API_KEY", raising=False) to test behavior when a variable is absent. setitem(settings, "timeout", 1) changes a dictionary entry temporarily. chdir(tmp_path) changes the working directory for code that uses relative paths. Automatic restoration keeps each of these changes local to the test.
Randomness works the same way. If game imports random and calls random.randint(1, 6), patch game.random.randint with a callable accepting the two bounds and returning a chosen result. The game logic stays real while its random input becomes predictable.
Pass dependencies explicitly
Dependency injection makes a dependency an argument:
def advice(city, get_temp=current_temp):
temp = get_temp(city)
return "Take a jacket" if temp < 15 else "No jacket needed"
The program can use the default real function, while a test passes get_temp=lambda city: 10. Default arguments are bound when the function is defined: patching current_temp later does not replace this stored default. Passing the test double explicitly avoids that problem and makes the dependency visible at the call site.
Key Takeaways
- Use test doubles to control external inputs and effects.
- A stub supplies answers, a mock records calls, and a fake implements a small working substitute.
- Patch dependencies while leaving the behavior under test real.
monkeypatchrestores attributes, settings, environment variables, and directory changes.- Dependency injection lets the test pass a stand-in directly.
5.2 Create and check mock objects
A mock can supply an answer and keep a record of how it was used. These are separate roles: configuring a result makes the code run; checking the returned value or recorded calls establishes what the code did.
Configure a useful response
from unittest.mock import Mock imports the standard-library mock class. A plain mock creates child mocks for attributes you access. Calling it returns its return_value, another mock unless you configure it.
Consider this real function:
def fetch_temp(client, city):
try:
data = client.get_json(f"/weather/{city}")
except ConnectionError:
return None
return data["temp_c"]
Configure the method actually called by the function:
from unittest.mock import Mock
def test_returns_temperature_from_service():
client = Mock()
client.get_json.return_value = {"temp_c": 21.5}
assert fetch_temp(client, "Lima") == 21.5
client.get_json.assert_called_once_with("/weather/Lima")
Setting client.return_value would affect calling client(); it would not set the result of client.get_json(...).
Exercise failures and sequences
Set client.get_json.side_effect = ConnectionError("timeout") to test the fallback to None. A side_effect list supplies successive responses: Mock(side_effect=[1, 2]) returns 1, then 2, and raises StopIteration when called again. A callable side effect receives the same arguments and computes the response. Use these forms when repeated calls or input-dependent answers matter.
Check the interaction you mean
| Check or record | Meaning |
|---|---|
assert_called_once_with(...) | Exactly one call, with these arguments |
assert_called_with(...) | Most recent call has these arguments |
assert_not_called() | No calls |
call_count | Number of calls |
call_args | Latest call |
call_args_list | All calls, in order |
After m(1, k=2) and m(3), the count is 2 and the latest call is call(3). m.assert_called_with(3) passes; m.assert_called_once_with(3) fails. A latest-call check alone cannot detect duplicate sends or retries.
Keep the stand-in faithful
MagicMock also prepares special methods used by operations such as len, iteration, and with. Its default length is 0 and its default iteration is empty. Plain Mock does not support len. patch creates a MagicMock by default.
A flexible mock can accept a method that no longer exists in the real client. Mock(spec=WeatherClient) restricts accessible attributes to that interface. create_autospec(fetch_temp) also checks the real function's signature, so omitting its city argument raises TypeError. Use patch(..., autospec=True) for signature-aware replacements.
Spell assertion methods carefully. Current Python versions reject names beginning with assert and common misspellings such as asert with AttributeError. Relying on an arbitrary mock method name can otherwise create a child mock instead of checking anything.
Key Takeaways
- Configure the return value of the exact mock method the code calls.
- Use
side_effectfor exceptions, successive results, or input-dependent responses. - A latest-call check does not establish that there was only one call.
- Use
MagicMockwhen the dependency needs special methods. - Use a spec for interface attributes and autospec for call signatures.
- Check observable results, and check calls when the interaction is part of the promised behavior.
5.3 Patch the right name and mock with care
A patch changes one name for a limited time. For the patch to affect your code, that code must look up the name you changed. Reading the import statement is often the quickest way to choose the target.
Follow the lookup
Suppose shop/app.py contains:
from shop.weather import current_temp
def headline(city):
return f"{city}: {current_temp(city)} °C"
The import binds current_temp inside shop.app. Test that lookup:
from unittest.mock import patch
from shop.app import headline
def test_headline_includes_temperature():
with patch("shop.app.current_temp", return_value=21) as fake:
assert headline("Rome") == "Rome: 21 °C"
fake.assert_called_once_with("Rome")
Patching shop.weather.current_temp after the import changes the definition module's name, but leaves shop.app.current_temp pointing to the original function. If the application instead does import shop.weather and calls shop.weather.current_temp(city), then patching shop.weather.current_temp reaches the lookup it actually performs.
Choose a patch style
A context manager restores the original attribute when the with block exits, including on failure. A decorator keeps the replacement for the test call and supplies the created mock as an argument:
@patch("shop.app.current_temp", return_value=20)
def test_headline_uses_the_service(fake):
assert headline("Rome") == "Rome: 20 °C"
fake.assert_called_once_with("Rome")
With stacked @patch decorators, the decorator nearest the function supplies the first mock argument. Name arguments after the dependencies they replace so the order is easy to check.
Use pytest-mock when it helps
Install pytest-mock to get the mocker fixture. fake = mocker.patch("shop.app.current_temp", return_value=20) provides the same sort of replacement and automatic cleanup at the end of the test. mocker.spy(obj, "method") records calls while letting the real method execute. A spy is useful when you need a call record without replacing the behavior; it does not isolate a real network call.
Some built-in types cannot be changed in place. Patching datetime.date.today raises TypeError because datetime.date is immutable. If your module does from datetime import date, patch its own date name, such as shop.reports.date, or pass a date or clock function into the code. Preserve the rest of the interface that the tested function needs.
Keep tests about behavior
Mock the network, clock, randomness, or another external service when it makes the test controllable. Replacing every helper inside your own function makes the test depend on the current arrangement of helpers. Moving a calculation without changing its result can then break the test. Prefer result assertions when the result is the promise; use call assertions for interactions such as sending exactly one email. Doubles control an isolated check, while real parts still need checks that show they cooperate.
Key Takeaways
- Patch the name the tested code looks up, as determined by its imports.
patchrestores attributes after the context or decorated call ends.- Stacked patch decorators supply mocks from the bottom upward.
mocker.patchreplaces behavior;mocker.spyrecords real execution.- Patch your module's binding of an immutable built-in type, or inject the dependency.
- Keep mocks at boundaries so tests survive behavior-preserving refactoring.
6Measure coverage and develop test-first
Passing tests and measured coverage provide different evidence about a program. You will read reports to find paths the suite missed, then judge whether its assertions and chosen values can detect meaningful bugs. Test-driven development uses that feedback while code is being built: one small failing example guides a passing change, followed by cleanup. Feature and bug-fix examples show how earlier tests protect behavior during the next change.
6.1 Measure line and branch coverage
Coverage records which application code runs during tests. Line coverage counts executable statements; branch coverage also records which destinations decisions take. A report turns unseen paths into specific places to investigate.
Measure application code
Install pytest-cov, then run:
pytest --cov=shop --cov-report=term-missing
The plugin runs coverage.py while pytest executes tests. Without the plugin, use coverage run --source=shop -m pytest, then coverage report -m. coverage html creates a browsable report with missed code highlighted. Specify the application source: including test files can inflate the result because those files usually run almost completely.
The terminal table shows Stmts (executable statements), Miss (statements never run), Cover (percentage), and Missing (unrun line numbers). Blank lines and comments are not executable statements.
Read a line-coverage example
Use grade on lines 1–8, with rejection on line 3 and the "C" return on line 8. Add this function on lines 11–14:
def apply_discount(price, member):
if member:
price = price * 0.9
return price
Together the file has 12 executable statements. Tests calling grade(95), grade(80), and apply_discount(200, True) execute 10. The report shows 2 misses, 83% coverage, and 3, 8 in Missing. Those gaps represent invalid scores and low valid scores, not merely two arbitrary lines to touch.
Include untaken decisions
Add --cov-branch to measure branches. A decision can lead to different next lines. The member test runs every statement of apply_discount, but never takes the false path from line 12 straight to line 14. A branch report exposes that missing jump as 12->14 even though this function has full line coverage.
The extra Branch column counts branch destinations. BrPart counts partially exercised branches. With branch measurement on, coverage.py combines statement and branch opportunities:
The four if statements in the file provide 8 branch destinations. The three tests take 5. Together with 10 executed statements out of 12, that is 15 opportunities reached out of 20, or 75%. The report has Branch 8, BrPart 3, and Missing 3, 8, 12->14; jumps into already-missing lines need not be listed twice.
Set a useful threshold
--cov-fail-under=90 makes a run fail when coverage falls below 90, even if all test assertions pass. Settings can live under [tool.coverage.run] with branch = true and source = ["shop"], and under [tool.coverage.report] with fail_under = 90 and show_missing = true.
# pragma: no cover excludes a line from measurement; on a block-opening line it excludes the block. Reserve it for intentionally untested code. Removing a meaningful error path from the report makes the number higher without adding a test for that behavior.
Key Takeaways
- Measure the application package, not the test files.
- Read Missing as a list of behaviors that tests have not exercised.
- Branch coverage can reveal a missing path when every statement ran.
- Branch-mode percentages combine statement and branch-destination opportunities.
- A coverage threshold can fail a run whose assertions all passed.
- Use exclusions only for deliberately untested code.
6.2 Judge what coverage shows
A coverage percentage answers a narrow question: how much measured code ran? It helps locate gaps, but test quality also depends on what the tests checked and which inputs they chose.
Separate execution from checking
This test runs three result paths:
def test_runs():
grade(95)
grade(80)
grade(50)
Add a pytest.raises(ValueError) test for grade(101) and every line of the grade function runs. Yet the three returned letters remain unchecked. Changing the first return from "A" to "B" would leave this call-only test green. Add assertions on the expected results to check the behavior the calls are meant to demonstrate.
Check values at the rules' edges
Even result assertions at 95, 80, and 50 can miss an endpoint bug. If the implementation says score > 90, it still returns the correct results for those three values, but gives "B" at 90. Line coverage remains complete because each return line was reached by some input.
Branch coverage has a related limit. Tests can take both outcomes of a comparison without checking whether the comparison uses the right endpoint. A test at 95 and another at 80 can take the true and false paths around the A threshold while never trying 90. Choose inputs that distinguish the required comparison from a plausible wrong one.
Turn gaps into meaningful tests
Start with a missed line or jump, then read the surrounding code and name the behavior it represents. A missed raise line suggests an invalid input. A jump around a discount suggests a nonmember case. Prepare that situation and assert on the result, exception, or interaction the program promises.
Running the path without checking its outcome might clear Missing while leaving the defect undetectable. Conversely, a failing boundary assertion can be valuable even when it adds no newly executed lines. Coverage and result assertions supply different evidence.
Use a target to prevent drift
A team can select a minimum it can currently meet, enforce it with fail_under, and raise it as useful tests are added. This stops coverage quietly falling during changes. The target is a maintenance aid, so assess exceptions and difficult paths in terms of risk and test value.
Chasing 100% by calling code without assertions, adding brittle tests tied to implementation details, or excluding real behavior trades useful feedback for a number. Ask whether a plausible wrong result would fail the test. That question directs attention to the assertion and its chosen input.
Key Takeaways
- Coverage records execution; assertions check the promised outcomes.
- Full line or branch coverage can still miss an incorrect threshold.
- Choose inputs that distinguish correct rules from plausible bugs.
- Add behavior tests for report gaps and use a threshold to prevent coverage from drifting down.
6.3 Follow the red–green–refactor cycle
Test-driven development (TDD) builds behavior through short feedback cycles. Write a test for the next small requirement before implementing it. Kent Beck developed this approach in the late 1990s as part of Extreme Programming.
Take one item through the cycle
Start with a short test list of behaviors and examples. Pick the simplest item. Keep new ideas on the list while completing the current cycle.
- Red: write one test, run it, and check that it fails for the intended missing behavior.
- Green: write the simplest code that passes it, then run all the tests.
- Refactor: improve names, structure, and duplication while the tests stay green. Run them after each change.
A red result caused by a typo in the test is not evidence about the desired behavior. A new test that unexpectedly passes may describe existing behavior, contain a truthy assertion, or never have been collected. Inspect the result before proceeding.
Grow a leap-year function
The test list has four cases: 2024 is a leap year; 2023 is not; 1900 is not, despite being divisible by 4; and 2000 is, because it is divisible by 400.
First, assert is_leap(2024) fails because the function does not exist. Make it pass with a function returning True. This is deliberately small: the next example will require more.
Next, assert not is_leap(2023) fails. Replace the constant with:
return year % 4 == 0
Now both tests pass. Add assert not is_leap(1900). The current expression returns True, so the test is red. Exclude century years:
return year % 4 == 0 and year % 100 != 0
The first three tests are green. The fourth, assert is_leap(2000), exposes the missing divisible-by-400 exception. Use:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Run all four tests. Each new example has required a specific extension of the rule.
Refactor while behavior stays fixed
With the suite green, remove duplication in the tests:
@pytest.mark.parametrize("year, expected", [
(2024, True), (2023, False),
(1900, False), (2000, True),
])
def test_leap_year_rules(year, expected):
assert is_leap(year) is expected
Run the suite again. The representation changed, but the cases and required outcomes stayed the same. Refactoring can improve tests as well as application code. Adding another behavior belongs to the next red step, not to this cleanup.
Keep feedback small enough to use
Avoid implementing speculative features while making one test pass. If a change leaves many failures, return to the last green state and take a smaller step. Skipping refactoring lets duplication accumulate; writing many tests before any implementation loses the short feedback loop.
TDD encourages callable, small pieces and leaves regression checks as development proceeds. It still depends on a sound test list: examples that misunderstand the requirement will guide code toward the wrong behavior.
Key Takeaways
- Write a short test list and take one behavior through red, green, and refactor.
- Check that each red test failed for the expected reason.
- Write the smallest passing change and rerun the existing suite.
- Refactor structure without adding behavior or changing required outcomes.
- Use small steps so failures point to a small recent change.
6.4 Apply test-driven development to features and bug fixes
Test-first work applies to an existing class and to an existing bug. Begin with the observable behavior you need, then let a failing test expose the smallest change required.
Add progress to a task list
TaskList stores titles mapped to booleans: False for pending and True for completed. Add progress(), which returns a whole-number percentage. The test list starts with an empty list giving 0, one completed task out of two giving 50, and one out of three giving 33.
The empty-list test first fails with AttributeError because the method is absent. Make it green with def progress(self): return 0. Next, build two tasks, complete one, and expect 50. This fails against the constant. Counting True values with sum gives an implementation for the new case:
def progress(self):
done = sum(self._tasks.values())
return round(100 * done / len(self._tasks))
Run the full suite: the empty-list test now raises ZeroDivisionError. The new calculation regressed an earlier case. Restore both behaviors by adding if not self._tasks: return 0 before dividing.
Make rounding a requirement
One of three completed tasks gives 33 after rounding; two of three give 67. Python's round sends an exact halfway value to the even integer. One of eight is exactly 12.5%, so round(12.5) is 12. Likewise, round(0.5) is 0 and round(2.5) is 2. If the product requirement expects 13, record that choice in a test and implement the required rule. Do not silently treat all rounding conventions as interchangeable.
A factory fixture can keep a growing table readable:
@pytest.mark.parametrize("total, completed, expected", [
(0, 0, 0), (2, 1, 50), (3, 1, 33), (3, 2, 67), (8, 1, 12),
])
def test_progress(make_task_list, total, completed, expected):
titles = [f"task {i}" for i in range(total)]
tasks = make_task_list(*titles)
for title in titles[:completed]:
tasks.complete(title)
assert tasks.progress() == expected
These cases use Python's halfway-to-even rule. The table makes that decision visible and gives each case separate setup and reporting.
Reproduce a bug before repairing it
For word_count implemented with split(" "), add assert word_count("") == 0 and watch it fail with assert 1 == 0. Change to split(), rerun, and keep the test. It becomes a regression check against the same bug returning later.
For a new feature involving a service or clock, begin with an injected double or a patch at the actual lookup. The first test makes the needed input visible without depending on a live service.
Run the selected test for quick feedback, and the full suite before refactoring and before finishing. Inspect coverage for newly untested code. When an expected value correctly states the requirement, fix the code to satisfy it. Change the expectation only when the requirement changed or the test itself states it incorrectly.
Key Takeaways
- Add one observable feature case at a time and keep earlier tests green.
- Test the empty case before introducing a division by a collection size.
- Record rounding decisions in explicit examples.
- Use a factory fixture and parameter rows to simplify repeated setup.
- Reproduce a bug with a failing test, then repair it and keep the test.
- Correct an expectation only for a changed requirement or an error in the test.
Testing with pytest examples
1From a check to a useful failure
14 steps
- 1IntroductionMake behavior repeatable
A test gives a requirement an executable form. You will begin with a word counter, use a failing example to find a bug, and rerun only the relevant check while repairing it.
The same approach works for invalid input: instead of checking a returned value, you check the error the function promises. Each test should make one behavior visible.
- 2ExplanationState what must be true
A pytest test is an ordinary function whose name begins with
test, inside atest_*.pyor*_test.pyfile. Install pytest in the active virtual environment withpip install pytest.A plain
assertexpresses the expected result. A false expression raisesAssertionError; a test passes when it finishes without a failed assertion or other unexpected exception. - 3ExampleStart with an ordinary sentence
Suppose
word_countcurrently returnslen(text.split(" ")). This check passes:def test_counts_three_words(): assert word_count("the cat sat") == 3The function splits the sentence into three items. The test name describes the behavior, and the assertion compares the actual result with an independently chosen expected value.
- 4ExampleLet the empty case reveal the bug
Add
assert word_count("") == 0in its own test. It fails: splitting an empty string on a literal space gives[''], a one-item list. pytest reportsassert 1 == 0.Change the implementation to
return len(text.split()). Without an explicit separator, the empty string produces an empty list. Run both tests: the ordinary sentence still gives 3 and the empty input now gives 0. - 5TipCheck a decimal result
0.1 + 0.2evaluates to0.30000000000000004, so exact equality with0.3fails. Useassert 0.1 + 0.2 == pytest.approx(0.3).The comparison allows a small tolerance: by default relative
1e-6, plus absolute1e-12near zero. Choose explicitrel=orabs=when the required accuracy differs. This checks acceptable numeric agreement without changing the expected calculation. - 6ChallengeFind the ineffective assertion
A test sets
actual = 7and expects 5, but writesassert (actual == 5, "wrong result"). Does it fail, and how should it change?---reveal---
It does not fail: the expression is a nonempty tuple, which is truthy even though its first item is false. Write
assert actual == 5, "wrong result". The condition is then checked, and the text becomes a failure message. - 7ExplanationLocate the failing check
Run
pytestfrom the project folder. Inspect the collection count, then the failure block. Read the exception, compared values, and source location near the bottom;>marks the failing line.A body failure appears as
F. Trouble while preparing or cleaning up a fixture appears asE. A collection error, such as an unavailable imported module, normally interrupts before test bodies run. - 8ExampleRerun one behavior
A node ID identifies a test:
pytest tests/test_text.py::test_empty_string_has_no_wordsUse it for focused feedback while changing the function.
--lfselects last run's failures, and-vgives one line per item. Use--coto inspect discovery without execution. If prints seem absent,-sdisables capture so they appear live. Run the full suite again after the fix. - 9ChallengeInvestigate an empty run
A file called
tests_prices.pycontainsdef check_total(): .... Running pytest exits with code 5. What should you change before investigating the price function?---reveal---
The names miss default collection rules. Rename the file to
test_prices.pyand the function totest_total, then inspect collection with--co. Exit code 5 means no tests were collected, so the price function has not been checked. - 10ExplanationTreat rejection as behavior
The grade function accepts scores from 0 through 100 and raises
ValueErroroutside that range. Check an invalid input with:with pytest.raises(ValueError): grade(101)If nothing raises, the test fails with
DID NOT RAISE. An unexpected type also fails. Naming a broadExceptioncould accept a programming error instead of the validation error you intend to check. - 11ExampleInspect the error after the block
Keep only the rejecting operation inside the block:
with pytest.raises(ValueError) as excinfo: grade(-1) assert str(excinfo.value) == "score must be between 0 and 100"The exception ends execution of the block, so the assertion belongs afterward. Use
match=for a regex search of the message. Escape literal punctuation withre.escapeif it has regex meaning. - 12ChallengeAvoid passing for the wrong reason
A test puts both
int("bad")and a rejecting application call insidepytest.raises(ValueError). The application call is never reached, but the test passes. How should the test be arranged?---reveal---
Prepare valid setup before the raises block and keep only the application call inside it. The conversion currently supplies the expected error itself, so the passing result says nothing about the application's rejection behavior.
- 13ChallengeDiagnose a misleading green run
A test named
test_rejects_negativeusestry: parse_count(-3)followed byexcept ValueError: pass. pytest collects it and reports a pass even when parsing returns normally. What change makes the result meaningful?---reveal---
Use
with pytest.raises(ValueError): parse_count(-3). The collected test now fails when rejection is absent. A successful collection count only shows that the test ran; the exception check must still detect the missing behavior. - 14RecapUse the report as a work queue
After a failure, identify the behavior from the test name, read the actual and expected values, and rerun that check while making the repair. Finish with the full suite.
For the next test, decide which observable promise matters: a returned value, a specific rejection, or a warning. That choice determines the assertion. Check collection when a supposedly new behavior never produces the failure you expected.
2Keep a growing suite easy to run
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep the test run predictable
- 2ExampleConnect the src package to its tests
- 3ExplanationRead the selected configuration
- 4TipAvoid accidental shared setup
- 5ChallengeFix a collection clash
- 6ExplanationSeparate grouping from selection
- 7ExampleChoose skip or expected failure
- 8ChallengeRead a strict unexpected pass
- 9ChallengeKeep selection independent
- 10RecapCheck organization through a narrow run
3Build fresh setup and reliable cleanup
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the starting state explicit
- 2ExamplePrepare two pending tasks
- 3ExplanationKnow which requests share an object
- 4ExampleReturn an ordinary builder
- 5ChallengeFollow a shared dependency
- 6ExamplePut cleanup after yield
- 7ExplanationChoose the right sharing period
- 8ChallengeRepair an incompatible lifetime
- 9TipHandle setup failure honestly
- 10ExampleCheck a file without touching real data
- 11ExampleRead new captured output
- 12ConnectionUse log records when level matters
- 13ChallengeTrack two capture reads
- 14ChallengeCombine shared reference data with separate work
- 15RecapInspect ownership before changing scope
4Turn examples into separate test cases
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep repeated checks easy to inspect
- 2ExampleWrite the grade rows
- 3ExplanationGive each case its own outcome
- 4Key InsightTest the change points
- 5ChallengeChoose the revealing input
- 6TipName and select a parameter case
- 7ExampleMark only the known failing row
- 8ExampleRun the same check against two stores
- 9ChallengeCount the expanded suite
- 10ChallengeKeep rejection cases separate
- 11RecapAudit the table as a rule
5Control an external dependency
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep the decision logic real
- 2ExplanationPick a stand-in for the job
- 3ExampleSet a controlled temperature
- 4ConnectionPass the service directly
- 5ChallengeChoose the replacement boundary
- 6ExampleConfigure the called method
- 7ExampleCheck a promised service interaction
- 8ExampleExercise the connection failure
- 9TipMatch the real interface
- 10ChallengeDetect an accidental duplicate
- 11ExampleTrace a direct import
- 12ExplanationTrace a qualified lookup
- 13TipChoose replacement or observation
- 14ChallengePatch an imported clock
- 15ChallengeRepair an ineffective interaction test
- 16RecapTrace input, execution, and evidence
6Use feedback to build and improve code
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionAsk what the feedback establishes
- 2ExampleMeasure the application package
- 3ExampleRead missing statements as behaviors
- 4ExplanationLook for an untaken jump
- 5ChallengeInterpret a mixed report
- 6Key InsightExecution leaves values unchecked
- 7ChallengeFind a bug a full report misses
- 8ExplanationUse one short cycle
- 9ExampleBegin with the simplest leap case
- 10ExampleLet exception cases refine the rule
- 11ChallengeSeparate cleanup from a new requirement
- 12ExampleAdd progress one behavior at a time
- 13ExampleLet an earlier test catch the regression
- 14ChallengeMake rounding explicit
- 15ExampleKeep a repaired bug reproducible
- 16ChallengeCheck a completed repair
- 17TipKeep coverage settings useful
- 18RecapFinish at a reviewed green state
Testing with pytest practice questions
Set 1: Write checks and interpret the test run10 Practice Questions
Question 1 of 10
double(6) returns 11. What happens when pytest executes assert double(6) == 12?Show answerHide answer
AssertionError in the test body and pytest records a failure. A normal return from double is insufficient: the assertion checks the returned value, not merely whether the function completed without an exception.Question 2 of 10
This check passes when actual is 9, although it expects 8. What repair makes it test the comparison?
assert (actual == 8, "unexpected count")
Show answerHide answer
bool preserves the same ineffective truth test.Question 3 of 10
Show answerHide answer
Question 4 of 10
parse_size(-2) is required to raise ValueError. A test uses try: parse_size(-2) and except ValueError: pass, but also passes when the function returns 0. How should rejection be checked?Show answerHide answer
pytest.raises(ValueError) fails if the call returns normally and also rejects an unrelated exception type. The existing try/except has no failure path for missing rejection. Catching the broader Exception would still allow a programming error to satisfy the test.Question 5 of 10
Show answerHide answer
pytest.approx(0.6) compares within a tolerance, accommodating small binary floating-point differences. Converting the same decimal string to a float still produces an exact float comparison and does not create a tolerance. Identity with is is not a numeric accuracy check.Question 6 of 10
ValueError("mass (kg) must be positive"). A test must search for the literal fragment "mass (kg)" in the message. What match expression works?Show answerHide answer
match performs a regex search, so re.escape makes the parentheses literal characters. The unescaped pattern treats them as a group and searches for "mass kg", which lacks the actual parentheses. A message fragment is sufficient; it need not match the whole message.Question 7 of 10
ConnectionError during setup, before its requesting test body begins. How is this outcome classified?Show answerHide answer
E; the test body cannot run without its setup. It is not a skip simply because its body never executed. Skipping is an explicit outcome with its own reason, not the default treatment of a broken fixture.Question 8 of 10
python -m pytest but reports an import error with plain pytest. What difference can explain the result?Show answerHide answer
python -m adds the current directory to Python's import path, which can make a flat application package importable. That does not disable import checks or replace proper project setup. The report's root directory alone does not guarantee that application imports work.Question 9 of 10
network marker. What command explicitly selects tests using that marker expression?Show answerHide answer
-m network selects tests using the marker expression; -m "not network" excludes those tests. The -k option uses broader keyword matching, which can also match marker names, while --co lists collection without running the checks.Question 10 of 10
test_balance twice, with different assertions. Another collected test calls a function but never checks its returned value. All collected tests pass. What two weaknesses should be repaired?Show answerHide answer
Set 2: Manage fixture state and observable effects10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
catalog returns a list. How does a test receive that value?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
pathlib.Path directory?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
capsys.readouterr(), then prints "Sent" and saves a second read. What is the second read's .out?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
tmp_path and receives ScopeMismatch. It needs a directory shared throughout the run. What setup fits?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
xfail(strict=True) passes after a defect is repaired. Why does the run now report failure?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
base returns a dictionary; fixture configured(base) mutates and returns it. One test requests both fixtures. It needs the original data and a configured copy in that same test. What arrangement supplies both?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Choose cases and expand parametrized tests10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
mass > 12 implementation. What additional input and expectation expose it?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
region values and four format values in stacked parametrize decorators. It has no other parameters or fixtures. How many cases are collected?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
params=["compact", "expanded"]. How does its setup choose which implementation to return for a case?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
xfail(strict=True) but its body passes. There are no setup errors. How many bodies execute, and does the run succeed?Show answerHide answer
Save this lesson to see this answer.
Set 4: Inspect dependencies and coverage evidence10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
settings.MODE by direct assignment and later tests unexpectedly use that value. What change provides test-end restoration?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
send is called as send("first"), then send("second"). What does send.assert_called_with("second") establish?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
notice uses from transport import send and later calls send(message). After both modules have loaded, what patch target controls that call?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
lookup(code, *, region) requires a keyword-only region. A test uses an unrestricted Mock, and code incorrectly calls lookup("x", "west") while the test remains green. How can the test expose this interface defect while still checking the returned result?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
billing imports today directly from clock. Its function calls today() twice, although one lookup is required. A test patches clock.today after import and uses assert_called_with(). What repair controls the right dependency and detects the duplicate?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
A mock client has send.side_effect = [ConnectionError("offline"), {"ok": True}]. What happens when this function runs?
def submit(client):
for attempt in range(2):
try:
result = client.send()
break
except ConnectionError:
continue
return client.send()
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 5: Develop features and diagnose misleading feedback10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
round to produce a whole-number percentage. Exactly one of four equal items is complete. What should the result be under that rule?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
>= 30 to > 30 and the suite stays green. What evidence explains that outcome and what check addresses it?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
ZeroDivisionError. What is the appropriate next change?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
screen directly imports fetch from api. Its real formatting function should request data once and return a formatted title. A test patches the formatting function itself, then checks its configured return. How should the test be redesigned to check the actual promise?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
round. A new case has one of eight items complete. What result should the test require, and what does a failure returning 12 show?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Approximate comparison
pytest.approx(0.3) when checking the floating-point result of adding 0.1 and 0.2.Arrange–Act–Assert
Assertion
assert raises AssertionError.assert total([2, 4]) == 6 checks the returned sum against an independent expectation.Assertion rewriting
assert 1 == 0 instead of only an exception name.Autospec
Autouse fixture
B
Branch coverage
Bug reproducer
C
Call history
Case ID
items0.Case-specific mark
pytest.param, leaving other rows unaffected.Context manager
with block; pytest.raises uses it to check a raising operation.pytest.raises block encloses just the call expected to reject an invalid score.Coverage exclusion
# pragma: no cover.Coverage gap
Coverage target
Coverage threshold
--cov-fail-under=90 and reports a failed coverage requirement.D
Dependency
Dependency injection
get_temp=lambda city: 10 instead of patching a hidden temperature lookup.E
Editable installation
pip install -e . in the project before testing a package stored beneath src.Exception information
.value and its class through .type.excinfo.value.code can be checked for a promised error code.Execution evidence
Exit code
Expected exception
pytest.raises(ValueError) block.Expected failure
xfail mark documents a rounding bug while allowing its check to keep executing.F
Factory fixture
make_task_list("draft", "review") to create a list with its own titles.Fake
Finalizer
request.addfinalizer.Fixture
tasks parameter asks pytest to supply the task-list object prepared by a fixture of that name.Fixture caching
Fixture dependency
finished_tasks(tasks) fixture completes a task in the object supplied by tasks.Fixture override
store without changing setup for the rest of the suite.Fixture scope
G
Green step
H
Halfway-to-even rounding
round does for whole-number results.round turns into 12.I
Import mode
L
Line coverage
Log capture
caplog fixture.Lookup location
M
MagicMock
MagicMock has length zero, while len(Mock()) raises TypeError.Marker
slow marker allows pytest -m "not slow" to select a faster subset.Message matching
match fragment can identify a range warning without repeating its entire sentence.Mock
Mock boundary
N
Node ID
tests/test_text.py::test_empty to rerun that specific test while repairing a bug.O
Output capture
capsys exposes those streams separately.captured.out and includes the newline produced by print.P
Parameter product
Parameter row
(90, "A") checks the inclusive start of that top grade band.Parametrized fixture
request.param.Parametrized test
Partial branch
12->14 jump in a branch report can show that a discount check's nonmember path never ran.Patch
with block runs in one test.R
Red step
Refactoring
Regression
Regression test
Request object
request.param to decide which store implementation to build.Return value
return_value configures the result of calling that specific mock.client.get_json.return_value when the real function calls client.get_json(...).Root directory
rootdir header when test identities appear relative to an unexpected folder.S
Scope mismatch
tmp_path; it can use tmp_path_factory.Shared behavior check
Side effect
Skip
Spec
Spy
Src layout
src directory, separate from the tests and project configuration.src, such as shop.grades, after the project is installed or src is added to the import path.Stacked parametrization
Stub
T
Teardown
Temporary path
tmp_path is a separate empty directory for one test, represented as a pathlib.Path object.tmp_path / "notes.txt" and checks the contents without using a real document.Test class
Test, without requiring a base class or constructor.Test discovery
check_total is absent from ordinary pytest collection.Test double
Test error
Test expectation
Test failure
TypeError in the test body is reported as a failure, even without a false assertion.Test independence
Test list
Test-driven development
Threshold case
> 90 comparison that a score of 95 misses.U
Unexpected pass
Unit test
Y
Yield fixture
yield, with setup before that point and cleanup afterward when its lifetime ends.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.