Sub topic 13
Building the Workflow into Review and CI
What this chapter assumes
This chapter assumes you can run pytest, read a pull request diff, and edit a CI configuration file. It also assumes you have already generated tests and docstrings for a function like apply_discount, and that you have reviewed them by hand. Here you turn that manual review into steps that run every time, so the checks do not depend on anyone remembering them.
Why a habit is not enough
Earlier chapters treated generated output as a draft that you verify. That works when one careful person does it once. It fails when a team is busy, when a reviewer sees 200 lines of plausible-looking tests, or when a docstring is correct today and wrong after the next refactor.
A workflow fixes this by splitting the checks into two kinds:
- Mechanical checks that a machine can decide: do the tests pass, do the doctest examples run, is coverage above a floor.
- Judgment checks that need a person: do the tests assert the right behavior, does the README describe what the project is for.
CI should handle the first kind completely. Review should spend its attention on the second kind.
The pipeline at a glance
The diagram has two loops back to the review step. A failing check sends the author back to fix the draft. It never sends the author forward to loosen the check.
Step 1: Run the same checks locally
Developers should be able to run exactly what CI runs. Otherwise the first sign of a problem is a red build several minutes after the push. A short script is enough:
#!/usr/bin/env bash
set -euo pipefail
python -m pytest --cov=pricing --cov-report=term-missing --cov-fail-under=90
python -m doctest -v pricing.pyset -e stops at the first failing command, and -u and pipefail catch unset variables and failures inside pipes. Commit this as scripts/check.sh and make CI call the same commands. If the two drift apart, "passes on my machine" returns.
Step 2: Add a mutation check by hand
Passing tests do not prove the tests are good. A quick way to test the tests is to break the code on purpose and see whether they notice. This is a small, manual form of mutation testing.
Take apply_discount and change one boundary:
# Original
if not 0 <= percent <= 100:
# Mutant: 0 is now rejected
if not 0 < percent <= 100:The parametrized test from the earlier chapter includes (19.99, 0, 19.99). With the mutant, that call raises ValueError, so the test fails. That is the result you want. Now change <= 100 to < 100. The case (50, 100, 0.0) should fail the same way.
If a mutant survives, meaning every test still passes, the tests have a gap. Add a case that kills the mutant, then restore the original code. For larger codebases a tool such as mutmut automates this, but it is slow. Run it on the files that changed in a pull request, not on the whole project on every push.
Step 3: Gate the pull request in CI
The following GitHub Actions workflow runs the tests with a coverage floor, then runs the doctest examples in the docstrings. It assumes pricing.py sits at the repository root and the tests are in tests/.
name: checks
on:
pull_request:
push:
branches: [main]
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install test dependencies
run: python -m pip install pytest pytest-cov
- name: Run tests with coverage floor
run: python -m pytest --cov=pricing --cov-report=term-missing --cov-fail-under=90
- name: Run docstring examples
run: python -m doctest -v pricing.pyThree details matter here:
permissions: contents: readgives the job the least access it needs. A test job should not be able to push or edit releases.python -m pytestadds the current directory to the import path, sofrom pricing import apply_discountworks without installing the package.python -m doctestexits with a non-zero status when an example's output differs from the docstring. That turns a staleExamplessection into a failed build.
Choosing a coverage floor
Coverage measures which lines ran, not whether anything was checked. A generated test that calls a function and asserts nothing still counts. Use the floor as a tripwire against deleted tests, not as a quality score.
| Setting | Effect | Risk |
|---|---|---|
| No floor | Nothing stops tests from being removed | Silent decay |
| Floor near current level (for example 90) | Catches deletions and untested new code | Encourages padding tests to hit the number |
| 100 percent | Forces every line to be touched | Produces assertion-free tests to satisfy the rule |
Pick a floor slightly below your current coverage. Raise it deliberately, not as a side effect of a generation session.
Step 4: Give reviewers a checklist
Reviewers need to know what to look at, since CI already covers the mechanical parts. Put a checklist in the pull request template so it appears on every PR:
## Generated content
- [ ] I read every generated test and can explain what each assertion checks.
- [ ] Expected values come from the documented contract, not copied from the code's output.
- [ ] At least one deliberate code change (mutant) made a test fail.
- [ ] Docstring and README claims were checked against the code or run as doctests.
- [ ] No secrets, customer data, or private URLs were pasted into prompts or committed in examples.
- [ ] The prompt or a summary of it is in the PR description.The last item is useful. When a reviewer sees what constraints the assistant was given, they can judge whether a missing case is a prompt problem or a review problem. It also helps whoever regenerates the tests later.
Step 5: Keep documentation from drifting
Docs break after the change that made them true. Three practices slow that down:
- Run examples, not just read them. Doctest covers function docstrings. For README snippets, extract them into a test file or run them with
python -m doctest README.mdwhen the snippets use>>>prompts. - Trigger doc checks when code changes. If your CI is path-aware, run the doc job whenever
*.pyfiles change, not only when*.mdfiles change. A signature change breaks docs without touching them. - Regenerate with the diff, not from scratch. When a function changes, give the assistant the old docstring, the diff, and the new code. Ask it to update only what the diff affects. This keeps wording stable and makes the review diff small.
Privacy and access in the pipeline
The CI file above never calls an assistant, and that is deliberate. Keep generation on the developer's side and keep verification in CI. If you do add automated generation, such as a bot that proposes docstrings on every push, follow these rules:
- Store API keys in the CI secret store, never in the repository or in logs.
- Send only the files needed for the task. Do not send the whole repository or configuration files that contain credentials.
- Have the bot open a pull request. It must not commit to the main branch, so the same review and CI gates apply to its output as to anyone else's.
- Check your organization's policy on sending source code to an external service before turning this on.
Common failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| CI is green but a bug shipped | Tests assert what the code does, not what it should do | Derive expected values from the contract. Run the mutant check |
| Coverage rises but quality does not | Tests call code without assertions | Review for missing `assert` or `pytest.raises`. Do not chase the number |
| Doctest fails after a refactor | Output format changed, such as `90.0` becoming `90` | Update the example only after confirming the new output is intended |
| Flaky tests after generation | Mock leaks state, or a test relies on real time or network | Isolate with fresh mocks per test. Remove real I/O |
| Reviewers approve without reading | Large generated diffs, no checklist | Split PRs. Require the checklist and a prompt summary |
| Docs stale within weeks | Doc job only runs on Markdown changes | Run doc checks on any source change |
Putting it together
A workable routine for a new function looks like this:
- Prompt the assistant with the code, conventions, and constraints, and ask for tests and a docstring with examples.
- Read the output and run
scripts/check.shlocally. - Introduce one or two mutants. Confirm that tests fail, then revert.
- Open a pull request with the checklist completed and the prompt summarized.
- Let CI run tests, the coverage floor, and doctests.
- A reviewer checks the assertions and the docs against the intended behavior, then approves.
The assistant accelerates steps 1 and 2. Steps 3 through 6 are what make the output trustworthy.
Exercise
Your CI shows 95 percent coverage and all tests pass on a pull request with generated tests for a new function. What two further checks would you perform before approving, and why is coverage alone not enough?
Show answer
First, a mutation check: change a boundary or return value in the function and confirm that at least one test fails. If none fails, the tests do not verify behavior. Second, a review of the assertions: confirm that expected values come from the documented contract and not from running the code, and that each error path uses pytest.raises. Coverage only records which lines executed. A test that calls the function and asserts nothing, or asserts the code's own output, raises coverage without checking anything.
Exercise
A teammate changes apply_discount so that invalid input raises TypeError instead of ValueError. The docstring still says ValueError, and the Examples section only shows two successful calls. Will python -m doctest catch the stale docstring? What would you add so that CI does catch it?
Show answer
No. Doctest only compares the output of the examples that exist, and both successful calls still produce the same output. To catch the change, add an example that shows the exception, such as >>> apply_discount(-1, 10) followed by Traceback (most recent call last):, ..., and ValueError: price must be non-negative. Doctest would then fail once the code raises TypeError. The existing pytest.raises(ValueError) tests would also fail, which is a second signal.