Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Evals and Testing

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.

Chaand Sheikh

·27 November 2026Evals and Testing

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).

Four test layers for one app End-to-end: the whole app, launched as a process Integration: our parts joined, a stand-in model Functional: one part, its own interface Unit refund_gate(amount) orders server via MCP client stand-in model
Unit checks one function, functional checks one part, integration checks the joins, end-to-end checks the launch. These four names are working terms for this app.

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

  1. A refund of exactly $500 is stopped, though the limit allows it.
  2. An order that doesn't exist gets a reply that reads like a status.
  3. A $640 refund is sent, over the limit.
  4. The model asks for a tool we never defined, and the customer hears it's done.
  5. 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

LayerChecksOwned failure here
UnitOne function, one input, one answerLimit used < instead of <=
FunctionalOne part through its own interfaceUnknown order not flagged as an error
IntegrationOur parts joined, stand-in modelHook on the wrong tool; unknown tool reported as done
End-to-endThe whole app, launched like a user wouldData 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.

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in AI Engineering · 59 of 89

Previous
RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
Next post
Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency

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.

On this page

  • Four layers, one app
  • Five failures reached customers
  • Unit: one function, one input, one answer
  • Functional: one part, through its own interface
  • Integration: our parts joined, a stand-in model
  • End-to-end: the whole app, as it is launched
  • regression.py: cheapest layer first
  • Common mistakes
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.