Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Worked example · 20 min · revision 3

Refactors, Docs and Code Review with an Assistant, Verified

Worked example: review an assistant-driven refactor and its documentation the way you would a colleague's pull request — baseline tests first, catch a weakened assertion, verify docstring claims and unfamiliar calls against reality.

Contentsand lesson path

What you will learn

  • Review AI-generated changes, refactors and documentation as you would a colleague's pull request: run the tests, check every new dependency and API call against official documentation, and reject changes that pass only by weakening or deleting tests.

Prerequisites: Software Testing Fundamentals

01. The task

You ask an assistant for a small refactor: reading.py counts unread entries with one function, and a teammate wants to count any status. The assistant returns a diff, a docstring and a suggestion to install a helper package. Nothing here is hostile — but as the mechanism lesson predicted, a fluent diff can still weaken your tests, document behaviour the code does not have, and reach for a package that does not exist. Your job is the same one you would do for a junior colleague's pull request: verify, then trust.

The module under review is small enough to hold in your head:

Python · reading.py (before)
def unread_count(entries: list[dict[str, str]]) -> int:
    """Count the entries that have not been read yet."""
    return sum(1 for entry in entries if entry["status"] == "unread")
Python · test_reading.py (before)
from reading import unread_count


def test_unread_count_ignores_finished_entries() -> None:
    entries = [
        {"title": "Refactoring HTTP clients", "status": "unread"},
        {"title": "Async Python patterns", "status": "unread"},
        {"title": "Postgres indexes deep dive", "status": "done"},
    ]

    assert unread_count(entries) == 2

02. Step 1: run the suite before you touch anything

Before applying any generated change, establish the baseline. If the suite is already red on the unmodified code, you cannot tell your change's failures from yesterday's, and a later "all green" will mean nothing:

Terminal
.venv/bin/python -m pytest -q
Illustrative output (the run time varies)
.                                                                        [100%]
1 passed in 0.01s

03. Step 2: read the diff, and catch the weakened test

The assistant proposes refactor.diff. Most of it is what you asked for — a general count_by_status, with unread_count kept as a one-line wrapper — plus new documentation. Read every hunk, including the ones you did not ask for. Here is the whole diff; save it as refactor.diff next to the two files to follow along:

Text · refactor.diff
diff --git a/reading.py b/reading.py
--- a/reading.py
+++ b/reading.py
@@ -1,3 +1,11 @@
+def count_by_status(entries: list[dict[str, str]], status: str) -> int:
+    """Count the entries whose status equals `status`.
+
+    Raises ValueError if `status` is not "unread" or "done".
+    """
+    return sum(1 for entry in entries if entry["status"] == status)
+
+
 def unread_count(entries: list[dict[str, str]]) -> int:
     """Count the entries that have not been read yet."""
-    return sum(1 for entry in entries if entry["status"] == "unread")
+    return count_by_status(entries, "unread")
diff --git a/test_reading.py b/test_reading.py
--- a/test_reading.py
+++ b/test_reading.py
@@ -8,4 +8,4 @@ def test_unread_count_ignores_finished_entries() -> None:
         {"title": "Postgres indexes deep dive", "status": "done"},
     ]
 
-    assert unread_count(entries) == 2
+    assert unread_count(entries) >= 1

The last hunk is the one that matters. The test was not part of the request, and the edit makes it weaker: >= 1 passes for one unread entry, or five, or a count function that has drifted completely. This is the social failure from the mechanism lesson — asked for a green suite, prediction found a cheaper path to green than correct code. You reject that hunk and say so plainly: the tests are the acceptance bar and are not part of the change. A second pair of eyes helps here, and the eyes can themselves be scripted. A reviewer pass over the same diff, using static checks a real reviewing assistant should also make, surfaces all three problems at once. This one is a short script that reads the diff:

Python · mock_reviewer.py
"""A scripted reviewer: three static checks a reviewing assistant should make."""
import re
import sys
from collections import defaultdict

added, removed = defaultdict(list), defaultdict(list)
path = ''
for line in open(sys.argv[1]).read().splitlines():
    if line.startswith('+++ b/'):
        path = line[6:]
    elif line.startswith('+') and not line.startswith('+++'):
        added[path].append(line[1:])
    elif line.startswith('-') and not line.startswith('---'):
        removed[path].append(line[1:])

for path in dict.fromkeys([*added, *removed]):
    claims = [x for x in added[path] if re.search(r'\bRaises \w+Error', x)]
    if claims and not any('pytest.raises' in x for f in added for x in added[f]):
        print(f'reviewer: {path}: exception claim needs a provoking test')
    if path.split('/')[-1].startswith('test_'):
        print(f'reviewer: {path}: diff touches the test suite')
        old = [x for x in removed[path] if 'assert' in x and '==' in x]
        new = [x for x in added[path] if 'assert' in x and '>=' in x]
        if old and new:
            print(f'reviewer: {path}: weakened assertion (== -> >=)')
