A person checks a test sheet beside a machine that feeds code past an AI arm, a coverage gauge, and a mutants cage into a tray of passing tests.

Generating Python Tests With AI: A Suite You Can Trust

by Leodanis Pozo Ramos Updated Reading time estimate 50m intermediate ai tools

Say you’ve inherited a project with no tests or so few that you can’t refactor it safely. Generating Python tests with AI seems like the quick way out, but a one-line prompt often gives you a suite that passes without catching real bugs. That’s worse than no suite at all because it falsely tells you everything is fine when it isn’t.

In this guide, you’ll learn a reusable workflow for building a pytest suite you can trust. A reliable test suite should have at least three qualities:

  • Accurate: Its assertions state what the code is supposed to do, not what it happens to do today.
  • Complete: It covers boundaries, error paths, and edge cases, not just the happy path.
  • Robust: It fails when someone changes the code’s behavior.

To get there, you’ll set up testing conventions once, map the project and extract its intended behavior, generate the suite to meet a coverage goal, and confirm that it holds up with a review and a mutation testing run.

Take the Quiz: Test your knowledge with our interactive “Generating Python Tests With AI: A Suite You Can Trust” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Generating Python Tests With AI: A Suite You Can Trust

Check how well you can generate Python tests with AI, from behavior tables and branch coverage to mutation testing with mutmut.

Prerequisites

This guide assumes you’ve written tests before and are comfortable working with an AI coding agent. You won’t learn pytest from scratch here. Instead, you’ll focus on directing the agent and checking its work. Before you start, make sure you have the following tools and knowledge:

  • Python 3.10 or newer: The sample project runs on any recent Python version.
  • Working knowledge of pytest: This guide uses pytest but doesn’t teach it. If you need a refresher, then check out the tutorial on effective Python testing with pytest.
  • An AI coding agent: This guide uses Claude Code, but any agent that can read code, edit code, and run commands will work.
  • Git: You’ll use Git to review everything the agent writes before you accept it.
  • pytest, pytest-cov, and mutmut: You’ll add these tools in Step 1. pytest-cov builds on Coverage.py. To learn pytest in depth, check out the Testing Your Code With pytest video course.
  • uv: The sample project uses uv to manage its dependencies and run commands. If you don’t have it yet, follow the installation instructions.
  • macOS, Linux, or WSL: The mutmut tool doesn’t run natively on Windows. If you’re on Windows, work through this guide in a WSL terminal.
  • The sample project: You can download the bookstore package using the link above.

The download contains the finished project, including the tests/ folder, BEHAVIOR.md, CLAUDE.md, and the extract-behavior skill under .claude/skills/, plus the testing configuration in pyproject.toml. As a bonus, you can copy the skill into any other project and reuse it as is.

To follow along from scratch, delete tests/, .claude/, BEHAVIOR.md, and CLAUDE.md. Then remove everything but the [project] table from pyproject.toml. You’ll have the following structure:

bookstore-project/
│
├── bookstore/
│   │
│   ├── data/
│   │   └── books.json
│   │
│   ├── __init__.py
│   ├── catalog.py
│   ├── inventory.py
│   └── pricing.py
│
├── main.py
├── pyproject.toml
├── README.md
└── uv.lock

The bookstore package models a small online bookshop with three modules:

  • pricing.py computes what a customer pays, including volume and member discounts, shipping, and country tax. You’ll use it as the running example.
  • catalog.py loads book records from data/books.json and looks them up by ISBN or author.
  • inventory.py tracks the copies on hand and reserves, releases, and ships them for orders.

This is your starting point. Go ahead and commit the project to Git before moving on so that you can inspect every change the agent makes.

Step 1: Set Up Testing Conventions and Environment

The first step is to write down the testing conventions for the project. The agent must follow these rules every time it writes a test. In this tutorial, you’ll use Claude Code, which reads CLAUDE.md from the project root. This file is a good place to put the rules.

Create CLAUDE.md and add the following sections. The rules refer to BEHAVIOR.md, which lists what each function should return or raise. You’ll create and review that file in Step 2:

Language: Markdown Text Filename: CLAUDE.md
## Testing Conventions

Write tests with `pytest`. Put them in `tests/test_<module>.py`, mirroring
the package layout.

### Test Structure

- Arrange, act, assert, in that order, separated by blank lines.
- One behavior per test. If the name needs an "and", split the test.
- Name tests `test_<unit>_<condition>_<expected>()`.
- Use `@pytest.mark.parametrize` for table-driven cases, not loops.

### Assertions

- Assert exact values, not just types: `assert total == Decimal("190.00")`,
  not `assert isinstance(total, Decimal)`.
- Take expected values from `BEHAVIOR.md`. Never call the code under
  test to produce an expected value, and never reimplement its
  arithmetic in the test.
- Match the full exception message, anchored with `^` and `$`:
  `pytest.raises(ValueError, match="^unknown tier: gold$")`.
  Wrap messages that contain regex special characters in `re.escape()`.
  Never `pytest.raises(Exception)`.
- Assert on returned values and raised errors, not on
  `assert_called_once_with`.

### Test Coverage

- Parametrize both sides of every boundary in `BEHAVIOR.md`. For a
  threshold at 10, test 9, 10, and 11.
- One test per error path.
- Cover empty, missing, and zero inputs.

### Mocking Conventions

- Mock only what you can't control or can't afford: clocks, randomness,
  network calls, subprocesses, slow or destructive operations.
- Never mock the module under test.
- Never mock code we own just to avoid setting it up. Use a
  fixture instead.
- For files, use `tmp_path` and real files rather than patching `open`.

### Quality Gates

Before reporting a suite as done, run these yourself and keep working until
they pass:

- `pytest` passes.
- `pytest --cov=<module> --cov-branch --cov-report=term-missing` reports at
  least 95% branch coverage on the module under test.

Then report the coverage number.

These rules tell the agent where tests go, what a useful assertion looks like, which cases it must cover, and when it’s allowed to mock. The mocking rules matter more than you might expect. Every piece of code that a test replaces with a mock is code the suite no longer checks.

The Quality Gates section is the most important part. Why put the coverage goal here rather than in each prompt? Because standing instructions give you consistent behavior across sessions. The agent knows it isn’t done until the tests pass and the suite meets the coverage goal, and your prompts can stay short.

Next, add the testing configuration to pyproject.toml, keeping the project’s existing settings:

Language: TOML Filename: pyproject.toml
[dependency-groups]
dev = [
    "pytest==9.1.1",
    "pytest-cov==7.1.0",
    "coverage==7.15.4",
    "mutmut==3.7.0",
]

