Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
Five failures reached customers of a refund app. Each one goes to the lowest test layer that can see its cause: a limit off by one (unit), a missing error flag (functional), a hook on the wrong tool and an unknown tool reported as done (integration), and a launch from another folder (end-to-end). The regression run grows from 5 tests to 10.
What you will learn
- Name four test layers for a Claude app: unit, functional, integration and end-to-end
- Send each production failure to the lowest layer that can see its cause
- Write the missing test at that layer with pytest, a stand-in model and an MCP client
- Run the layers cheapest first in a regression run that stops at the first red layer
Before you start
- Integration layer or model output: isolating the problem
- Basic pytest
Our refund app has been live for a while, and five things have gone wrong for customers. Each one raises the same question: which test should have caught it, and at which layer?
The rule we'll use the whole way through: the lowest layer that can see the cause owns the failure. Write the missing test there, and it joins the regression run for good.
Four layers, one app
The app is a loop that talks to Claude, an orders server (an MCP server with a get_order tool) and a refund gate (a hook that denies refunds over $500).
Think of checking a car at four sizes. A single bolt on a bench is a unit test. The engine alone on a stand is a functional test. Engine and gearbox fitted and run together is an integration test. A test drive of the finished car is end-to-end. A fault belongs to the smallest check that can see it.
Five failures reached customers
- A refund of exactly $500 is stopped, though the limit allows it.
- An order that doesn't exist gets a reply that reads like a status.
- A $640 refund is sent, over the limit.
- The model asks for a tool we never defined, and the customer hears it's done.
- Started from another folder, the app calls real orders missing.
Every symptom shows at the top, in what the customer reads. The lecture's failures.py replays them against a stand-in model (scripted replies, no API key):
$ python failures.py
F1 issue_refund A-104 -> hook denies
F2 test model reply: order A-999 is no order A-999.
F3 issue_refund A-103 -> refund sent: $640
F4 test model reply: your order A-102 is cancelled.
F5 test model reply: I cannot find order A-101.
exit code 0
Unit: one function, one input, one answer
Failure 1 is decided by one function. The gate used amount < LIMIT where the rule needs <=. No model and no server are needed to see that.
"""Unit layer: one function, one input, one answer."""
import asyncio
from hooks import LIMIT, refund_gate
def gate(amount):
call = {"tool_input": {"amount": amount}}
return asyncio.run(refund_gate(call, "toolu_1", None))
def test_a_small_refund_is_allowed():
assert gate(120) == {}
def test_a_large_refund_is_denied():
out = gate(640)["hookSpecificOutput"]
assert out["permissionDecision"] == "deny"
def test_a_refund_of_exactly_the_limit_is_allowed():
assert gate(LIMIT) == {}
An empty result means allowed. The third test is the new one: test the boundary, exactly at the limit.
Functional: one part, through its own interface
Failure 2 needs the orders server, called the way the app calls it: through its MCP client. The error flag exists only at that interface, so a test on a bare Python function can't show it.
"""Functional layer: one part, through its own interface."""
import asyncio
from mcp import Client
from orders_server import mcp
def call(order_id):
async def go():
async with Client(mcp) as orders:
args = {"order_id": order_id}
return await orders.call_tool("get_order", args)
return asyncio.run(go())
def test_a_known_order_returns_its_status():
res = call("A-101")
assert not res.is_error
assert '"shipped"' in res.content[0].text
def test_an_unknown_order_is_an_error_result():
res = call("A-999")
assert res.is_error
assert "A-999" in res.content[0].text
Integration: our parts joined, a stand-in model
Failures 3 and 4 both live where parts meet. In failure 3 the hook watched the wrong tool name, so the gate never ran on the refund tool. In failure 4 the model's answer meets our code: it asked for cancel_order, which we never defined, and the loop must report that as an error, never as done.
"""Integration layer: our parts joined, a stand-in model."""
import asyncio
from mcp import Client
from app import answer
from orders_server import mcp
from stand_in import make_client
def run(question):
async def go():
async with Client(mcp) as orders:
model = make_client()
return await answer(question, model, orders)
return asyncio.run(go())
def test_a_small_refund_goes_through():
_reply, steps = run("Please refund order A-102.")
assert steps[-1].endswith("refund sent: $120")
def test_a_large_refund_stops_at_the_hook():
_reply, steps = run("Please refund order A-103.")
assert "issue_refund A-103 -> hook denies" in steps
def test_a_tool_we_do_not_have_is_an_error():
_reply, steps = run("Please cancel order A-102.")
assert "cancel_order A-102 -> unknown tool" in steps
Notice that failure 4 starts in model output, but the test still belongs to integration: what we can control is how our loop handles that reply. (For telling the two sides apart in the first place, see integration layer or model output.)
End-to-end: the whole app, as it is launched
Failure 5 only shows when the app is started from somewhere else, so only a test that launches it as a new process can see it.
"""End-to-end layer: the whole app, as it is launched."""
import pathlib
import subprocess
import sys
import tempfile
APP = pathlib.Path(__file__).resolve().parents[2] / "app.py"
def ask(question, folder):
cmd = [sys.executable, str(APP), question]
return subprocess.run(cmd, cwd=folder, capture_output=True,
text=True)
def test_it_answers_from_its_own_folder():
done = ask("Where is order A-101?", APP.parent)
assert "order A-101 is shipped" in done.stdout
def test_it_answers_from_any_folder():
with tempfile.TemporaryDirectory() as other:
done = ask("Where is order A-101?", other)
assert done.returncode == 0
assert "order A-101 is shipped" in done.stdout
A clean temporary folder with no orders file in it forces the app to find its own data.
regression.py: cheapest layer first
New tests don't need registering. The runner calls pytest once per layer folder, in order, and stops at the first red layer with exit code 1, the signal a pipeline reads.
LAYERS = ["unit", "functional", "integration", "e2e"]
def main(root=HERE, old=False):
skip = NEW_TESTS if old else []
total = 0
for layer in LAYERS:
ok, red = run_pytest(f"tests/{layer}", root, skip)
total += ok
note = f", {len(red)} failed" if red else ""
print(f"{layer:<13}{ok} passed{note}")
if red:
print("stopped at", red[0].split("::")[1])
return 1
print(f"regression run: {total} passed")
return 0
Before, with the old suite only (--old), after the five new tests, and with failure 3 switched back on:
$ python regression.py --old
unit 2 passed
functional 1 passed
integration 1 passed
e2e 1 passed
regression run: 5 passed
exit code 0
$ python regression.py
unit 3 passed
functional 2 passed
integration 3 passed
e2e 2 passed
regression run: 10 passed
exit code 0
$ python regression.py --with F3
unit 3 passed
functional 2 passed
integration 2 passed, 1 failed
stopped at test_a_large_refund_stops_at_the_hook
exit code 1
The triage script confirms the pattern for every failure: the old suite was green, the new test fails on the buggy code, and the fixed code passes all ten.
$ python triage.py
layer old suite new test fixed
F1 unit 5 ok FAIL 10 ok
F2 functional 5 ok FAIL 10 ok
F3 integration 5 ok FAIL 10 ok
F4 integration 5 ok FAIL 10 ok
F5 e2e 5 ok FAIL 10 ok
exit code 0
Common mistakes
- Reaching for an end-to-end test with a live model. It's slow, and red doesn't say where.
- Using a judge model for a rule a plain check decides. "Is $500 allowed?" needs an assert, not an LLM.
- Hoping a higher test happens to hit the case. An integration test only catches the off-by-one if it uses exactly $500.
- Testing an MCP tool as a bare function. The error flag lives at the interface; test through the client.
- Only running tests from the project folder. Path bugs show up when the app is launched from somewhere else.
Quick recap
| Layer | Checks | Owned failure here |
|---|---|---|
| Unit | One function, one input, one answer | Limit used < instead of <= |
| Functional | One part through its own interface | Unknown order not flagged as an error |
| Integration | Our parts joined, stand-in model | Hook on the wrong tool; unknown tool reported as done |
| End-to-end | The whole app, launched like a user would | Data not found from another folder |
Model-quality questions (is the answer good?) belong to evals; see why you can't ship without an eval. The layers above cover the code around the model.
Try it yourself
Take the last bug that reached your users. Name the lowest layer that could have seen its cause, write that one test, and add it to your regression run. Then switch the bug back on and check the run stops where you expect.
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
From ML Metrics to LLM Evals: Same Ruler, New Targets
Precision and recall don't disappear when you build with LLMs; they move. A spam filter at 0.75/0.75, precision@3 and recall@3 on six help-desk documents, exact match vs a key-fact check on two written answers, and the rubric that replaces a single label.
Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
A friendlier prompt looked better on three questions and broke on others. An eval catches that: a fixed set of cases, a grader, a pass rate and a threshold. A tiny Python eval scores two prompt versions on the same six questions: v1 passes 83% and ships, v2 passes 50% and is blocked.
Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
The answer key for a support bot: 24 cases in one JSONL file, from 12 past tickets, 8 edge cases and 4 attacks. A Pydantic schema catches 4 problems in a broken file, a stats table finds that payments and account have no hard case, and a seeded split gives the same 16 dev and 8 test cases every time.
Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
When a RAG answer is wrong, check the retriever first. Score two retrievers on 24 graded queries with Recall@5, MRR and nDCG@5: overall there's no clear winner (0.757 vs 0.819, 0.854 vs 0.826, 0.769 vs 0.782), but the paraphrase slice drops to about 0.5 for both, and one query scores zero everywhere.