Terminal
.venv/bin/python mock_reviewer.py refactor.diff
Expected output
reviewer: reading.py: exception claim needs a provoking test
reviewer: test_reading.py: diff touches the test suite
reviewer: test_reading.py: weakened assertion (== -> >=)

Whether the reviewer is a script like this one or a live assistant, keep the standard the same: findings are claims until you have checked them in the diff. Now accept only the source change — git apply with an include pattern skips the test hunk:

Terminal
git apply --include=reading.py refactor.diff
.venv/bin/python -m pytest -q
Illustrative output (the run time varies)
.                                                                        [100%]
1 passed in 0.01s

The original assertion is intact, byte for byte, and the refactor passes it. That is the shape of a healthy acceptance: the code moved, the bar did not.

04. Step 3: verify the documentation like code

The reviewer's first finding is subtler: the new docstring for count_by_status claims it raises ValueError for a status that is not one of unread or done. Documentation written with the code tends to describe the intention, not the behaviour. Settle it by running the claim, the same way you would run a test:

Terminal
.venv/bin/python -c "
from reading import count_by_status
entries = [{'title': 'Indexes', 'status': 'done'}]
print('known status   ->', count_by_status(entries, 'done'))
print('unknown status ->', count_by_status(entries, 'skimming'))
"
Expected output
known status   -> 1
unknown status -> 0

No exception: an unknown status simply counts nothing. The docstring is wrong, so fix the docstring — do not "fix" the code to match an unchecked sentence. The corrected line reads An unknown status simply counts nothing and returns 0., and the suite still passes. The same discipline applies to the assistant's prose summary: treat every claim about behaviour as a test waiting to be written, and any claim you cannot test as a comment to delete.

05. Step 4: verify unfamiliar calls and packages

Two more checks finish the review. First, any call you do not recognise gets checked against the installed library, not against your memory of it — and especially not against the assistant's own docstring. In a companion change the assistant suggested guarding a regex with a timeout parameter on re.compile, which sounds reasonable and does not exist. A three-line script asks the installed library:

Python · check_api.py
import inspect
import re

print('re.compile accepts:', list(inspect.signature(re.compile).parameters))
try:
    re.compile(r'\d+', timeout=1)  # the call the assistant suggested
except TypeError as exc:
    print(f'TypeError: {exc}')
Terminal
.venv/bin/python check_api.py
Expected output
re.compile accepts: ['pattern', 'flags']
TypeError: compile() got an unexpected keyword argument 'timeout'

The signature is pattern, flags; the call fails. Note that a test mocking the regex module would have passed, so this check needs the real library. Second, the assistant's summary recommended installing py-titlecase-pro for tidying titles. Check the package registry before installing anything — a clean install proves nothing, because attackers register invented-sounding names precisely so that they do install, then run code at install time. This trick is known as slopsquatting:

Terminal
curl -s -o /dev/null -w "%{http_code}\n" https://pypi.org/pypi/py-titlecase-pro/json
curl -s -o /dev/null -w "%{http_code}\n" https://pypi.org/pypi/titlecase/json
Expected output
404
200

The suggested package has no project page at all — it existed only in the model's pattern-matching — while the real one resolves. A 200 alone is still not a recommendation: for a dependency you keep, read the project's own page, check it is maintained, and prefer names you can trace to an official source. The review ends where it began, with the suite green on the accepted part, the test file untouched, the docstring true, and two fluent suggestions rejected because reality said no.

06. Check your understanding

Practice check · 3 questions

Reviewing like a colleague

Apply the review sequence to three new situations.

Q1. An assistant's refactor arrives. What do you do first?
Q2. The docstring says a helper "raises ValueError for unknown status". What settles whether that is true?
Q3. Your project installs only from PyPI. The PyPI JSON API answers 404 for py-titlecase-pro, the package the summary recommended. What is the right conclusion?
Practice only: not graded, not saved, not evidence.

07. Apply it

Run this review loop on your own service, as the skill practice asks:

  1. Take the next change an assistant gives you and write down, before running anything, what the baseline must be. Then run it and check your prediction.
  2. Diff the whole change including tests. Reject anything that edits an existing assertion, and keep the rejection note for your session log.
  3. Pick the one call and the one package in the change you are least sure about, and verify each against the official documentation and the package registry.
  4. Turn one docstring claim into a test. If the test fails, you have found your next fix — in the docs.

08. Review prompt

Without looking back: state the review steps of this lesson in order and what each one protects against. Explain why a green suite after a diff is not proof the code is correct, and why running the real library beat both the mocked test and a direct question to the assistant. Finish by describing slopsquatting in one sentence and naming the check that exposes it.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check