[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["."]

[tool.coverage.run]
branch = true
source = ["bookstore"]

[tool.coverage.report]
show_missing = true

[tool.mutmut]
source_paths = ["bookstore"]

The dev dependency group pins the testing tools. The pythonpath setting lets pytest import bookstore from the project root. The coverage settings turn on branch measurement for the bookstore package, and the [tool.mutmut] table tells mutmut which code to mutate.

The sample project uses uv to manage its dependencies. To install them, including the testing tools, run the following command from the project root:

Language: Shell
$ uv sync

This command creates a virtual environment in .venv/ and installs the project’s dependencies along with the dev group, which uv includes by default. You don’t need to activate the environment. When you prefix a command with uv run, uv runs it inside the environment for you.

Up to this point, you’ve written down the rules the agent will follow and the gates that tell it when it’s done. Next, you’ll find out what to test.

Step 2: Extract the Project Behavior

Before the agent writes a single test, it needs to know what the code is supposed to do. Getting that right is the goal of this step.

You can split the work by package or module depending on the project’s complexity. This keeps each session focused and avoids cluttering the agent’s context window. Start with the module that has the most branching logic, because that’s where bugs tend to hide. In the bookstore package, that’s the pricing.py module.

Unlike the testing conventions, which apply every time the agent writes or updates a test, behavior extraction is a job you run once per module. Its instructions don’t need to stay in the agent’s context for the whole session, so they’re a good fit for a skill. Claude Code loads a skill’s instructions only when the skill is invoked, and you can reuse the same skill on any project.

Go ahead and create .claude/skills/extract-behavior/SKILL.md in the project root, adding the directories in that path as needed. Then add the following content to the file:

Language: Markdown Text Filename: .claude/skills/extract-behavior/SKILL.md
---
name: extract-behavior
description: Extracts the intended behavior of a Python module or package
  into BEHAVIOR.md as reviewable tables. Use before writing tests.
argument-hint: <path/to/module.py | path/to/package/>
disable-model-invocation: true
---

# Extract Behavior

Extract the intended behavior of `$ARGUMENTS` into `BEHAVIOR.md`.

## Steps

1. Collect the target modules:
   - If `$ARGUMENTS` is a `.py` file, the target is that module.
   - If it's a directory, the targets are all `.py` files under it,
     recursively, in path order. Skip test files and files whose names
     start with an underscore (`_`).
2. Carefully read the package that contains the targets and map it: list
   each module's public callables, their parameters, branches, error
   paths, and external dependencies.
3. For each target module, write its section group in `BEHAVIOR.md` at
   the project root. Start the group with a `` # `<module path>` ``
   heading, then write one section per public callable. Include every
   decision point, boundary, error, and edge case. Replace any existing
   group for the module, and leave the other groups alone.
4. Report the modules and sections you wrote, and every row marked
   NEEDS REVIEW.

Don't write tests or edit any code.

## Template

Use this template for every section:

    ## `<callable>(<parameters>)`

    <One sentence on what the callable returns or does.>

    Source: <docstring, comment, or requirement>.

    | <parameter> | expected                         | note     |
    | ----------- | -------------------------------- | -------- |
    | <value>     | <exact return value>             | boundary |
    | <value>     | raises <Error>: "<full message>" | error    |

## Rules

- Add one column per parameter. For stateful code, add a `given` column
  first to record the starting state.
- One row per case. Write boundaries as concrete rows on both sides,
  never as ranges.
- Start each note with happy, boundary, edge, or error.
- Mark values inferred only from the implementation as NEEDS REVIEW.

The YAML frontmatter gives the skill its name and tells the agent what it does. Setting disable-model-invocation to true means the skill runs only when you call it, so the agent won’t start extracting behavior on its own.

When you invoke the skill, Claude Code replaces $ARGUMENTS with the path you provide. This can be the path to a single module or a package directory. Given a directory, the agent walks it recursively and writes one group of sections per module, each under a heading with the module’s path.

The template gives the agent a fixed layout for every section, so the tables stay consistent from one module or session to the next.

Now go ahead and start a Claude Code session in the project root and invoke the skill on pricing.py:

Language: Text Filename: Claude Code session
❯ /extract-behavior bookstore/pricing.py

Claude Code will load the skill, start the workflow, and create BEHAVIOR.md. At this point, the file will include only the sections for the pricing.py module. Here’s how the section for the volume_discount() function should look:

Language: Markdown Text Filename: BEHAVIOR.md
## `volume_discount(quantity)`

Returns the bulk discount rate: 5% for 10 or more books and 12% for 50 or
more.

Source: docstring.

| quantity | expected                                       | note     |
| -------- | ---------------------------------------------- | -------- |
| -1       | raises ValueError: "quantity must be positive" | error    |
| 0        | raises ValueError: "quantity must be positive" | error    |
| 1        | Decimal("0.00")                                | edge     |
| 9        | Decimal("0.00")                                | boundary |
| 10       | Decimal("0.05")                                | boundary |
| 11       | Decimal("0.05")                                | boundary |
| 49       | Decimal("0.05")                                | boundary |
| 50       | Decimal("0.12")                                | boundary |
| 51       | Decimal("0.12")                                | boundary |

The section starts with the function’s signature as its title, followed by a summary of what the function does. The Source line records where the expected values come from.

In the table, you have one input column because the function takes only one argument, quantity. The expected column defines what the function returns or raises. Finally, the note column labels each row as a happy, boundary, edge, or error case.

Because volume_discount() is a pure function, it doesn’t need a given column. For stateful code, such as a shopping cart, add a given column to record the starting state for each row.

The discount starts at ten books, so the table has concrete rows at nine, ten, and eleven instead of a range like quantity >= 10. It follows the same pattern around the fifty-book tier. Each error row holds the exception and its full message, which is exactly what pytest.raises() needs.

To see why the rows on both sides of the threshold matter, change the comparison in the code below and compare a suite that tests 9, 10, and 11 with one that tests only 10:

Interactive diagram — enable JavaScript to view.

Because bookstore is a small package, go ahead and rerun the skill on the whole directory with /extract-behavior bookstore/ to extract the behavior of every module in one go. On a larger project, stick to one module or subpackage per session to keep the agent’s context focused and the behavior extraction manageable.

Then comes the part that only you can do: review the behavior tables. Compare each row against what the code should do, using the docstrings, expected arguments, return branches, raised exceptions, and anything else that documents the intended behavior. Correct any inaccurate rows, resolve all NEEDS REVIEW flags, and fix any section that doesn’t follow the template.

This thorough review will help you produce an accurate test suite. The agent can find every branch in the code, but it can’t tell whether quantity >= 10 is the intended rule or a bug. If you skip the review, then the tests will lock in whatever the code does today, bugs included.

Click the Show/Hide toggle below to see the reviewed BEHAVIOR.md file for the whole sample project:

Language: Markdown Text Filename: BEHAVIOR.md
# Bookstore Behavior

Intended behavior of the `bookstore` package, one section per public
callable. Rows are checked against the docstrings and the pricing tables.
Money values are `Decimal`, and prices in the catalog are strings.

# `bookstore/pricing.py`

## `volume_discount(quantity)`

Returns the bulk discount rate: 5% for 10 or more books and 12% for 50 or
more.

Source: docstring.

| quantity | expected                                       | note     |
| -------- | ---------------------------------------------- | -------- |
| -1       | raises ValueError: "quantity must be positive" | error    |
| 0        | raises ValueError: "quantity must be positive" | error    |
| 1        | Decimal("0.00")                                | edge     |
| 9        | Decimal("0.00")                                | boundary |
| 10       | Decimal("0.05")                                | boundary |
| 11       | Decimal("0.05")                                | boundary |
| 49       | Decimal("0.05")                                | boundary |
| 50       | Decimal("0.12")                                | boundary |
| 51       | Decimal("0.12")                                | boundary |

## `member_discount(member_tier)`

Returns the discount rate for a membership tier.

Source: `MEMBER_DISCOUNTS` table.

| member_tier | expected                                | note  |
| ----------- | --------------------------------------- | ----- |
| "none"      | Decimal("0.00")                         | happy |
| "plus"      | Decimal("0.05")                         | happy |
| "pro"       | Decimal("0.10")                         | happy |
| "gold"      | raises ValueError: "unknown tier: gold" | error |
| ""          | raises ValueError: "unknown tier: "     | edge  |

## `tax_rate(country)`

Returns the sales tax rate for a country code.

Source: `TAX_RATES` table.

| country | expected                                 | note  |
| ------- | ---------------------------------------- | ----- |
| "US"    | Decimal("0.00")                          | happy |
| "GB"    | Decimal("0.20")                          | happy |
| "DE"    | Decimal("0.19")                          | happy |
| "FR"    | raises ValueError: "unknown country: FR" | error |

## `shipping_cost(subtotal)`

Returns the shipping charge for a discounted subtotal: free from $35.00,
and $4.99 below that.

Source: docstring, `FREE_SHIPPING_THRESHOLD`, and `SHIPPING_FEE`.

| subtotal         | expected        | note     |
| ---------------- | --------------- | -------- |
| Decimal("0.00")  | Decimal("4.99") | edge     |
| Decimal("34.99") | Decimal("4.99") | boundary |
| Decimal("35.00") | Decimal("0.00") | boundary |
| Decimal("35.01") | Decimal("0.00") | boundary |

## `quote_order(quantity, unit_price, member_tier="none", country="US")`

Returns the total the customer pays. Applies the volume and member
discounts one after the other, rounds the subtotal to cents, adds
shipping, then adds tax on the subtotal and shipping and rounds the
total to cents. Both roundings go half up.

Source: docstring and the callables above.

| quantity | unit_price | member_tier | country   | expected                                             | note                                              |
| -------- | ---------- | ----------- | --------- | ---------------------------------------------------- | ------------------------------------------------- |
| 1        | "39.99"    | "none"      | "US"      | Decimal("39.99")                                     | happy, ships free                                 |
| 1        | "20.00"    | "none"      | "US"      | Decimal("24.99")                                     | happy, adds shipping                              |
| 1        | "20.00"    | (omitted)   | (omitted) | Decimal("24.99")                                     | happy, defaults to a US non-member                |
| 1        | "34.99"    | "none"      | "US"      | Decimal("39.98")                                     | boundary, pays shipping                           |
| 1        | "35.00"    | "none"      | "US"      | Decimal("35.00")                                     | boundary, ships free                              |
| 1        | "0.00"     | "none"      | "US"      | Decimal("4.99")                                      | edge, free book still pays shipping               |
| 10       | "39.99"    | "none"      | "US"      | Decimal("379.91")                                    | happy, volume discount, 379.905 rounds half up    |
| 2        | "20.00"    | "pro"       | "US"      | Decimal("36.00")                                     | happy, member discount, ships free                |
| 2        | "18.00"    | "plus"      | "US"      | Decimal("39.19")                                     | edge, discount drops subtotal below free shipping |
| 1        | "20.00"    | "none"      | "GB"      | Decimal("29.99")                                     | happy, tax applies to shipping too                |
| 1        | "35.50"    | "none"      | "DE"      | Decimal("42.25")                                     | edge, tax rounds half up                          |
| 50       | "10.00"    | "pro"       | "GB"      | Decimal("475.20")                                    | happy, every discount and tax combined            |
| 0        | "10.00"    | "none"      | "US"      | raises ValueError: "quantity must be positive"       | error                                             |
| 1        | "-0.01"    | "none"      | "US"      | raises ValueError: "unit price must not be negative" | error                                             |
| 1        | "10.00"    | "gold"      | "US"      | raises ValueError: "unknown tier: gold"              | error                                             |
| 1        | "10.00"    | "none"      | "FR"      | raises ValueError: "unknown country: FR"             | error                                             |

# `bookstore/catalog.py`

Each record has `isbn`, `title`, `author`, and `price` keys.

## `Catalog(path=None)`

Creates a read-only catalog backed by a JSON file, without reading the
file yet.

Source: class docstring and `DEFAULT_CATALOG_PATH`.

| path                   | expected                                                             | note  |
| ---------------------- | -------------------------------------------------------------------- | ----- |
| (omitted)              | `.books` has the four ISBNs in `bookstore/data/books.json`, in order | happy |
| path to a missing file | no error, and `.path` is that path                                   | edge  |

## `Catalog.books`

Returns every record keyed by ISBN, reading the file on first access.

Source: property docstring.

| given                                 | expected                                                                  | note  |
| ------------------------------------- | ------------------------------------------------------------------------- | ----- |
| file with two records                 | dict of both records keyed by ISBN                                        | happy |
| file with `[]`                        | `{}`                                                                      | edge  |
| `.books` already read, file rewritten | the original records, since the file is read once                         | edge  |
| path to a missing file                | raises FileNotFoundError: "[Errno 2] No such file or directory: '<path>'" | error |

## `Catalog.load()`

Reads and parses the catalog file, and returns the catalog itself.

Source: method docstring.

| given                                 | expected                            | note  |
| ------------------------------------- | ----------------------------------- | ----- |
| a valid catalog file                  | returns the same `Catalog` instance | happy |
| `.books` already read, file rewritten | `.books` has the new records        | happy |

## `Catalog.get(isbn)`

Returns the record for one ISBN.

Source: method docstring.

| given                 | isbn    | expected                             | note  |
| --------------------- | ------- | ------------------------------------ | ----- |
| file with two records | stocked | that record's dict                   | happy |
| file with two records | "000"   | raises KeyError: "unknown isbn: 000" | error |

## `Catalog.price_of(isbn)`

Returns the list price of one book, as stored in the file.

Source: method docstring.

| given                     | isbn    | expected                             | note  |
| ------------------------- | ------- | ------------------------------------ | ----- |
| record with price "39.99" | stocked | "39.99"                              | happy |
| file with two records     | "000"   | raises KeyError: "unknown isbn: 000" | error |

## `Catalog.by_author(author)`

Returns every record by an author, in catalog order.

Source: method docstring.

| given                                    | author      | expected                       | note  |
| ---------------------------------------- | ----------- | ------------------------------ | ----- |
| two books by "Dan Bader", one by another | "Dan Bader" | both records, in catalog order | happy |
| no books by the author                   | "Nobody"    | `[]`                           | edge  |

# `bookstore/inventory.py`

`available` is always `on_hand - reserved`.

## `Inventory(stock=None)`

Creates an inventory that keeps its own copy of the on-hand counts.

Source: class docstring.

| stock                            | expected                  | note  |
| -------------------------------- | ------------------------- | ----- |
| `{"A": 5}`                       | `on_hand("A")` is 5       | happy |
| (omitted)                        | `on_hand("A")` is 0       | edge  |
| `{"A": 5}`, caller then edits it | `on_hand("A")` is still 5 | edge  |

## `Inventory.on_hand(isbn)`

Returns the copies physically in the warehouse.

Source: method docstring.

| given      | isbn | expected | note  |
| ---------- | ---- | -------- | ----- |
| `{"A": 5}` | "A"  | 5        | happy |
| `{"A": 5}` | "B"  | 0        | edge  |

## `Inventory.reserved(isbn)`

Returns the copies held for orders that haven't shipped.

Source: method docstring.

| given      | isbn | expected | note |
| ---------- | ---- | -------- | ---- |
| `{"A": 5}` | "A"  | 0        | edge |

## `Inventory.available(isbn)`

Returns the copies that can still be reserved.

Source: method docstring.

| given      | isbn | expected | note  |
| ---------- | ---- | -------- | ----- |
| `{"A": 5}` | "A"  | 5        | happy |

## `Inventory.reserve(isbn, quantity)`

Holds copies for an order and returns what's left available.

Source: method docstring.

| given                  | isbn | quantity | expected                                             | note     |
| ---------------------- | ---- | -------- | ---------------------------------------------------- | -------- |
| `{"A": 5}`             | "A"  | 2        | returns 3, `reserved("A")` is 2, `on_hand("A")` is 5 | happy    |
| `{"A": 5}`, 2 reserved | "A"  | 1        | returns 2, `reserved("A")` is 3                      | happy    |
| `{"A": 5}`             | "A"  | 5        | returns 0                                            | boundary |
| `{"A": 5}`             | "A"  | 6        | raises ValueError: "only 5 copies of A available"    | boundary |
| `{"A": 5}`, 2 reserved | "A"  | 4        | raises ValueError: "only 3 copies of A available"    | boundary |
| `{"A": 5}`             | "A"  | 0        | raises ValueError: "quantity must be positive"       | error    |
| `{"A": 5}`             | "B"  | 1        | raises KeyError: "unknown isbn: B"                   | error    |

## `Inventory.release(isbn, quantity)`

Puts held copies back in the pool and returns what's available.

Source: method docstring.

| given                  | isbn | quantity | expected                                               | note     |
| ---------------------- | ---- | -------- | ------------------------------------------------------ | -------- |
| `{"A": 5}`, 3 reserved | "A"  | 1        | returns 3, `reserved("A")` is 2                        | happy    |
| `{"A": 5}`, 3 reserved | "A"  | 3        | returns 5, `reserved("A")` is 0                        | boundary |
| `{"A": 5}`, 3 reserved | "A"  | 4        | raises ValueError: "cannot release 4, only 3 reserved" | boundary |
| `{"A": 5}`             | "A"  | 0        | raises ValueError: "quantity must be positive"         | error    |
| `{"A": 5}`             | "B"  | 1        | raises KeyError: "unknown isbn: B"                     | error    |

## `Inventory.commit(isbn, quantity)`

Ships held copies, removes them from stock, and returns what's on hand.

Source: method docstring.

| given                  | isbn | quantity | expected                                               | note     |
| ---------------------- | ---- | -------- | ------------------------------------------------------ | -------- |
| `{"A": 5}`, 3 reserved | "A"  | 2        | returns 3, `reserved("A")` is 1, `available("A")` is 2 | happy    |
| `{"A": 5}`, 3 reserved | "A"  | 3        | returns 2, `reserved("A")` is 0                        | boundary |
| `{"A": 5}`, 3 reserved | "A"  | 4        | raises ValueError: "cannot ship 4, only 3 reserved"    | boundary |
| `{"A": 5}`             | "A"  | 0        | raises ValueError: "quantity must be positive"         | error    |
| `{"A": 5}`             | "B"  | 1        | raises KeyError: "unknown isbn: B"                     | error    |

With BEHAVIOR.md reviewed, you now have a written record of what each callable should do, with a source for every expected value. Next, you’ll hand that record to the agent and let it turn each table row into a test.

Step 3: Generate Python Tests With AI

In this step, you’ll generate the test suite by giving the agent your code’s behavior tables. You’ve already established your testing conventions and coverage goal in CLAUDE.md, so the prompt needs only the details that change.

Go ahead and send the following prompt to your agent so it writes tests for the bookstore/pricing.py module:

Language: Text Filename: Claude Code session
❯ Write tests for @bookstore/pricing.py from its corresponding sections in
  @BEHAVIOR.md. Only create or edit files under tests/.

From here, the agent works on its own. It writes the tests, runs pytest, checks coverage, adds tests for any branches it missed, and reruns everything until the suite meets the coverage goal.

Here’s the part of tests/test_pricing.py that the agent generated for the volume_discount() function:

Language: Python Filename: tests/test_pricing.py
from decimal import Decimal

import pytest

from bookstore.pricing import volume_discount

@pytest.mark.parametrize(
    ("quantity", "expected"),
    [
        (1, Decimal("0.00")),
        (9, Decimal("0.00")),
        (10, Decimal("0.05")),
        (11, Decimal("0.05")),
        (49, Decimal("0.05")),
        (50, Decimal("0.12")),
        (51, Decimal("0.12")),
    ],
)
def test_volume_discount_by_quantity_returns_rate(quantity, expected):
    result = volume_discount(quantity)

    assert result == expected

def test_volume_discount_returns_decimal():
    assert isinstance(volume_discount(10), Decimal)

def test_volume_discount_applies_rule():
    quantity = 10
    expected = Decimal("0.05") if quantity >= 10 else Decimal("0.00")

    assert volume_discount(quantity) == expected

@pytest.mark.parametrize("quantity", [-1, 0])
def test_volume_discount_non_positive_quantity_raises_value_error(quantity):
    with pytest.raises(ValueError, match="quantity must be positive"):
        volume_discount(quantity)

In the first test, each table row becomes one parametrize case, and the expected values are Decimal literals copied from BEHAVIOR.md. If the case for quantity=10 fails, then the test report tells you exactly which boundary broke. The error rows get their own parametrized test, with a match argument that checks the message from the table.

After running the prompt on a module, you can start a new agent session to keep the context from growing so long that it reduces the quality of the generated tests.

Once you’ve used the prompt for every module, you’ll have one test file per module. Expand each section to see what the agent generated for the sample project on its first pass:

Language: Python Filename: tests/test_pricing.py
from decimal import Decimal

import pytest

from bookstore.pricing import (
    member_discount,
    quote_order,
    shipping_cost,
    tax_rate,
    volume_discount,
)

@pytest.mark.parametrize(
    ("quantity", "expected"),
    [
        (1, Decimal("0.00")),
        (9, Decimal("0.00")),
        (10, Decimal("0.05")),
        (11, Decimal("0.05")),
        (49, Decimal("0.05")),
        (50, Decimal("0.12")),
        (51, Decimal("0.12")),
    ],
)
def test_volume_discount_by_quantity_returns_rate(quantity, expected):
    result = volume_discount(quantity)

    assert result == expected

def test_volume_discount_returns_decimal():
    assert isinstance(volume_discount(10), Decimal)

def test_volume_discount_applies_rule():
    quantity = 10
    expected = Decimal("0.05") if quantity >= 10 else Decimal("0.00")

    assert volume_discount(quantity) == expected

@pytest.mark.parametrize("quantity", [-1, 0])
def test_volume_discount_non_positive_quantity_raises_value_error(quantity):
    with pytest.raises(ValueError, match="quantity must be positive"):
        volume_discount(quantity)

@pytest.mark.parametrize(
    ("member_tier", "expected"),
    [
        ("none", Decimal("0.00")),
        ("plus", Decimal("0.05")),
        ("pro", Decimal("0.10")),
    ],
)
def test_member_discount_known_tier_returns_rate(member_tier, expected):
    result = member_discount(member_tier)

    assert result == expected

def test_member_discount_unknown_tier_raises_value_error():
    with pytest.raises(ValueError, match="unknown tier: gold"):
        member_discount("gold")

def test_member_discount_empty_tier_raises_value_error():
    with pytest.raises(ValueError, match="unknown tier: "):
        member_discount("")

@pytest.mark.parametrize(
    ("country", "expected"),
    [
        ("US", Decimal("0.00")),
        ("GB", Decimal("0.20")),
        ("DE", Decimal("0.19")),
    ],
)
def test_tax_rate_known_country_returns_rate(country, expected):
    result = tax_rate(country)

    assert result == expected

def test_tax_rate_unknown_country_raises_value_error():
    with pytest.raises(ValueError, match="unknown country: FR"):
        tax_rate("FR")

@pytest.mark.parametrize(
    ("subtotal", "expected"),
    [
        (Decimal("0.00"), Decimal("4.99")),
        (Decimal("34.99"), Decimal("4.99")),
        (Decimal("35.00"), Decimal("0.00")),
        (Decimal("35.01"), Decimal("0.00")),
    ],
)
def test_shipping_cost_by_subtotal_returns_charge(subtotal, expected):
    result = shipping_cost(subtotal)

    assert result == expected

@pytest.mark.parametrize(
    ("quantity", "unit_price", "member_tier", "country", "expected"),
    [
        (1, "39.99", "none", "US", Decimal("39.99")),
        (1, "20.00", "none", "US", Decimal("24.99")),
        (1, "34.99", "none", "US", Decimal("39.98")),
        (1, "35.00", "none", "US", Decimal("35.00")),
        (1, "0.00", "none", "US", Decimal("4.99")),
        (10, "39.99", "none", "US", Decimal("379.91")),
        (2, "20.00", "pro", "US", Decimal("36.00")),
        (2, "18.00", "plus", "US", Decimal("39.19")),
        (1, "20.00", "none", "GB", Decimal("29.99")),
        (1, "35.50", "none", "DE", Decimal("42.25")),
        (50, "10.00", "pro", "GB", Decimal("475.20")),
    ],
)
def test_quote_order_valid_order_returns_total(
    quantity, unit_price, member_tier, country, expected
):
    result = quote_order(quantity, unit_price, member_tier, country)

    assert result == expected

def test_quote_order_default_tier_and_country_prices_as_us_non_member():
    result = quote_order(1, "20.00")

    assert result == Decimal("24.99")

def test_quote_order_zero_quantity_raises_value_error():
    with pytest.raises(ValueError, match="quantity must be positive"):
        quote_order(0, "10.00")

def test_quote_order_negative_unit_price_raises_value_error():
    with pytest.raises(ValueError, match="unit price must not be negative"):
        quote_order(1, "-0.01")

def test_quote_order_unknown_tier_raises_value_error():
    with pytest.raises(ValueError, match="unknown tier: gold"):
        quote_order(1, "10.00", member_tier="gold")

def test_quote_order_unknown_country_raises_value_error():
    with pytest.raises(ValueError, match="unknown country: FR"):
        quote_order(1, "10.00", country="FR")
Language: Python Filename: tests/test_catalog.py
import json
from unittest.mock import patch

import pytest

from bookstore.catalog import Catalog

PYTHON_TRICKS = {
    "isbn": "978-1775093305",
    "title": "Python Tricks",
    "author": "Dan Bader",
    "price": "29.99",
}
MANAGING_DEPENDENCIES = {
    "isbn": "978-1775093312",
    "title": "Managing Python Dependencies",
    "author": "Dan Bader",
    "price": "24.99",
}
PYTHON_BASICS = {
    "isbn": "978-1775093329",
    "title": "Python Basics",
    "author": "Real Python",
    "price": "39.99",
}

def write_catalog(path, records):
    path.write_text(json.dumps(records), encoding="utf-8")
    return path

@pytest.fixture
def catalog_path(tmp_path):
    return write_catalog(
        tmp_path / "books.json", [PYTHON_TRICKS, PYTHON_BASICS]
    )

@pytest.fixture
def catalog(catalog_path):
    return Catalog(catalog_path)

def test_catalog_default_path_reads_bundled_books():
    catalog = Catalog()

    result = list(catalog.books)

    assert result == [
        "978-1775093329",
        "978-1775093305",
        "978-1775093312",
        "978-1775093350",
    ]

def test_catalog_missing_file_constructs_without_reading(tmp_path):
    catalog = Catalog(tmp_path / "missing.json")

    assert catalog.path == tmp_path / "missing.json"

def test_catalog_books_missing_file_raises_file_not_found(tmp_path):
    catalog = Catalog(tmp_path / "missing.json")

    with pytest.raises(FileNotFoundError, match="No such file or directory"):
        catalog.books

def test_catalog_books_two_records_returns_dict_by_isbn(catalog):
    result = catalog.books

    assert result == {
        "978-1775093305": PYTHON_TRICKS,
        "978-1775093329": PYTHON_BASICS,
    }

def test_catalog_books_empty_file_returns_empty_dict(tmp_path):
    catalog = Catalog(write_catalog(tmp_path / "books.json", []))

    result = catalog.books

    assert result == {}

def test_catalog_books_second_access_reads_file_once(catalog):
    with patch("pathlib.Path.read_text", return_value="[]") as read_text:
        catalog.books
        catalog.books

    read_text.assert_called_once()

def test_catalog_load_file_rewritten_after_read_returns_new_records(
    catalog, catalog_path
):
    catalog.books
    write_catalog(catalog_path, [MANAGING_DEPENDENCIES])

    catalog.load()

    assert catalog.books == {"978-1775093312": MANAGING_DEPENDENCIES}

def test_catalog_load_valid_file_returns_same_instance(catalog):
    result = catalog.load()

    assert result is catalog

def test_catalog_get_stocked_isbn_returns_record(catalog):
    result = catalog.get("978-1775093329")

    assert result == PYTHON_BASICS

def test_catalog_get_unknown_isbn_raises_key_error(catalog):
    with pytest.raises(KeyError, match="unknown isbn: 000"):
        catalog.get("000")

def test_catalog_price_of_stocked_isbn_returns_price(catalog):
    result = catalog.price_of("978-1775093329")

    assert result == "39.99"

def test_catalog_price_of_unknown_isbn_raises_key_error(catalog):
    with pytest.raises(KeyError, match="unknown isbn: 000"):
        catalog.price_of("000")

def test_catalog_by_author_two_books_returns_both_in_order(tmp_path):
    path = write_catalog(
        tmp_path / "books.json",
        [PYTHON_TRICKS, PYTHON_BASICS, MANAGING_DEPENDENCIES],
    )
    catalog = Catalog(path)

    result = catalog.by_author("Dan Bader")

    assert result == [PYTHON_TRICKS, MANAGING_DEPENDENCIES]

def test_catalog_by_author_no_books_returns_empty_list(catalog):
    result = catalog.by_author("Nobody")

    assert result == []
Language: Python Filename: tests/test_inventory.py
import pytest

from bookstore.inventory import Inventory

@pytest.fixture
def inventory():
    return Inventory({"A": 5})

@pytest.fixture
def held_inventory():
    inventory = Inventory({"A": 5})
    inventory.reserve("A", 3)
    return inventory

def test_inventory_on_hand_stocked_isbn_returns_count(inventory):
    result = inventory.on_hand("A")

    assert result == 5

def test_inventory_on_hand_unknown_isbn_returns_zero(inventory):
    result = inventory.on_hand("B")

    assert result == 0

def test_inventory_reserved_nothing_held_returns_zero(inventory):
    result = inventory.reserved("A")

    assert result == 0

def test_inventory_available_nothing_held_returns_on_hand(inventory):
    result = inventory.available("A")

    assert result == 5

def test_inventory_no_stock_on_hand_returns_zero():
    inventory = Inventory()

    result = inventory.on_hand("A")

    assert result == 0

def test_inventory_caller_edits_stock_dict_keeps_own_copy():
    stock = {"A": 5}
    inventory = Inventory(stock)
    stock["A"] = 1

    result = inventory.on_hand("A")

    assert result == 5

def test_inventory_reserve_some_copies_returns_available(inventory):
    result = inventory.reserve("A", 2)

    assert result == 3
    assert inventory.reserved("A") == 2
    assert inventory.on_hand("A") == 5

def test_inventory_reserve_again_adds_to_held(inventory):
    inventory.reserve("A", 2)

    result = inventory.reserve("A", 1)

    assert result == 2
    assert inventory.reserved("A") == 3

@pytest.mark.parametrize(
    ("already_reserved", "quantity", "message"),
    [
        (0, 6, "only 5 copies of A available"),
        (2, 4, "only 3 copies of A available"),
    ],
)
def test_inventory_reserve_more_than_available_raises_value_error(
    inventory, already_reserved, quantity, message
):
    if already_reserved:
        inventory.reserve("A", already_reserved)

    with pytest.raises(ValueError, match=message):
        inventory.reserve("A", quantity)

def test_inventory_reserve_zero_quantity_raises_value_error(inventory):
    with pytest.raises(ValueError, match="quantity must be positive"):
        inventory.reserve("A", 0)

def test_inventory_reserve_unknown_isbn_raises_key_error(inventory):
    with pytest.raises(KeyError, match="unknown isbn: B"):
        inventory.reserve("B", 1)

def test_inventory_release_some_copies_returns_available(held_inventory):
    result = held_inventory.release("A", 1)

    assert result == 3
    assert held_inventory.reserved("A") == 2

def test_inventory_release_all_held_returns_on_hand(held_inventory):
    result = held_inventory.release("A", 3)

    assert result == 5
    assert held_inventory.reserved("A") == 0

def test_inventory_release_more_than_held_raises_value_error(
    held_inventory,
):
    with pytest.raises(ValueError, match="cannot release 4, only 3 reserved"):
        held_inventory.release("A", 4)

def test_inventory_release_zero_quantity_raises_value_error(inventory):
    with pytest.raises(ValueError, match="quantity must be positive"):
        inventory.release("A", 0)

def test_inventory_release_unknown_isbn_raises_key_error(inventory):
    with pytest.raises(KeyError, match="unknown isbn: B"):
        inventory.release("B", 1)

def test_inventory_commit_some_held_returns_on_hand(held_inventory):
    result = held_inventory.commit("A", 2)

    assert result == 3
    assert held_inventory.reserved("A") == 1
    assert held_inventory.available("A") == 2

def test_inventory_commit_all_held_returns_on_hand(held_inventory):
    result = held_inventory.commit("A", 3)

    assert result == 2
    assert held_inventory.reserved("A") == 0

def test_inventory_commit_more_than_held_raises_value_error(held_inventory):
    with pytest.raises(ValueError, match="cannot ship 4, only 3 reserved"):
        held_inventory.commit("A", 4)

def test_inventory_commit_zero_quantity_raises_value_error(inventory):
    with pytest.raises(ValueError, match="quantity must be positive"):
        inventory.commit("A", 0)

def test_inventory_commit_unknown_isbn_raises_key_error(inventory):
    with pytest.raises(KeyError, match="unknown isbn: B"):
        inventory.commit("B", 1)

To check the agent’s claim, run the coverage command yourself:

Language: Shell
$ uv run pytest --cov=bookstore --cov-branch --cov-report=term-missing

Each module should show at least 95 percent in the Cover column, and the Missing column lists any lines and branches that no test reached.

Every test passes, and the suite meets the coverage gate. At first glance, your work looks complete. In the next step, you’ll judge the quality of the suite.

Step 4: Confirm the Suite Holds Up

Coverage only tells you which lines and branches the suite runs, not whether the tests would catch a bug in them. That’s what this step is for.

You’ll check the suite in two ways:

  1. A manual review
  2. An automated check

For the manual review, you’ll use a short list of common issues in AI-generated tests to guide your inspection.

For the automated check, you’ll use mutmut, a mutation testing tool that shows whether the suite catches the bugs that coverage alone can’t reveal.

Review the Test Suite Manually

Check the tests against BEHAVIOR.md and the conventions in CLAUDE.md. Every expected value should trace back to a row, and every boundary row should have cases on both sides.

Pay special attention to tests that look reasonable but don’t check anything useful. AI-generated tests tend to go wrong in a few recurring ways:

  • Weak assertions: The test checks a data type, a truthy value, or is not None instead of the exact expected value, so it also passes for wrong results.
  • Mirrored logic: The test computes its expected value by repeating the code’s logic, so a bug in the code becomes a bug in the test.
  • Needless mocks: The test mocks something it could use directly, like code you own or a file it could create in tmp_path. By asserting on calls, it checks how the code works rather than what it returns.
  • Missing boundaries: The test covers one side of a threshold but not the other, so a bug on the uncovered side goes unnoticed.
  • Loose exception checks: The test uses a broad exception check like pytest.raises(Exception) or a match argument that checks only part of the error message.

Your CLAUDE.md rules forbid all of these, so why bother checking? Because agents don’t always follow their instructions.

As an example, go back to the test files from Step 3. First, take a look at this test from test_pricing.py:

Language: Python Filename: tests/test_pricing.py
# ...

def test_volume_discount_applies_rule():
    quantity = 10
    expected = Decimal("0.05") if quantity >= 10 else Decimal("0.00")

    assert volume_discount(quantity) == expected

In this example, the test mirrors the code’s logic. It computes the expected value with the same quantity >= 10 rule that the implementation uses, so the expected value comes from the code rather than from BEHAVIOR.md.

You can delete it without losing coverage because test_volume_discount_by_quantity_returns_rate() already checks quantity=10 against a value from BEHAVIOR.md.

Next, look at how the suite checks error messages:

Language: Python Filename: tests/test_pricing.py
# ...

@pytest.mark.parametrize("quantity", [-1, 0])
def test_volume_discount_non_positive_quantity_raises_value_error(quantity):
    with pytest.raises(ValueError, match="quantity must be positive"):
        volume_discount(quantity)

This is a loose message check. Because the match argument searches anywhere in the message, the test also passes if the code raises "The quantity must be positive and even" or any other variation that contains the target message. Every match pattern in the three files has the same problem.

To fix this issue, use a pattern that matches the whole message with ^ at the beginning and $ at the end:

Language: Python Filename: tests/test_pricing.py
# ...

@pytest.mark.parametrize("quantity", [-1, 0])
def test_volume_discount_non_positive_quantity_raises_value_error(quantity):
    with pytest.raises(ValueError, match="^quantity must be positive$"):
        volume_discount(quantity)

These two aren’t the only issues in the AI-generated suite. Go through the rest of the files yourself, using the list above to flag problems. Then fix them by hand or ask the agent to do so with a prompt that names each issue:

Language: Text Filename: Claude Code session
❯ Fix these issues in tests/, following CLAUDE.md and BEHAVIOR.md:
  - Delete test_volume_discount_applies_rule(). It mirrors the code's rule.
  - Anchor every match pattern to the full message with ^ and $.
  - <One line per issue you found>
  Rerun the quality gates, then report what you changed.

Read the new diff before you move on. If you spot anything else, then ask the agent to fix it for you or fix it yourself.

If you’re following along with the sample project, then your review should also flag these issues:

  • test_volume_discount_returns_decimal() checks only the return type. You can delete it because the parametrized test already asserts exact Decimal values.
  • test_catalog_books_second_access_reads_file_once() patches Path.read_text() and asserts on the call count. Replace it with a test that rewrites the file in tmp_path and checks that .books still returns the original records.
  • test_inventory.py has no test for reserving exactly the five copies available, even though BEHAVIOR.md has a row for it. Add one that expects 0.

The final test files at the end of this step include all of these fixes.

Verify the Test Suite With mutmut

Mutation testing checks whether your tests can catch bugs introduced by changes to the code. A tool like mutmut makes small, deliberate changes to your code and runs the suite against each one. If the suite is robust, then every change that alters the behavior makes at least one test fail.

Each changed version of the code is called a mutant. For example, mutmut might turn quantity >= 10 into quantity > 10 in volume_discount() or pad an error message so that "quantity must be positive" becomes "XXquantity must be positiveXX". When a test fails against a mutant, the mutant is killed.

If the test suite still passes, then the mutant survives, which means the suite wouldn’t notice that change. A survivor usually points to a weak test or a missing case. The padded message is a good example. With the unanchored match patterns from the first-pass suite, that mutant would survive because the original message still appears inside the padded one.

Not every survivor points to a weak test, though. Some mutants change the code without changing what it does. For example, changing encoding="utf-8" to encoding="UTF-8" gives the same result because both strings name the same encoding. These are equivalent mutants, and no test can kill them.

Here’s what that looks like when you run mutmut on catalog.py, with the output trimmed:

Language: Shell
$ uv run mutmut run "bookstore.catalog*"
$ uv run mutmut results
    bookstore.catalog.xǁCatalogǁload__mutmut_4: survived
$ uv run mutmut show "bookstore.catalog.xǁCatalogǁload__mutmut_4"
--- bookstore/catalog.py
+++ bookstore/catalog.py
@@ -1,6 +1,6 @@
 def load(self):
     """Read and parse the catalog file."""
-    text = self.path.read_text(encoding="utf-8")
+    text = self.path.read_text(encoding="UTF-8")
     records = json.loads(text)
     self._books = {record["isbn"]: record for record in records}
     return self

The results command lists each surviving mutant by name, and show prints the change as a diff. In this example, mutmut uppercased the encoding name. Python treats "utf-8" and "UTF-8" as the same codec, so it reads the file the same way in either case. No test could catch the change. That’s an equivalent mutant.

The same line also produces a second equivalent mutant that replaces "utf-8" with None, which makes Python fall back to your system’s default encoding. The catalog file contains only ASCII text, so it reads the same way, and that mutant survives too.

Now ask the agent to run mutmut on the pricing.py module:

Language: Text Filename: Claude Code session
❯ Run mutmut on bookstore/pricing.py. For each surviving mutant:
  - If a BEHAVIOR.md row covers the mutated behavior, add or strengthen
    the tests under tests/ so that they kill the mutant.
  - If no BEHAVIOR.md row covers it, propose the missing row marked
    NEEDS REVIEW, and don't write a test for it yet.
  - If no test could tell the mutant apart from the original code, report
    it as equivalent instead of writing a test.
  Never weaken or delete existing tests. Rerun mutmut until the only
  survivors are the ones you reported, then report the results.

Behind the scenes, the agent runs commands like the following:

Language: Shell
$ uv run mutmut run "bookstore.pricing*"
$ uv run mutmut results

The first command mutates pricing.py and runs the suite against each mutant. The second command lists the survivors.

You can inspect any survivor with uv run mutmut show <mutant-name> or browse them interactively with uv run mutmut browse. The mutmut documentation covers the rest of its commands and options.

When the agent finishes, read its report and the diff. Review any row it proposes before you add it to BEHAVIOR.md, and then ask the agent to write the corresponding test.

For each mutant the agent reports as equivalent, confirm that the change can’t affect the behavior. Then add a # pragma: no mutate comment to that line so that mutmut skips it on the next run. Keep in mind that the pragma skips every mutation on the line, not just the equivalent one, so check that the tests kill the line’s other mutants before you add the pragma.

With the review fixes in place, no mutants survive in pricing.py, including the padded-message mutant, which the anchored patterns now kill.

That’s it! You now have a suite for pricing.py that’s accurate, complete, and robust as far as your reviewed behavior table and mutmut can show. Run mutmut on catalog.py and inventory.py the same way, fix any survivors, and you’ll end up with a test suite you can trust for the whole package.

Expand each section below to see the full suite for each module:

Language: Python Filename: tests/test_pricing.py
from decimal import Decimal

import pytest

from bookstore.pricing import (
    member_discount,
    quote_order,
    shipping_cost,
    tax_rate,
    volume_discount,
)

@pytest.mark.parametrize(
    ("quantity", "expected"),
    [
        (1, Decimal("0.00")),
        (9, Decimal("0.00")),
        (10, Decimal("0.05")),
        (11, Decimal("0.05")),
        (49, Decimal("0.05")),
        (50, Decimal("0.12")),
        (51, Decimal("0.12")),
    ],
)
def test_volume_discount_by_quantity_returns_rate(quantity, expected):
    result = volume_discount(quantity)

    assert result == expected

@pytest.mark.parametrize("quantity", [-1, 0])
def test_volume_discount_non_positive_quantity_raises_value_error(quantity):
    with pytest.raises(ValueError, match="^quantity must be positive$"):
        volume_discount(quantity)

@pytest.mark.parametrize(
    ("member_tier", "expected"),
    [
        ("none", Decimal("0.00")),
        ("plus", Decimal("0.05")),
        ("pro", Decimal("0.10")),
    ],
)
def test_member_discount_known_tier_returns_rate(member_tier, expected):
    result = member_discount(member_tier)

    assert result == expected

def test_member_discount_unknown_tier_raises_value_error():
    with pytest.raises(ValueError, match="^unknown tier: gold$"):
        member_discount("gold")

def test_member_discount_empty_tier_raises_value_error():
    with pytest.raises(ValueError, match="^unknown tier: $"):
        member_discount("")

@pytest.mark.parametrize(
    ("country", "expected"),
    [
        ("US", Decimal("0.00")),
        ("GB", Decimal("0.20")),
        ("DE", Decimal("0.19")),
    ],
)
def test_tax_rate_known_country_returns_rate(country, expected):
    result = tax_rate(country)

    assert result == expected

def test_tax_rate_unknown_country_raises_value_error():
    with pytest.raises(ValueError, match="^unknown country: FR$"):
        tax_rate("FR")

@pytest.mark.parametrize(
    ("subtotal", "expected"),
    [
        (Decimal("0.00"), Decimal("4.99")),
        (Decimal("34.99"), Decimal("4.99")),
        (Decimal("35.00"), Decimal("0.00")),
        (Decimal("35.01"), Decimal("0.00")),
    ],
)
def test_shipping_cost_by_subtotal_returns_charge(subtotal, expected):
    result = shipping_cost(subtotal)

    assert result == expected

@pytest.mark.parametrize(
    ("quantity", "unit_price", "member_tier", "country", "expected"),
    [
        (1, "39.99", "none", "US", Decimal("39.99")),
        (1, "20.00", "none", "US", Decimal("24.99")),
        (1, "34.99", "none", "US", Decimal("39.98")),
        (1, "35.00", "none", "US", Decimal("35.00")),
        (1, "0.00", "none", "US", Decimal("4.99")),
        (10, "39.99", "none", "US", Decimal("379.91")),
        (2, "20.00", "pro", "US", Decimal("36.00")),
        (2, "18.00", "plus", "US", Decimal("39.19")),
        (1, "20.00", "none", "GB", Decimal("29.99")),
        (1, "35.50", "none", "DE", Decimal("42.25")),
        (50, "10.00", "pro", "GB", Decimal("475.20")),
    ],
)
def test_quote_order_valid_order_returns_total(
    quantity, unit_price, member_tier, country, expected
):
    result = quote_order(quantity, unit_price, member_tier, country)

    assert result == expected

def test_quote_order_default_tier_and_country_prices_as_us_non_member():
    result = quote_order(1, "20.00")

    assert result == Decimal("24.99")

def test_quote_order_zero_quantity_raises_value_error():
    with pytest.raises(ValueError, match="^quantity must be positive$"):
        quote_order(0, "10.00")

def test_quote_order_negative_unit_price_raises_value_error():
    with pytest.raises(ValueError, match="^unit price must not be negative$"):
        quote_order(1, "-0.01")

def test_quote_order_unknown_tier_raises_value_error():
    with pytest.raises(ValueError, match="^unknown tier: gold$"):
        quote_order(1, "10.00", member_tier="gold")

def test_quote_order_unknown_country_raises_value_error():
    with pytest.raises(ValueError, match="^unknown country: FR$"):
        quote_order(1, "10.00", country="FR")
Language: Python Filename: tests/test_catalog.py
import json
import re

import pytest

from bookstore.catalog import Catalog

PYTHON_TRICKS = {
    "isbn": "978-1775093305",
    "title": "Python Tricks",
    "author": "Dan Bader",
    "price": "29.99",
}
MANAGING_DEPENDENCIES = {
    "isbn": "978-1775093312",
    "title": "Managing Python Dependencies",
    "author": "Dan Bader",
    "price": "24.99",
}
PYTHON_BASICS = {
    "isbn": "978-1775093329",
    "title": "Python Basics",
    "author": "Real Python",
    "price": "39.99",
}

def write_catalog(path, records):
    path.write_text(json.dumps(records), encoding="utf-8")
    return path

@pytest.fixture
def catalog_path(tmp_path):
    return write_catalog(
        tmp_path / "books.json", [PYTHON_TRICKS, PYTHON_BASICS]
    )

@pytest.fixture
def catalog(catalog_path):
    return Catalog(catalog_path)

def test_catalog_default_path_reads_bundled_books():
    catalog = Catalog()

    result = list(catalog.books)

    assert result == [
        "978-1775093329",
        "978-1775093305",
        "978-1775093312",
        "978-1775093350",
    ]

def test_catalog_missing_file_constructs_without_reading(tmp_path):
    catalog = Catalog(tmp_path / "missing.json")

    assert catalog.path == tmp_path / "missing.json"

def test_catalog_books_missing_file_raises_file_not_found(tmp_path):
    path = tmp_path / "missing.json"
    catalog = Catalog(path)
    message = f"[Errno 2] No such file or directory: '{path}'"

    with pytest.raises(FileNotFoundError, match=f"^{re.escape(message)}$"):
        catalog.books

def test_catalog_books_two_records_returns_dict_by_isbn(catalog):
    result = catalog.books

    assert result == {
        "978-1775093305": PYTHON_TRICKS,
        "978-1775093329": PYTHON_BASICS,
    }

def test_catalog_books_empty_file_returns_empty_dict(tmp_path):
    catalog = Catalog(write_catalog(tmp_path / "books.json", []))

    result = catalog.books

    assert result == {}

def test_catalog_books_file_rewritten_after_read_returns_original(
    catalog, catalog_path
):
    catalog.books
    write_catalog(catalog_path, [MANAGING_DEPENDENCIES])

    result = catalog.books

    assert result == {
        "978-1775093305": PYTHON_TRICKS,
        "978-1775093329": PYTHON_BASICS,
    }

def test_catalog_load_file_rewritten_after_read_returns_new_records(
    catalog, catalog_path
):
    catalog.books
    write_catalog(catalog_path, [MANAGING_DEPENDENCIES])

    catalog.load()

    assert catalog.books == {"978-1775093312": MANAGING_DEPENDENCIES}

def test_catalog_load_valid_file_returns_same_instance(catalog):
    result = catalog.load()

    assert result is catalog

def test_catalog_get_stocked_isbn_returns_record(catalog):
    result = catalog.get("978-1775093329")

    assert result == PYTHON_BASICS

def test_catalog_get_unknown_isbn_raises_key_error(catalog):
    with pytest.raises(KeyError, match="^'unknown isbn: 000'$"):
        catalog.get("000")

def test_catalog_price_of_stocked_isbn_returns_price(catalog):
    result = catalog.price_of("978-1775093329")

    assert result == "39.99"

def test_catalog_price_of_unknown_isbn_raises_key_error(catalog):
    with pytest.raises(KeyError, match="^'unknown isbn: 000'$"):
        catalog.price_of("000")

def test_catalog_by_author_two_books_returns_both_in_order(tmp_path):
    path = write_catalog(
        tmp_path / "books.json",
        [PYTHON_TRICKS, PYTHON_BASICS, MANAGING_DEPENDENCIES],
    )
    catalog = Catalog(path)

    result = catalog.by_author("Dan Bader")

    assert result == [PYTHON_TRICKS, MANAGING_DEPENDENCIES]

def test_catalog_by_author_no_books_returns_empty_list(catalog):
    result = catalog.by_author("Nobody")

    assert result == []
Language: Python Filename: tests/test_inventory.py
import pytest

from bookstore.inventory import Inventory

@pytest.fixture
def inventory():
    return Inventory({"A": 5})

@pytest.fixture
def held_inventory():
    inventory = Inventory({"A": 5})
    inventory.reserve("A", 3)
    return inventory

def test_inventory_on_hand_stocked_isbn_returns_count(inventory):
    result = inventory.on_hand("A")

    assert result == 5

def test_inventory_on_hand_unknown_isbn_returns_zero(inventory):
    result = inventory.on_hand("B")

    assert result == 0

def test_inventory_reserved_nothing_held_returns_zero(inventory):
    result = inventory.reserved("A")

    assert result == 0

def test_inventory_available_nothing_held_returns_on_hand(inventory):
    result = inventory.available("A")

    assert result == 5

def test_inventory_no_stock_on_hand_returns_zero():
    inventory = Inventory()

    result = inventory.on_hand("A")

    assert result == 0

def test_inventory_caller_edits_stock_dict_keeps_own_copy():
    stock = {"A": 5}
    inventory = Inventory(stock)
    stock["A"] = 1

    result = inventory.on_hand("A")

    assert result == 5

def test_inventory_reserve_some_copies_returns_available(inventory):
    result = inventory.reserve("A", 2)

    assert result == 3
    assert inventory.reserved("A") == 2
    assert inventory.on_hand("A") == 5

def test_inventory_reserve_again_adds_to_held(inventory):
    inventory.reserve("A", 2)

    result = inventory.reserve("A", 1)

    assert result == 2
    assert inventory.reserved("A") == 3

def test_inventory_reserve_all_available_returns_zero(inventory):
    result = inventory.reserve("A", 5)

    assert result == 0

@pytest.mark.parametrize(
    ("already_reserved", "quantity", "message"),
    [
        (0, 6, "only 5 copies of A available"),
        (2, 4, "only 3 copies of A available"),
    ],
)
def test_inventory_reserve_more_than_available_raises_value_error(
    inventory, already_reserved, quantity, message
):
    if already_reserved:
        inventory.reserve("A", already_reserved)

    with pytest.raises(ValueError, match=f"^{message}$"):
        inventory.reserve("A", quantity)

def test_inventory_reserve_zero_quantity_raises_value_error(inventory):
    with pytest.raises(ValueError, match="^quantity must be positive$"):
        inventory.reserve("A", 0)

def test_inventory_reserve_unknown_isbn_raises_key_error(inventory):
    with pytest.raises(KeyError, match="^'unknown isbn: B'$"):
        inventory.reserve("B", 1)

def test_inventory_release_some_copies_returns_available(held_inventory):
    result = held_inventory.release("A", 1)

    assert result == 3
    assert held_inventory.reserved("A") == 2

def test_inventory_release_all_held_returns_on_hand(held_inventory):
    result = held_inventory.release("A", 3)

    assert result == 5
    assert held_inventory.reserved("A") == 0

def test_inventory_release_more_than_held_raises_value_error(
    held_inventory,
):
    with pytest.raises(
        ValueError, match="^cannot release 4, only 3 reserved$"
    ):
        held_inventory.release("A", 4)

def test_inventory_release_zero_quantity_raises_value_error(inventory):
    with pytest.raises(ValueError, match="^quantity must be positive$"):
        inventory.release("A", 0)

def test_inventory_release_unknown_isbn_raises_key_error(inventory):
    with pytest.raises(KeyError, match="^'unknown isbn: B'$"):
        inventory.release("B", 1)

def test_inventory_commit_some_held_returns_on_hand(held_inventory):
    result = held_inventory.commit("A", 2)

    assert result == 3
    assert held_inventory.reserved("A") == 1
    assert held_inventory.available("A") == 2

def test_inventory_commit_all_held_returns_on_hand(held_inventory):
    result = held_inventory.commit("A", 3)

    assert result == 2
    assert held_inventory.reserved("A") == 0

def test_inventory_commit_more_than_held_raises_value_error(held_inventory):
    with pytest.raises(ValueError, match="^cannot ship 4, only 3 reserved$"):
        held_inventory.commit("A", 4)

def test_inventory_commit_zero_quantity_raises_value_error(inventory):
    with pytest.raises(ValueError, match="^quantity must be positive$"):
        inventory.commit("A", 0)

def test_inventory_commit_unknown_isbn_raises_key_error(inventory):
    with pytest.raises(KeyError, match="^'unknown isbn: B'$"):
        inventory.commit("B", 1)

Once you’ve covered every module, go ahead and run both gates across the whole package:

Language: Shell
$ uv run pytest --cov=bookstore --cov-branch --cov-report=term-missing
$ uv run mutmut run
$ uv run mutmut results

The coverage report should show at least 95 percent for every module, and mutmut results should list no surviving mutants.

Troubleshooting

Even with a solid workflow, a pass can go wrong. Here are some common problems you might encounter and how to fix them:

  1. The agent starts creating poor-quality tests: The piece of code you gave it might be too big for one pass. Split the project by package or module, and work on one piece per session. Because BEHAVIOR.md and CLAUDE.md live in the repository, a fresh session picks up right where the last one left off.

  2. The agent edits the source instead of the tests: When a test fails, an agent you’ve told to make the tests pass often changes the module under test. Scope your prompts to the tests/ directory, and run git diff before accepting any change. If you want to fix a bug the tests found, then check out How to Debug Python Code With an AI Agent.

  3. Coverage is high, but mutants survive: Run uv run mutmut show <mutant-name> to see the change. If no test can tell a mutant from the original, then it’s equivalent. Otherwise, the survivor usually points to one of these gaps:

    • A missing row in BEHAVIOR.md: Have the agent propose the row marked NEEDS REVIEW, and review it before the agent writes tests.
    • A loose exception check: Anchor the match pattern.
    • A needless mock: Replace it with a fixture.

After each fix, rerun the tests, the coverage command, and mutmut for the current module before moving on.

Next Steps

You started with a package you couldn’t refactor safely, and you now have a suite that guards it. The reviewed BEHAVIOR.md keeps the tests accurate, the coverage gate keeps them complete, and mutmut confirms they’re robust enough to fail when the behavior changes.

Once the whole package passes both gates, you can keep it that way and reuse the workflow on other projects:

  1. Gate CI on coverage: Add --cov-fail-under=95 to the pytest command in your continuous integration pipeline so that the package’s overall coverage can’t quietly erode.
  2. Schedule mutmut: A mutation testing run for the whole package is slow, so run it nightly rather than on every commit.
  3. Package the rest of the workflow as skills: You already have a skill for Step 2. Turn the generation and mutation testing prompts from Steps 3 and 4 into skills too, so that you can run the whole process on any project with a few commands.

With this workflow, generating Python tests with AI becomes a process you can repeat and trust, whether you’re covering a small package or one module of a much larger project.

Frequently Asked Questions

Now that you have some experience generating Python tests with AI, you can use the questions and answers below to check your understanding and recap what you’ve learned.

These FAQs cover the most important concepts you’ve explored in this tutorial. Click the Show/Hide toggle beside each question to reveal the answer.

Give the agent standing testing conventions in CLAUDE.md, then have it extract a behavior table that you review before any tests exist. The agent generates the suite from that table to meet a coverage goal, and you confirm the result with a diff review and a mutation testing run.

A test that derives its expected value from the implementation inherits any bug in that implementation. Taking expected values from a reviewed BEHAVIOR.md file keeps the tests independent of the code, so they can catch incorrect behavior.

No. Coverage shows only which lines and branches ran during the tests, not whether any assertion would fail if the behavior changed. Mutation testing with a tool like mutmut fills that gap by checking whether the suite notices deliberate changes to the code.

A surviving mutant is a small change to your code that the test suite didn’t detect. It usually means the behavior table is missing a case or an existing test is too weak, often because of a loose match pattern or needless mocking. Occasionally, it’s an equivalent mutant that behaves exactly like the original code, which you can exclude with # pragma: no mutate.

Claude Code reads CLAUDE.md at the start of every session, so you don’t need to repeat the rules for them to apply consistently. That keeps your prompts short and focused on the details that change: the module and its reviewed behavior table. One-off jobs, like extracting a module’s behavior table, fit better in a skill, which the agent loads only when it’s invoked.

Take the Quiz: Test your knowledge with our interactive “Generating Python Tests With AI: A Suite You Can Trust” quiz. You’ll receive a score upon completion to help you track your learning progress:


Interactive Quiz

Generating Python Tests With AI: A Suite You Can Trust

Check how well you can generate Python tests with AI, from behavior tables and branch coverage to mutation testing with mutmut.

🐍 Python Tricks 💌

Get a short & sweet Python Trick delivered to your inbox every couple of days. No spam ever. Unsubscribe any time. Curated by the Real Python team.

Dictionary merging in Python 3.5+

About Leodanis Pozo Ramos

Leodanis is a self-taught Python developer, educator, and technical writer with over 10 years of experience.

» More about Leodanis

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Master Real-World Python Skills With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

Master Real-World Python Skills
With Unlimited Access to Real Python

Locked learning resources

Join us and get access to thousands of tutorials, hands-on video courses, and a community of expert Pythonistas:

Level Up Your Python Skills »

What Do You Think?

Rate this article:

What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment below and let us know.

Commenting Tips: The most useful comments are those written with the goal of learning from or helping out other students. Get tips for asking good questions and get answers to common questions in our support portal.


Looking for a real-time conversation? Visit the Real Python Community Chat or join the next “Office Hours” Live Q&A Session. Happy Pythoning!