Testing with pytest

Learn to write automated tests for Python code with pytest. Write test functions with plain 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

  1. Turn expected behavior into test functions with plain assert statements, run them with pytest, read its report, and check that code raises the errors it promises.
    • Write test functions with assert
      Write small test functions that call your code with chosen inputs and check the result with plain assert statements, including results that are floating-point numbers.
    • Run pytest and read its report
      Run 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 exceptions
      Use pytest.raises to check that invalid input raises the expected exception type and message, and inspect the exception object when the details matter.
  2. 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 pytest
      Put tests in a tests folder 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 tests
      Group related tests in classes, label tests with markers, skip tests or mark expected failures with a reason, and run only the subset you need.
  3. 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 fixtures
      Write 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 scope
      Write 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 fixtures
      Request pytest's own fixtures to work with temporary files, captured printed output and log messages instead of writing that setup yourself.
  4. 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 inputs
      Use @pytest.mark.parametrize to 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 fixtures
      Mark single cases with pytest.param, test error cases in a table, and parametrize fixtures so the same tests run against several implementations.
  5. 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 dependencies
      Recognize 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 objects
      Use Mock and MagicMock from unittest.mock to 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 care
      Use patch and the mocker fixture to replace objects for one test, patch the name where the code looks it up, and keep mocks to the boundaries of the code.
  6. 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 coverage
      Use coverage.py through the pytest-cov plugin to see which lines and branches the tests ran, read its report, and set a minimum the suite must reach.
    • Judge what coverage shows
      Use 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 cycle
      Develop 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 fixes
      Use 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.

Testing with pytest study guide

6 chapters

1

Write 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.approx for 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
SymbolOutcome
.Passed
FFailed in the test body
EError in setup or teardown
sSkipped
xExpected failure occurred
XExpected 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.

OptionEffect
-v / -qMore detail / less output
-x / --maxfail=2Stop after one / two failures or errors
-k "word and not empty"Match names with a case-insensitive expression
--lf / --ffRun last failures only / first
--coList collected tests without running them
-l / --tb=shortShow local variables / shorter tracebacks
-raSummarize all outcomes other than passes
--pdbOpen 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 --lf for a focused rerun, then run the full suite.
  • Use --co to investigate discovery and -s to 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.raises with 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.value afterward.
  • Use normal result assertions for valid inputs and pytest.warns for expected warnings.
2

Organize 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.py without 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
ToolWhen to use itWhat runs
skipA test cannot usefully run hereNo test body
skipif(condition, reason=...)A known condition prevents a useful runBody runs only when the condition is false
xfail(reason=...)A known defect is expected to failBody 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-markers to catch typos.
  • -m selects marker expressions; -k matches 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.
3

Share 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
ScopeShared within
functionOne test; the default
classOne test class
moduleOne test module
packageOne test package
sessionThe 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 yield cleans up after passing and failing tests.
  • A fixture that fails before yield does 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_factory for 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_path for separate test files and tmp_path_factory for shared temporary directories.
  • capsys.readouterr() returns new stdout and stderr since the previous read.
  • Include the newline when checking ordinary print output.
  • Use caplog for log messages and record fields.
  • request.node reflects the fixture's scope; request.param carries a fixture parameter.
4

Test 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.param for 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.
5

Replace 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.

DoubleMain purpose
StubReturn a prepared answer
MockRecord calls so the test can check interactions
FakeProvide 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.
  • monkeypatch restores 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 recordMeaning
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_countNumber of calls
call_argsLatest call
call_args_listAll 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_effect for exceptions, successive results, or input-dependent responses.
  • A latest-call check does not establish that there was only one call.
  • Use MagicMock when 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.
  • patch restores attributes after the context or decorated call ends.
  • Stacked patch decorators supply mocks from the bottom upward.
  • mocker.patch replaces behavior; mocker.spy records 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.
6

Measure 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:

coverage=executed statements+taken branch destinationsstatements+branch destinations×100%

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.

  1. Red: write one test, run it, and check that it fails for the intended missing behavior.
  2. Green: write the simplest code that passes it, then run all the tests.
  3. 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

6 Walkthroughs

1

From a check to a useful failure

