Product case study · November 27, 2026

Ask Claude Code why your Python mock never gets called

Reproduce a Python mock that misses its target, ask Claude Code for a test-only repair, and verify the call, result and cleanup with unittest.

Reading time
6 min
Checked
Nov 27, 2026
A charcoal cable connects to a blue socket on a paper card beside an unused ochre socket, illustrating a corrected mock target.
A replacement only helps if the code looks up the name you replaced.
Bottom line

Before rewriting working application code, check whether the test replaces the name the application actually reads.

Your test replaces a function, but the application keeps calling the original. The mock records zero calls. Asking an agent to rewrite the application can make this failure disappear while leaving the real mistake in the test unexplained.

In this exercise, Claude Code gets a smaller job: trace an imported name and repair its patch target. The application is intentionally correct. You will check both the result and which function received the call.

You need Python 3, Bash on Linux, macOS or WSL, and an installed, signed-in Claude Code. No Python packages or network services are needed for the fixture. The Python reproduction and reference repair were run locally; the Claude prompt below is an authored exercise, not a recorded agent session. Official documentation was checked November 27, 2026.

Create a harmless failure

Start in a new practice folder:

mock_lab=$(mktemp -d /tmp/claude-mock.XXXXXX)
cd "$mock_lab"

Save this as catalog.py:

def lookup_label(item_id):
    return f"Catalog item {item_id}"

Save this as receipt.py:

from catalog import lookup_label


def receipt_line(item_id):
    return f"Item: {lookup_label(item_id)}"

The contract is to prefix the catalog label with Item: . The catalog function is local and deterministic; even when the mock misses, it cannot send a request or alter a real catalog.

Save this deliberately broken test as test_receipt.py:

import unittest
from unittest.mock import patch
import receipt


class ReceiptTests(unittest.TestCase):
    def test_uses_catalog_label(self):
        with patch("catalog.lookup_label", return_value="Desk lamp") as lookup:
            result = receipt.receipt_line("A7")
            lookup.assert_called_once_with("A7")
            self.assertEqual(result, "Item: Desk lamp")

Run it:

python3 -m unittest -v test_receipt

The local baseline failed with a call-count assertion: the mock was called zero times, rather than once. The real function still returned its normal label.

Trace the name before editing

receipt.py imports lookup_label into its own module namespace. Replacing catalog.lookup_label later does not replace the name already held by receipt.

Python’s where-to-patch documentation explains that the replacement belongs where the object is looked up. Here, receipt_line reads receipt.lookup_label, so that is the target to patch.

Import style matters. If the application instead used import catalog and called catalog.lookup_label(...), it would look up the attribute on that module. Do not mechanically change every patch to the caller’s module name without reading the actual call.

Give Claude Code a test-only task

Start claude from the practice folder. Send this prompt:

Read catalog.py, receipt.py and test_receipt.py. Run:
python3 -m unittest -v test_receipt

Explain why the mock has zero calls. Trace the name receipt_line
looks up, including the effect of the from-import.

Change only test_receipt.py. Preserve both application files,
the expected string and assert_called_once_with("A7").
Repair the patch target; do not mock receipt_line itself.
Add coverage for a second item ID and verify that the original
lookup is restored after the patch context ends.
Run the complete test module and report the actual command,
exit status and test count. Do not claim a pass without running it.

Anthropic’s common workflows documents starting Claude in a project directory and giving it focused debugging and testing tasks. This prompt adds the exercise’s acceptance conditions: the application must stay fixed, and a green result must include evidence that the mock was used.

If the agent cannot run Python in your environment, run the command yourself. Keep that distinction in the handoff; a proposed patch is not a test result.

Compare with the reference repair

The essential change is catalog.lookup_label to receipt.lookup_label. This complete reference test file also checks another input and restoration:

import unittest
from unittest.mock import patch
import receipt


class ReceiptTests(unittest.TestCase):
    def test_uses_catalog_label(self):
        with patch("receipt.lookup_label", return_value="Desk lamp") as lookup:
            result = receipt.receipt_line("A7")
            lookup.assert_called_once_with("A7")
            self.assertEqual(result, "Item: Desk lamp")

    def test_forwards_another_id(self):
        with patch("receipt.lookup_label", return_value="Notebook") as lookup:
            result = receipt.receipt_line("B2")
            lookup.assert_called_once_with("B2")
            self.assertEqual(result, "Item: Notebook")

    def test_restores_original_lookup(self):
        original = receipt.lookup_label
        with patch("receipt.lookup_label", return_value="Temporary"):
            self.assertEqual(receipt.receipt_line("A7"), "Item: Temporary")
        self.assertIs(receipt.lookup_label, original)
        self.assertEqual(receipt.receipt_line("A7"), "Item: Catalog item A7")

Run the same command again:

python3 -m unittest -v test_receipt

The reference repair passed three tests locally. Python’s unittest documentation describes running a named test module and using -v for individual test names. Check that all three names appear; an empty discovery run would not prove this repair.

The result assertion checks formatting. The call assertion catches a hardcoded answer or the wrong item ID. The restoration test checks that the temporary replacement ends with its context. These checks cover this small fixture, not a real catalog integration.

Reject a green run that changes the wrong thing

Review the changed files before accepting the agent’s work. catalog.py and receipt.py should still match the snippets above. Only the test target and added coverage should differ.

What you observeWhat to check next
The mock still records zero callsRead the import and the exact name used inside receipt_line.
ModuleNotFoundErrorRun from the practice folder and check the three filenames.
The result passes but the call assertion vanishedRestore the assertion; matching text alone does not prove delegation.
Claude changed the application importsAsk for the test-only repair with both application files restored to the fixture.
A real service gets contacted in your own projectStop that run and isolate the dependency before continuing; this local fixture has no external calls.

Avoid adding create=True to silence a missing-target error. That can let a patch create an attribute your application never reads. Find the actual lookup instead.

For a related testing problem, try the environment-leak exercise. That failure depends on what a previous test leaves behind; this one depends on the name the application reads during the call.

Sources and verification

Checked November 27, 2026:

Verification covers the supplied Python fixture: one failing baseline test, three passing reference tests, and unchanged application files. It does not measure Claude Code’s success rate or claim that an agent executed this prompt.

Put this to work

Why a from-import changes where unittest.mock.patch must point.

Try

Repair one patch target in a disposable Python practice folder.

Prove it worked

Run three tests and confirm the application files remain unchanged.

Keep in view

  • Reproduce a mock that leaves the original function running.
  • Ask Claude Code to trace imports before changing the test.
  • Check the return value, call arguments and restoration after patching.
Learn the workflow: Set up a Claude Code project session