AUTOMATION FRAMEWORKS

Mocking External APIs in Pytest Without Overcommitting, With AI

Mocking external APIs in pytest feels like pure upside until the day it isn't. You swap a slow, flaky third-party call for a fast fake, the suite goes green, and everyone's happy right up until the real integration breaks in production and no test saw it coming. The mock was too broad, too optimistic, or committed to a response shape the real API stopped honouring a while ago.

"Overcommitting" is the word I keep coming back to. A mock that returns a perfect 200 with every optional field filled in is making a claim about someone else's API that you probably can't back up. Coding agents make this easier to get wrong. Ask Copilot or an agent to "fix the failing test" and patching the call that fails is often the shortest path to green. The agent isn't wrong that the test now passes. It's just that the test no longer tests anything.

In this article I'll go through the patterns I use to keep pytest mocks honest: scope them to the narrowest boundary, make them expose assumptions instead of hiding them, anchor them to a contract so they don't drift, and set rules so agents mock the way you would.

Build an API Automation Framework in Python

Learn Python, Behave, GitHub Copilot, APIs, and CI/CD by building a real framework you can finish in a weekend.

Learn more

Mock the boundary, not the whole client

The most common overcommitment is patching too much. Patch requests.Session wholesale and every HTTP call in that test is swallowed, including ones you never meant to fake. I mock as close to the external call as I can, and I like tools that fail loudly on anything I didn't mention. The responses library does that: only registered URLs are answered, and any other request made through requests raises a connection error.

import responses

from myapp.clients.user_client import UserClient


@responses.activate
def test_fetch_user_returns_display_name():
    responses.add(
        responses.GET,
        "https://api.example.com/users/u_123",
        json={"id": "u_123", "display_name": "Ada"},
        status=200,
    )

    client = UserClient(base_url="https://api.example.com")
    result = client.fetch_user("u_123")

    assert result["display_name"] == "Ada"
    assert len(responses.calls) == 1

Two things to notice. The fake body has only the fields this test uses. Every extra field you fill in is a silent claim that it exists and has that value. And the test checks the call happened exactly once, so it verifies what your code sends as well as what it does with the reply.

If you mock at the Python level instead, with pytest-mock, use autospec=True so the mock keeps the real signature. A call with the wrong arguments then fails, instead of being accepted by a mock that will accept anything.

Make mocks expose assumptions

A mock that always succeeds teaches you nothing about error handling. I treat every mock as a hypothesis ("the API returns this shape under these conditions") and write at least one test that challenges it:

import pytest
import responses

from myapp.clients.order_client import ExternalAPIError, OrderClient

URL = "https://api.orders.example.com/orders/ord_99"


@responses.activate
def test_get_order_raises_clear_error_on_503():
    responses.add(responses.GET, URL, status=503, json={"error": "unavailable"})
    client = OrderClient(base_url="https://api.orders.example.com")
    with pytest.raises(ExternalAPIError, match="503"):
        client.get_order("ord_99")


@responses.activate
def test_get_order_handles_missing_optional_fields():
    responses.add(responses.GET, URL, status=200, json={"order_id": "ord_99"})
    client = OrderClient(base_url="https://api.orders.example.com")
    order = client.get_order("ord_99")
    assert order["status"] is None

The 503 test is the one most teams skip, and it's the one that matches a real bad day. The sparse-body test asks what your client does when an optional field is absent. If it crashes, you've found a defensive-coding bug before production did. The same thinking applies to responses that change with state, like the last page of a paginated list with no next cursor.

Keep mocks from drifting

The long-term problem isn't writing the first mock. It's keeping it honest after the vendor changes a field. I keep canned responses in tests/fixtures/ as JSON, loaded by one fixture in conftest.py, so there's a single place to update. Where the vendor publishes a JSON Schema or an OpenAPI document, I validate the fixture against it:

import json
from pathlib import Path

from jsonschema import validate

FIXTURES = Path(__file__).parent / "fixtures"


def test_user_fixture_still_matches_vendor_schema():
    fixture = json.loads((FIXTURES / "user_response.json").read_text())
    schema = json.loads((FIXTURES / "user_schema.json").read_text())
    validate(instance=fixture, schema=schema)

This test calls nothing. It checks that your fake is still plausible according to the vendor's own contract. Pull the latest schema and this fails before any test runs against a stale fixture. Pair it with a small scheduled job that calls the real API and compares the live shape to the fixture, which is the idea behind contract testing for breaking changes.

Keep mocks visible at the fixture level too. When patches are scattered across dozens of tests with slightly different settings, nobody can say what the canonical fake for that API looks like.

When an agent reaches for a mock

Agents mock for the same reason people do: it's the quickest way past a failure. The patterns I watch for in agent-written changes:

  • Mocking the code under test. A test for OrderService that patches OrderService.calculate_total proves only that the mock returns what it was told.
  • A new mock in a test that used to hit a real service. Sometimes right, often a failure being hidden. Ask what was failing first.
  • Bodies copied from the current response. A mock built by pasting today's output freezes today's behaviour, bugs included, as the expected result.
  • Broad patches. Patching requests.get globally rather than registering one URL.

I write the rules where the agent reads them (.github/copilot-instructions.md for Copilot, or your agent's own instruction file) and check them in review:

## Mocking
- Mock only third-party HTTP calls, using responses with explicit URLs. Never mock our own modules under test.
- Canned bodies live in tests/fixtures/ and must validate against the vendor schema there.
- Do not add a mock to make a failing test pass. Report the failure and why it fails.
- Every new mocked happy path needs a matching error-path test (4xx/5xx or missing field).

The same rules for model calls

If your code calls an LLM, the model provider is just another external API, and the same discipline applies. Inject a generate(prompt) -> str function and pass a fake in unit tests so prompt building, parsing and guardrails run fast and deterministically. Don't overcommit there either: a fake that always returns clean, well-formed JSON never tests your parser's handling of the truncated, chatty or malformed output real models sometimes produce. Give the fake a few bad outputs on purpose. Then test real model behaviour separately, on a schedule, with a fixed set of cases and a pass rate rather than a single pass or fail.

Honest mocks

Mocking well comes down to honesty: honest scope, honest response shapes and honest upkeep. The mock that saves you time today is only worth it if it doesn't lie to you later. For the bigger decision of when to fake a dependency at all, see choosing between mocking and a real test environment. If you'd like to practise these patterns on a full project with GitHub Copilot alongside, my API testing courses cover them in Python and Node.