14 steps
Write a small test, inspect its report, and check invalid inputs.
  1. 1
    IntroductionMake 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.

  2. 2
    ExplanationState what must be true

    A pytest test is an ordinary function whose name begins with test, inside a test_*.py or *_test.py file. Install pytest in the active virtual environment with pip install pytest.

    A plain assert expresses the expected result. A false expression raises AssertionError; a test passes when it finishes without a failed assertion or other unexpected exception.

  3. 3
    ExampleStart with an ordinary sentence

    Suppose word_count currently returns len(text.split(" ")). This check passes:

    def test_counts_three_words():
        assert word_count("the cat sat") == 3
    

    The 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.

  4. 4
    ExampleLet the empty case reveal the bug

    Add assert word_count("") == 0 in its own test. It fails: splitting an empty string on a literal space gives [''], a one-item list. pytest reports assert 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.

  5. 5
    TipCheck a decimal result

    0.1 + 0.2 evaluates to 0.30000000000000004, so exact equality with 0.3 fails. Use assert 0.1 + 0.2 == pytest.approx(0.3).

    The comparison allows a small tolerance: by default relative 1e-6, plus absolute 1e-12 near zero. Choose explicit rel= or abs= when the required accuracy differs. This checks acceptable numeric agreement without changing the expected calculation.

  6. 6
    ChallengeFind the ineffective assertion

    A test sets actual = 7 and expects 5, but writes assert (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.

  7. 7
    ExplanationLocate the failing check

    Run pytest from 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 as E. A collection error, such as an unavailable imported module, normally interrupts before test bodies run.

  8. 8
    ExampleRerun one behavior

    A node ID identifies a test:

    pytest tests/test_text.py::test_empty_string_has_no_words
    

    Use it for focused feedback while changing the function. --lf selects last run's failures, and -v gives one line per item. Use --co to inspect discovery without execution. If prints seem absent, -s disables capture so they appear live. Run the full suite again after the fix.

  9. 9
    ChallengeInvestigate an empty run

    A file called tests_prices.py contains def 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.py and the function to test_total, then inspect collection with --co. Exit code 5 means no tests were collected, so the price function has not been checked.

  10. 10
    ExplanationTreat rejection as behavior

    The grade function accepts scores from 0 through 100 and raises ValueError outside 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 broad Exception could accept a programming error instead of the validation error you intend to check.

  11. 11
    ExampleInspect 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 with re.escape if it has regex meaning.

  12. 12
    ChallengeAvoid passing for the wrong reason

    A test puts both int("bad") and a rejecting application call inside pytest.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.

  13. 13
    ChallengeDiagnose a misleading green run

    A test named test_rejects_negative uses try: parse_count(-3) followed by except 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.

  14. 14
    RecapUse 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.

2

Keep a growing suite easy to run

10 steps
Set up imports and configuration, then use classes and markers to select tests.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep the test run predictable
  2. 2
    ExampleConnect the src package to its tests
  3. 3
    ExplanationRead the selected configuration
  4. 4
    TipAvoid accidental shared setup
  5. 5
    ChallengeFix a collection clash
  6. 6
    ExplanationSeparate grouping from selection
  7. 7
    ExampleChoose skip or expected failure
  8. 8
    ChallengeRead a strict unexpected pass
  9. 9
    ChallengeKeep selection independent
  10. 10
    RecapCheck organization through a narrow run
3

Build fresh setup and reliable cleanup

15 steps
Use fixture values, scopes, and built-in capture to check a small program.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the starting state explicit
  2. 2
    ExamplePrepare two pending tasks
  3. 3
    ExplanationKnow which requests share an object
  4. 4
    ExampleReturn an ordinary builder
  5. 5
    ChallengeFollow a shared dependency
  6. 6
    ExamplePut cleanup after yield
  7. 7
    ExplanationChoose the right sharing period
  8. 8
    ChallengeRepair an incompatible lifetime
  9. 9
    TipHandle setup failure honestly
  10. 10
    ExampleCheck a file without touching real data
  11. 11
    ExampleRead new captured output
  12. 12
    ConnectionUse log records when level matters
  13. 13
    ChallengeTrack two capture reads
  14. 14
    ChallengeCombine shared reference data with separate work
  15. 15
    RecapInspect ownership before changing scope
4

Turn examples into separate test cases

11 steps
Build a table, choose useful cases, and combine it with controlled setup.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep repeated checks easy to inspect
  2. 2
    ExampleWrite the grade rows
  3. 3
    ExplanationGive each case its own outcome
  4. 4
    Key InsightTest the change points
  5. 5
    ChallengeChoose the revealing input
  6. 6
    TipName and select a parameter case
  7. 7
    ExampleMark only the known failing row
  8. 8
    ExampleRun the same check against two stores
  9. 9
    ChallengeCount the expanded suite
  10. 10
    ChallengeKeep rejection cases separate
  11. 11
    RecapAudit the table as a rule
5

Control an external dependency

16 steps
Supply responses, inspect important calls, and patch the name the code uses.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep the decision logic real
  2. 2
    ExplanationPick a stand-in for the job
  3. 3
    ExampleSet a controlled temperature
  4. 4
    ConnectionPass the service directly
  5. 5
    ChallengeChoose the replacement boundary
  6. 6
    ExampleConfigure the called method
  7. 7
    ExampleCheck a promised service interaction
  8. 8
    ExampleExercise the connection failure
  9. 9
    TipMatch the real interface
  10. 10
    ChallengeDetect an accidental duplicate
  11. 11
    ExampleTrace a direct import
  12. 12
    ExplanationTrace a qualified lookup
  13. 13
    TipChoose replacement or observation
  14. 14
    ChallengePatch an imported clock
  15. 15
    ChallengeRepair an ineffective interaction test
  16. 16
    RecapTrace input, execution, and evidence
6

Use feedback to build and improve code

18 steps
Read coverage evidence and develop a feature through small test-first changes.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionAsk what the feedback establishes
  2. 2
    ExampleMeasure the application package
  3. 3
    ExampleRead missing statements as behaviors
  4. 4
    ExplanationLook for an untaken jump
  5. 5
    ChallengeInterpret a mixed report
  6. 6
    Key InsightExecution leaves values unchecked
  7. 7
    ChallengeFind a bug a full report misses
  8. 8
    ExplanationUse one short cycle
  9. 9
    ExampleBegin with the simplest leap case
  10. 10
    ExampleLet exception cases refine the rule
  11. 11
    ChallengeSeparate cleanup from a new requirement
  12. 12
    ExampleAdd progress one behavior at a time
  13. 13
    ExampleLet an earlier test catch the regression
  14. 14
    ChallengeMake rounding explicit
  15. 15
    ExampleKeep a repaired bug reproducible
  16. 16
    ChallengeCheck a completed repair
  17. 17
    TipKeep coverage settings useful
  18. 18
    RecapFinish at a reviewed green state

Testing with pytest practice questions

50 Practice Questions in 5 sets

Set 1: Write checks and interpret the test run10 Practice Questions

Question 1 of 10

A function double(6) returns 11. What happens when pytest executes assert double(6) == 12?
  1. The test passes because the call returns normally.
  2. The test fails with an assertion error.
  3. The test is skipped because no exception was expected.
  4. The run stops during collection before calling double.
Show answerHide answer
Answer: B
The comparison is false, so Python raises 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")
  1. Change the check to assert bool((actual == 8, "unexpected count")).
  2. Change the check to assert (actual, "unexpected count") == (9, "unexpected count").
  3. Change the check to assert "unexpected count", actual == 8.
  4. Change the check to assert actual == 8, "unexpected count".
Show answerHide answer
Answer: D
The original expression is a two-item tuple, and a nonempty tuple is truthy even when its comparison item is false. Put the condition before the comma and the message after it. Converting the tuple to bool preserves the same ineffective truth test.

Question 3 of 10

A run executes no test bodies and returns pytest exit code 5. What does that code report?
  1. No tests were collected for the selected run.
  2. An assertion failed in a collected test body.
  3. A fixture failed before a collected test could run.
  4. The command used an unsupported pytest option.
Show answerHide answer
Answer: A
Exit code 5 identifies an empty collection, so inspect selected paths and discovery names. It does not mean that a collected test failed to set up: a fixture error requires a test to have been collected in the first place, and is reported differently.

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?
  1. Assert that parse_size(-2) returns None.
  2. Wrap the call in pytest.raises(Exception).
  3. Wrap the call in pytest.raises(ValueError).
  4. Replace pass with return True in the except block.
Show answerHide answer
Answer: C
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

A Celsius calculation returns a float with a tiny representation difference from its expected value of 0.6. What assertion allows an appropriate numeric tolerance?
  1. assert result is 0.6
  2. assert result == pytest.approx(0.6)
  3. assert str(result) == "0.6"
  4. assert result == float("0.6")
Show answerHide answer
Answer: B
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

A function raises ValueError("mass (kg) must be positive"). A test must search for the literal fragment "mass (kg)" in the message. What match expression works?
  1. match=re.escape("mass (kg)")
  2. match="mass (kg)"
  3. match=str("mass (kg)")
  4. match="^mass kg$"
Show answerHide answer
Answer: A
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

A fixture raises ConnectionError during setup, before its requesting test body begins. How is this outcome classified?
  1. An assertion failure inside the test body.
  2. An expected failure for an anticipated error.
  3. A skipped test because its body never executed.
  4. A test error caused by unsuccessful setup.
Show answerHide answer
Answer: D
A failure while preparing a fixture is a setup error, reported with 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

An importable flat-layout project runs with python -m pytest but reports an import error with plain pytest. What difference can explain the result?
  1. python -m pytest disables collection-time import checks.
  2. python -m pytest adds the current folder to the import path.
  3. Plain pytest always ignores the project's configuration file.
  4. Plain pytest collects only tests installed as packages.
Show answerHide answer
Answer: B
Running a module with 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

A test has a registered network marker. What command explicitly selects tests using that marker expression?
  1. pytest -m "not network"
  2. pytest --lf network
  3. pytest -m network
  4. pytest --co network
Show answerHide answer
Answer: C
-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

A test module defines 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?
  1. Rename the module and replace every test call with a fixture.
  2. Run with -s and move both balance checks into a test class.
  3. Use --lf and convert every returned value to a boolean.
  4. Give the balance checks unique names and assert on the unchecked result.
Show answerHide answer
Answer: D
The second definition replaces the first before collection, so one intended balance check is absent. The call-only test also leaves a returned value unchecked. More verbose output or a test class does not restore an overwritten definition or add a meaningful outcome assertion.
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

A fixture named catalog returns a list. How does a test receive that value?
  1. By importing and calling catalog() inside the test.
  2. By naming the test function test_catalog_fixture.
  3. By setting a module-level variable named catalog.
  4. By declaring a catalog parameter in the test function.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A default-scoped fixture returns a new empty list. Two separate tests request it, and the first appends an item. What list does the second receive?
  1. The first test's list containing its appended item.
  2. The first test's list, cleared automatically before reuse.
  3. A separately created empty list for the second test.
  4. A new list, but only when the first test passes.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A fixture successfully yields a file handle, and the test then fails an assertion. Its next fixture line closes the handle. What happens to that line?
  1. It runs only if the test catches its own assertion error.
  2. It is skipped because assertions bypass all fixture cleanup.
  3. It runs during fixture teardown after the test failure.
  4. It is deferred until the next test requests the same fixture.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A test must create a file in a separate empty directory for that test. What built-in fixture supplies a pathlib.Path directory?
  1. tmp_path
  2. caplog
  3. request
  4. capsys
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A test prints "Queued", calls capsys.readouterr(), then prints "Sent" and saves a second read. What is the second read's .out?
  1. "Queued\nSent\n"
  2. "Sent\n"
  3. "Sent"
  4. ""
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A module-scoped fixture returns a mutable list. A function-scoped fixture requests it, appends an item, and returns it. Two tests use the function fixture. The second sees two appended items. How can setup preserve shared reference loading and independent edits?
  1. Keep both scopes and clear the list only at module teardown.
  2. Make both fixtures session-scoped so setup runs just once.
  3. Mark the second test xfail because fixture caching is expected.
  4. Copy the reference list in the function fixture before appending.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A session fixture requests function-scoped tmp_path and receives ScopeMismatch. It needs a directory shared throughout the run. What setup fits?
  1. Request tmp_path_factory and call its mktemp method.
  2. Call the decorated tmp_path fixture directly during setup.
  3. Leave the dependency unchanged and add autouse=True.
  4. Move the same tmp_path parameter into a session test class.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A test marked xfail(strict=True) passes after a defect is repaired. Why does the run now report failure?
  1. Strict markers reject all built-in xfail decorators.
  2. A strict expected-failure mark treats an unexpected pass as failure.
  3. The repair prevented pytest from collecting the test.
  4. The test must raise an assertion error to prove the repair succeeded.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Fixture 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?
  1. Make base function-scoped and continue mutating it directly.
  2. Make configured autouse and remove its parameter from the test.
  3. Request base twice under different local variable names.
  4. Create a separate dictionary in configured before applying its changes.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A function logs a warning through Python logging. A test needs to check both the message and severity without depending on the complete formatted line. What evidence should it inspect?
  1. The stdout string from capsys.readouterr() only.
  2. The log records collected by caplog at the needed level.
  3. The fixture names listed by pytest --fixtures only.
  4. The stderr text printed with capture disabled through -s.
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

One test has four rows in a single parametrize decorator. How many test items does it create before any stop-on-failure option takes effect?
  1. One item with four internal assertion results.
  2. Eight items, one for each input and expected result.
  3. Four items, each with a separate case outcome.
  4. Five items, including the undecorated test body.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A mass label must switch to "heavy" at 12 kg, including exactly 12. Tests at 5 kg and 17 kg pass against an incorrect mass > 12 implementation. What additional input and expectation expose it?
  1. 12 kg, expecting "heavy".
  2. 11 kg, expecting the lighter label.
  3. 18 kg, expecting "heavy".
  4. 0 kg, expecting the lighter label.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A test uses three region values and four format values in stacked parametrize decorators. It has no other parameters or fixtures. How many cases are collected?
  1. 7 cases, because the two list lengths are added.
  2. 4 cases, because the longer decorator supplies the rows.
  3. 24 cases, because each decorator is applied twice.
  4. 12 cases, because every region pairs with every format.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

One row in a table needs a readable ID and an xfail mark, while the remaining rows stay ordinary tests. What object wraps that row?
  1. pytest.fixture
  2. pytest.param
  3. pytest.raises
  4. pytest.skip
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A fixture has two implementation choices. Three tests request it: one has three input rows, one has two stacked decorators with two values each, and one has no test parametrization. How many items are collected?
  1. 12 items.
  2. 14 items.
  3. 18 items.
  4. 16 items.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

An implementation fixture is declared with params=["compact", "expanded"]. How does its setup choose which implementation to return for a case?
  1. By requesting request and reading request.param.
  2. By requesting a fixture named after each string value.
  3. By reading the expected value from the assertion report.
  4. By importing the parameter strings as Python modules automatically.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

Two independent labels and three independent modes are parametrized for a test. Mode "legacy" has a known defect only for label "dense". How can all combinations remain visible while only that pair has an expected-failure mark?
  1. Mark the whole test xfail and keep the stacked decorators.
  2. Use a six-row paired table and mark only dense/legacy with pytest.param.
  3. Keep only the dense/legacy pair and mark it xfail.
  4. Mark the legacy mode value xfail for both label values.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A test needs to check three rejected input values and one successful return rule. How can the assertions stay clear without branching in the test body?
  1. Put every case inside one broad pytest.raises(Exception) block.
  2. Replace the rejection assertions with a loop that catches every error.
  3. Use a rejection table with pytest.raises and a separate return-value test.
  4. Use xfail on the successful case so all rows expect some failure.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A table tests two different operations on a list. It requests a default-scoped fixture that constructs the list. What setup does each parameter row receive?
  1. The same list as modified by the previous row.
  2. One cached list shared across the whole decorator.
  3. A fresh fixture value for that separate test case.
  4. No fixture value, only the row's parameter values.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A test requests a two-choice store fixture and has three input rows. The ordinary row passes; one row is skipped; one has xfail(strict=True) but its body passes. There are no setup errors. How many bodies execute, and does the run succeed?
  1. Four bodies execute, and strict unexpected passes fail the run.
  2. Six bodies execute, and strict unexpected passes fail the run.
  3. Four bodies execute, and skipped cases make the run succeed.
  4. Two bodies execute, and all expected-failure cases are skipped.
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

A test replaces a live exchange service with a callable returning a prepared numeric rate. It does not inspect calls. What role is that callable serving?
  1. A spy that observes the unchanged real service.
  2. A stub that supplies a controlled response.
  3. A fixture scope that controls test collection.
  4. A fake implementing the complete production service.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A test changes settings.MODE by direct assignment and later tests unexpectedly use that value. What change provides test-end restoration?
  1. Assign the same value in a module-level variable.
  2. Mark every later test to share the same test class.
  3. Run the suite with -s so setting changes are visible.
  4. Use monkeypatch.setattr(settings, "MODE", "test").
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A mock send is called as send("first"), then send("second"). What does send.assert_called_with("second") establish?
  1. Both calls used "second", because the last arguments replace history.
  2. Exactly one call occurred, and it used "second".
  3. The latest call used "second", without requiring only one call.
  4. The first call failed, and only the second call was recorded.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Module notice uses from transport import send and later calls send(message). After both modules have loaded, what patch target controls that call?
  1. notice.send
  2. notice.transport.send
  3. transport.send
  4. transport.notice.send
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A real 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?
  1. Replace the assertion with assert lookup.call_count == 1.
  2. Configure the existing Mock with a longer return string.
  3. Use MagicMock so positional arguments become keyword arguments.
  4. Use create_autospec(lookup) and configure its returned value.
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?
  1. Patch billing.today and use assert_called_once_with().
  2. Patch clock.today and check only call_args afterward.
  3. Patch billing itself and keep the latest-call assertion.
  4. Patch both function results and mark the test xfail.
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()
  1. It returns the successful response after retrying the first call.
  2. It returns a new child mock after the two prepared responses.
  3. It raises StopIteration after the retry succeeds.
  4. It raises the original ConnectionError after both attempts.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A line-only coverage report shows 25 executable statements and 5 missed statements. What percentage ran?
  1. 83%.
  2. 20%.
  3. 75%.
  4. 80%.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A branch-enabled report has 16 statements, 4 missed statements, 8 branch destinations, and 2 missed destinations. All assertions pass, and the required minimum is 80%. Does the coverage requirement pass?
  1. Yes: the six taken destinations give exactly the required 80%.
  2. No: 18 of 24 opportunities were reached, giving 75%.
  3. No: the combined result is 62.5%, using all misses as statements.
  4. Yes: passing assertions override the coverage minimum.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A suite executes every return line of a price function but does not assert on any returned price. What useful weakness can remain despite full line coverage?
  1. A missing return statement must cause collection failure.
  2. Incorrect returned prices may go undetected by the tests.
  3. pytest must automatically convert those tests into expected failures.
  4. The coverage tool must exclude the function because no assert exists.
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

In TDD, what should happen immediately after writing a test for the next missing behavior, before implementing that behavior?
  1. Change its expectation to the current output.
  2. Refactor all existing tests into one table.
  3. Observe the test fail for the intended reason.
  4. Implement several future behaviors from the test list.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A progress display uses Python 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

A classifier should return "high" from 30 inclusive. Its tests assert results at 10 and 50 and reach both branches. Someone changes >= 30 to > 30 and the suite stays green. What evidence explains that outcome and what check addresses it?
  1. Branch coverage failed to measure the false path; rerun the same inputs with -s.
  2. Both paths ran but the endpoint was untested; add 30 expecting "high".
  3. The return values were never checked; replace both assertions with call checks.
  4. The minimum was too low; raise it to 100 without changing any cases.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A new test was meant to exercise an absent feature, but the collection count does not increase and all tests remain green. What should you investigate first?
  1. Whether the application needs a broader implementation.
  2. Whether the coverage exclusion should hide the feature.
  3. Whether all existing assertions should use pytest.approx.
  4. Whether the new test matches the discovery and selection rules.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A ratio feature returns 0 for an empty list. A later test expects 40 for two completed items out of five. Implementing the formula makes the new test pass but the empty-list test raises ZeroDivisionError. What is the appropriate next change?
  1. Delete the empty-list test because the formula defines the feature now.
  2. Handle the empty list before dividing, preserving both expectations.
  3. Change the empty-list expectation to accept any exception.
  4. Mark the new ratio test xfail until the earlier test is removed.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A repaired parser should reject whitespace-only input. You have observed a new test fail before the fix and pass afterward. What should happen to that test once the repair is complete?
  1. Remove it so the suite contains only current feature work.
  2. Convert it to skip because the defect no longer occurs.
  3. Keep it as a regression check for the repaired behavior.
  4. Change it to accept either rejection or a returned value.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A member-only test reaches all 4 statements of a discount function. With branch measurement, it reaches 1 of 2 decision destinations. Nonmembers should retain their original price. What would a 90% branch-mode coverage minimum report, and what behavior test addresses the gap?
  1. Fail at about 83%; assert an unchanged price for a nonmember customer.
  2. Fail at 50%; assert an unchanged price for a nonmember customer.
  3. Pass at 90%; assert that the member call returns without an exception.
  4. Pass at 100%; assert the same member discount using another starting price.
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?
  1. Patch the formatting function and add assert_not_called on api.fetch.
  2. Patch api.fetch after import and compare only its default return object.
  3. Patch screen.fetch, call real formatting, and check its result and one request.
  4. Spy on the formatting function and replace its entire body with the title.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

All tests pass. A developer replaces duplicated conditionals with a helper and keeps the required results unchanged. What TDD step is this, and what feedback should accompany it?
  1. Red, followed by weakening the expectations until they pass.
  2. Green, followed by adding all remaining features without reruns.
  3. Collection, accompanied by converting every test into a fixture.
  4. Refactor, accompanied by repeated runs of the existing tests.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A progress requirement explicitly rounds exact halfway percentages upward. Tests at 0%, 20%, and 100% pass with Python round. A new case has one of eight items complete. What result should the test require, and what does a failure returning 12 show?
  1. Require 13; the implementation uses a different tie rule from the requirement.
  2. Require 12; a built-in function determines the product requirement.
  3. Require 12.5; rounding should be removed from the stated requirement.
  4. Require either 12 or 13; a halfway value has no testable result.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

82 Key Terms, each with its definition

A

Approximate comparison
An approximate comparison accepts numeric results within a tolerance, allowing small floating-point representation differences.
Use pytest.approx(0.3) when checking the floating-point result of adding 0.1 and 0.2.
Arrange–Act–Assert
Arrange–Act–Assert is a test structure that prepares inputs, performs the operation, and checks its observable outcome.
A test builds a task list, completes a task, then checks the remaining pending titles.
Assertion
An assertion states a condition that must be true at that point; a false Python assert raises AssertionError.
The statement assert total([2, 4]) == 6 checks the returned sum against an independent expectation.
Assertion rewriting
Assertion rewriting is pytest's transformation of test assertions so a failure report can show compared values and useful differences.
A failed word-count check can show assert 1 == 0 instead of only an exception name.
Autospec
An autospec creates a mock from a real interface and checks call signatures, exposing missing or unexpected arguments.
An autospecced two-argument function rejects a call that supplies only its first argument.
Autouse fixture
An autouse fixture applies setup to tests in its scope without those tests explicitly requesting its value through a parameter.
An autouse reset can protect all local tests, though the reset is less visible in their signatures.

B

Branch coverage
Branch coverage records decision destinations reached during execution, exposing missing paths that statement coverage can overlook.
When only members get a discount, a member-only test misses the false path around the price-changing assignment.
Bug reproducer
A bug reproducer is a small test that reliably demonstrates an existing defect before a repair, usually through a failing assertion.
An empty-string word-count test exposes the extra item produced by splitting on a literal space.

C

Call history
A mock's call history records its interactions, including the total count, latest arguments, and ordered list of all calls.
Inspecting only the latest call cannot establish that a notification was sent exactly once.
Case ID
A case ID is the readable parameter-case label appended to a test name, helping identify a result and select its node ID.
The label "empty" is easier to recognize than an object-based default label such as items0.
Case-specific mark
A case-specific mark attaches behavior such as xfail to one parameter row through pytest.param, leaving other rows unaffected.
In a table of word-count cases, only the row with a known repeated-space failure is marked xfail.
Context manager
A context manager defines entry and exit behavior for a with block; pytest.raises uses it to check a raising operation.
A pytest.raises block encloses just the call expected to reject an invalid score.
Coverage exclusion
A coverage exclusion removes selected code from measurement, such as a line or block marked with # pragma: no cover.
Excluding an intentional entry-point block changes measurement, but does not add any behavior check.
Coverage gap
A coverage gap is measured code or a branch destination the run did not reach, pointing to behavior that needs investigation.
A missed rejection line suggests adding an invalid-input test with an exception assertion.
Coverage target
A coverage target is a chosen level of measured execution used to guide and maintain a suite, alongside judgment of assertions and cases.
A team can enforce a reachable minimum and increase it as useful behavior tests are added.
Coverage threshold
A coverage threshold is a required minimum percentage that can fail the run even when all tests pass their assertions.
A run at 83% falls short of --cov-fail-under=90 and reports a failed coverage requirement.

D

Dependency
A dependency is something code relies on outside the behavior currently being tested, such as a service, a clock, or an environment value.
A jacket recommendation depends on temperature data, but its decision can be tested without live weather.
Dependency injection
Dependency injection means supplying a dependency through an argument, allowing callers and tests to choose the implementation.
A test passes get_temp=lambda city: 10 instead of patching a hidden temperature lookup.

E

Editable installation
An editable installation makes a configured local project importable from its working source through the active Python environment.
Run pip install -e . in the project before testing a package stored beneath src.
Exception information
Exception information is pytest's saved wrapper exposing a caught exception through .value and its class through .type.
After leaving the raises block, excinfo.value.code can be checked for a promised error code.
Execution evidence
Execution evidence shows that a measured path ran during testing, without itself establishing that the path's outcome was checked.
A call-only grade test can reach each return while accepting an incorrect returned letter.
Exit code
An exit code is the integer result a command returns to its caller, allowing scripts to distinguish success and different problems.
pytest exits with code 5 when the selected run collects no test items.
Expected exception
An expected exception is an error type the behavior promises to raise in a particular situation, such as invalid input.
A score above the valid maximum is tested with a pytest.raises(ValueError) block.
Expected failure
An expected failure marks behavior with a known defect, normally running the test while reporting the anticipated failure separately.
An xfail mark documents a rounding bug while allowing its check to keep executing.

F

Factory fixture
A factory fixture returns a callable that builds test data or objects from values chosen inside the requesting test.
A test calls make_task_list("draft", "review") to create a list with its own titles.
Fake
A fake is a small working implementation used in place of a production dependency, such as an in-memory store replacing a database.
A fake store supports save and load operations while keeping its data in a local dictionary.
Finalizer
A finalizer is a cleanup callable registered with pytest for the end of a fixture lifetime, including through request.addfinalizer.
A fixture can register a resource-closing function as an alternative to post-yield cleanup.
Fixture
A fixture is a pytest-managed setup function that prepares a value or resource and supplies it to tests that request it by name.
A tasks parameter asks pytest to supply the task-list object prepared by a fixture of that name.
Fixture caching
Fixture caching reuses a fixture value within its lifetime, so repeated requests in one test receive the same prepared object.
Two fixtures that depend on one task-list fixture see the same list in one test, including its mutations.
Fixture dependency
A fixture dependency is another fixture requested by a fixture parameter, allowing related setup to build on existing values.
A finished_tasks(tasks) fixture completes a task in the object supplied by tasks.
Fixture override
A fixture override replaces an outer fixture with a same-named fixture closer to the test, changing setup for that local group.
Tests in a subfolder can request a local store without changing setup for the rest of the suite.
Fixture scope
A fixture scope controls how long a fixture instance is shared, from one test function to a class, module, package, or session.
Module scope loads shared read-only reference data once for the tests in that module.

G

Green step
The green step adds the simplest implementation that passes the new test, then checks the existing suite for regressions.
A constant result can serve the first example until the next failing case demands a broader rule.

H

Halfway-to-even rounding
Halfway-to-even rounding chooses the even neighboring integer at an exact halfway value, as Python's round does for whole-number results.
One completed task out of eight gives 12.5%, which round turns into 12.

I

Import mode
An import mode controls how pytest loads test modules; modes differ in how they handle module names and the import path.
Importlib mode avoids the bare-name clash between unpackaged test modules with identical names.

L

Line coverage
Line coverage is the share of measured executable statements reached during a run, also called statement coverage.
Ten executed statements out of twelve appear as 83% with the default report precision.
Log capture
Log capture collects Python logging output for assertions on formatted messages or record fields, using pytest's caplog fixture.
A low-stock test can inspect a warning message without depending on the terminal log format.
Lookup location
A lookup location is the module or object namespace where executing code finds a name, determining the effective patch target.
A direct imported name must be patched in the consuming module after that binding exists.

M

MagicMock
A MagicMock is a mock with support for Python special methods, making it useful for iteration, length checks, or context managers.
A default MagicMock has length zero, while len(Mock()) raises TypeError.
Marker
A marker labels a test or changes its collection or execution behavior, such as identifying slow tests or expected failures.
A registered slow marker allows pytest -m "not slow" to select a faster subset.
Message matching
Message matching checks an exception or warning message against a regex pattern, using search unless the pattern adds constraints.
A match fragment can identify a range warning without repeating its entire sentence.
Mock
A mock is a test double that records interactions so a test can check important calls as well as any configured responses.
A mail mock lets a test check that exactly one message was sent to the intended address.
Mock boundary
A mock boundary is an external interface selected for replacement so the test controls a dependency while keeping its own logic real.
When testing a jacket recommendation, patch the weather service call while allowing the jacket decision to execute normally.

N

Node ID
A node ID identifies a collected test by its file and name, plus a class and parameter-case identifier when applicable.
Pass tests/test_text.py::test_empty to rerun that specific test while repairing a bug.

O

Output capture
Output capture collects text written to stdout and stderr so tests can inspect it; capsys exposes those streams separately.
A greeting test checks captured.out and includes the newline produced by print.

P

Parameter product
A parameter product is the collection of combinations formed by independent fixture and test parameter lists in one check.
Three fixture choices and four input rows produce 12 cases for each requesting test function.
Parameter row
A parameter row is one set of values assigned to the named arguments of a parametrized test, often including an expected result.
When an A starts at 90, the row (90, "A") checks the inclusive start of that top grade band.
Parametrized fixture
A parametrized fixture has several input choices and runs requesting tests once for each choice, read through request.param.
The same save/load test runs against both an in-memory store and a file-backed store.
Parametrized test
A parametrized test runs the same test body as separate cases with different supplied inputs and independently expected results.
Six score rows create six items, so one failure does not prevent reporting the remaining cases.
Partial branch
A partial branch is a decision for which execution took some possible destinations but missed at least one other destination.
A missing 12->14 jump in a branch report can show that a discount check's nonmember path never ran.
Patch
A patch temporarily replaces an attribute binding with a controlled object and restores the original when its context ends.
A context-managed patch replaces a temperature lookup only while its with block runs in one test.

R

Red step
The red step writes and runs a test that fails for the intended missing behavior, checking that the test can detect what needs adding.
An absent method should give the expected missing-method failure before its implementation starts.
Refactoring
Refactoring improves code structure, names, or duplication while preserving required behavior and keeping the suite passing.
Four equivalent test functions can become parameter rows without changing the expected outcomes.
Regression
A regression is a change that breaks behavior which previously worked, often in a part of the program outside the intended edit.
An added percentage calculation regresses the empty-list case when it divides by zero.
Regression test
A regression test preserves a required behavior after a feature or repair, so a later change that breaks it produces a failure.
Keep a progress test for an empty task list after adding calculations for nonempty task lists.
Request object
A request object gives a fixture information about its current context, including its scope node and any fixture parameter value.
A parametrized fixture reads request.param to decide which store implementation to build.
Return value
A return value is the result supplied by a call; a mock's return_value configures the result of calling that specific mock.
Set client.get_json.return_value when the real function calls client.get_json(...).
Root directory
The root directory is pytest's project location for organizing the run and writing relative node IDs, usually tied to its chosen config file.
Inspect the rootdir header when test identities appear relative to an unexpected folder.

S

Scope mismatch
A scope mismatch occurs when a fixture requests a narrower-lived dependency that cannot serve the requesting fixture's lifetime.
A session fixture cannot request function-scoped tmp_path; it can use tmp_path_factory.
Shared behavior check
A shared behavior check tests one promised interface across multiple implementations, using equivalent actions and expectations.
Two stores sharing one interface must each return the value saved under a key, even though their storage differs.
Side effect
A mock side effect configures call behavior using an exception, an iterable of successive results, or a callable receiving the arguments.
A connection-error side effect exercises the fallback path of a function that handles failed connections.
Skip
A skip records that a test is not run because the present conditions prevent a useful execution, ideally with a specific reason.
A platform-specific file-permission check can be skipped on an unsupported operating system.
Spec
A mock spec restricts accessible attribute names to a real interface, helping expose tests that call a missing or renamed method.
A mock based on a weather client class rejects access to a method absent from that class's interface.
Spy
A spy records calls to real behavior without replacing that behavior, allowing interaction checks while the original method executes.
A spy on a formatter still runs the formatting code and keeps a record of its arguments.
Src layout
A src layout places application packages inside a src directory, separate from the tests and project configuration.
Tests import a package under src, such as shop.grades, after the project is installed or src is added to the import path.
Stacked parametrization
Stacked parametrization applies independent parameter lists to one test, creating a case for every combination of their values.
Two values for one argument and three for another expand one test function into six items.
Stub
A stub is a test double that supplies prepared answers, allowing a test to choose the conditions seen by the real code.
A callable returning 10 supplies a stable cold temperature without contacting a service.

T

Teardown
Teardown is cleanup performed after a test or resource lifetime, such as closing connections or restoring a changed setting.
Post-yield teardown closes the connection even when an assertion in the test fails.
Temporary path
A temporary path from tmp_path is a separate empty directory for one test, represented as a pathlib.Path object.
A save-file test writes to tmp_path / "notes.txt" and checks the contents without using a real document.
Test class
A test class groups related pytest methods under a name beginning with Test, without requiring a base class or constructor.
pytest gives each method a new class instance, so a previous method does not arrange its state.
Test discovery
Test discovery is pytest's search for test files, functions, and methods that match its collection rules and selected locations.
A function called check_total is absent from ordinary pytest collection.
Test double
A test double is a controlled stand-in for a real dependency during a test, making selected inputs or effects predictable.
A fixed temperature provider lets a test reliably exercise a cold-weather decision in the code.
Test error
A test error is a problem outside normal test-body execution, such as a fixture failure during setup or teardown.
A database fixture that cannot open its connection reports an error before the test body runs.
Test expectation
A test expectation is the result or behavior a test requires, derived from the requirement independently of the current implementation.
Change a wrong expectation when the requirement was misstated, not merely to match a failing return value.
Test failure
A test failure occurs when a test body violates an assertion or raises an unexpected exception while pytest is executing it.
An unexpected TypeError in the test body is reported as a failure, even without a false assertion.
Test independence
Test independence means a test has the setup it needs and does not rely on state or execution supplied by another test.
A task test should pass when selected alone as well as after every other task test.
Test list
A test list is a short record of behaviors and examples to develop, with one item taken through a small TDD cycle at a time.
Keep empty, partial, and complete progress cases on the list while implementing the first case.
Test-driven development
Test-driven development is a development approach that writes a failing behavior test before implementing its smallest passing change.
A leap-year function grows through examples before its four cases are consolidated into a table.
Threshold case
A threshold case uses an input at a rule's change point, helping distinguish an inclusive comparison from a plausible incorrect one.
A score of exactly 90 catches a mistaken > 90 comparison that a score of 95 misses.

U

Unexpected pass
An unexpected pass occurs when an xfail-marked test succeeds; strict xfail makes that result fail the run for attention.
After a defect is fixed, an unexpected pass signals that its expected-failure marker needs review.
Unit test
A unit test is an automated check of a small piece of code, often one function or method, using chosen inputs and expected outcomes.
A test of an empty word counter asserts that the returned count is zero.

Y

Yield fixture
A yield fixture supplies its test value at yield, with setup before that point and cleanup afterward when its lifetime ends.
A database fixture yields an open connection and closes it after the requesting test finishes.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started