Unit, integration and regression testing

Topic 4 of 4 in Observability & evaluation22 min readAdvancedFree course

Overview

A LangGraph application can compile successfully, execute without exceptions, and still behave incorrectly.

A customer support agent might retrieve the wrong customer’s order. A research agent might repeatedly invoke an expensive search tool. A financial workflow might bypass an approval node. A multi-agent application might produce a convincing answer while delegating work to the wrong specialist.

These are behavioral failures that ordinary exception monitoring cannot reliably detect.

In the previous lesson, Evaluating agents — datasets, LLM-as-a-judge and trajectories, you learned how to measure agent quality using representative examples and evaluators. This lesson converts those measurements into an automated engineering process that protects your application against defects introduced by future changes.

Testing agentic systems requires distinguishing two categories of behavior:

  • Deterministic behavior: Python functions, reducers, validation rules, permissions, conditional edges, and database operations under controlled conditions.
  • Probabilistic behavior: Model-generated responses, tool selection, reasoning strategies, and task decomposition.

Deterministic behavior should normally satisfy exact assertions. Probabilistic behavior requires semantic checks, measurable acceptance criteria, and sometimes repeated execution.

An effective test suite examines both what an agent produces and how it produces it.

For example, a correct order status is insufficient if the agent obtained it by accessing another customer’s records. The execution path is part of the application contract.

Throughout this lesson, you will use pytest, fake chat models, in-memory persistence, and LangSmith to construct that contract.

Development environment

Install the dependencies into an isolated Python environment.

Terminal
pip install "langgraph>=1,<2" "langchain>=1,<2" langchain-openai
pip install pytest pytest-asyncio "langsmith[pytest]"

Local deterministic tests require no API credentials. Live evaluations require an OpenAI API key and a LangSmith API key.

The examples use Python 3.11 or newer and LangGraph/LangChain 1.x APIs. Expected outputs are illustrative; the live model and hosted evaluation examples require execution against your own configured services.

The testing pyramid for agents

A testing pyramid organizes tests according to their scope, execution cost, speed, and reliability.

Agentic applications benefit from a substantial foundation of deterministic tests, complemented by broader integration tests and real-model evaluations.

The following diagram shows the testing hierarchy from inexpensive component checks to production-oriented evaluations.

The testing pyramid for agents diagram: Real Model Regression to Fake Model Integration; Fake Model Integration to Graph Component Tests; Graph Component Tests to Deterministic Unit Tests.

Testing layer What it verifies Real LLM Relative cost
Unit Individual functions and rules No Very low
Graph component Nodes, reducers, routing No Very low
Simulated integration Complete graph orchestration No Low
Live integration Provider and service compatibility Yes Medium
Regression evaluation Behavioral quality across versions Yes Medium to high
End-to-end Deployed application and infrastructure Usually High

Regression testing is technically a testing objective rather than an exclusive testing layer. A deterministic unit test that prevents a previously fixed defect from returning is also a regression test.

Here, the term real-model regression evaluation refers specifically to measuring agent behavior against an established dataset.

Choosing the appropriate layer

Suppose an order support agent contains a validation function, a model node, a lookup tool, and a conditional edge.

Test order ID normalization with a unit test. Test the model-to-tool-to-model sequence with a scripted model. Test whether the actual model chooses the lookup tool for ambiguous customer requests using a live evaluation.

Do not spend model tokens testing string normalization. Conversely, do not assume that a scripted model selecting the correct tool proves that a real model will make the same decision.

Each test should use the least expensive environment capable of detecting the intended failure.

Unit tests

Unit tests execute individual components independently of the complete graph.

In LangGraph, useful unit-testing targets include:

  • Node functions and state updates.
  • Conditional edge functions.
  • Custom reducers.
  • Tool implementations and input validation.
  • Runtime context handling.
  • Authorization and approval rules.
  • Error classification and fallback decisions.

Testing nodes as ordinary Python functions

Most LangGraph nodes are Python functions that accept state and return partial state updates.

LangGraph applies those updates to state channels using their configured reducer behavior. Calling a node directly allows you to inspect its returned update before the graph runtime processes it.

The following example tests a refund policy with an approval boundary of 5,000 cents.

Save it as test_policy.py.

Python
from copy import deepcopy
from typing import Literal, TypedDict

import pytest

class RefundState(TypedDict):
    amount_cents: int
    decision: str

def assess_refund(state: RefundState) -> dict:
    amount = state["amount_cents"]

    if amount <= 0:
        raise ValueError("Amount must be positive")

    return {
        "decision": "review" if amount > 5000 else "approved"
    }

def route_refund(
    state: RefundState,
) -> Literal["review", "execute"]:
    if state["decision"] == "review":
        return "review"

    if state["decision"] == "approved":
        return "execute"

    raise ValueError("Unknown decision")

@pytest.mark.parametrize(
    "amount, expected",
    [
        (1, "approved"),
        (4999, "approved"),
        (5000, "approved"),
        (5001, "review"),
        (100000, "review"),
    ],
)
def test_refund_policy(amount, expected):
    state = {
        "amount_cents": amount,
        "decision": "pending",
    }

    original = deepcopy(state)

    assert assess_refund(state) == {"decision": expected}
    assert state == original

@pytest.mark.parametrize("amount", [0, -1, -100])
def test_invalid_amount(amount):
    with pytest.raises(ValueError, match="positive"):
        assess_refund({
            "amount_cents": amount,
            "decision": "pending",
        })

@pytest.mark.parametrize(
    "decision, expected",
    [
        ("approved", "execute"),
        ("review", "review"),
    ],
)
def test_routing(decision, expected):
    assert route_refund({
        "amount_cents": 100,
        "decision": decision,
    }) == expected

def test_unknown_decision():
    with pytest.raises(ValueError, match="Unknown"):
        route_refund({
            "amount_cents": 100,
            "decision": "invalid",
        })

Run the tests.

Terminal
pytest -v test_policy.py

Expected result:

Text
11 passed

The tests verify boundary conditions, invalid inputs, routing decisions, and the absence of unintended state mutation.

Notice that no graph compilation or model initialization is necessary.

Testing only the middle of an allowed range would miss an accidental change from > to >=. Boundary tests protect the precise business rule.

Testing compiled nodes and reducers

Directly invoking a function does not verify how LangGraph combines its returned update with existing state.

You can access an individual compiled node through graph.nodes or invoke a small compiled graph to test reducer behavior.

This example distinguishes a node’s raw update from its final merged state.

Save it as test_reducers.py.

Python
from typing import Annotated, TypedDict
import operator

from langgraph.graph import StateGraph, START, END

class AuditState(TypedDict):
    events: Annotated[list[str], operator.add]

def validate(state: AuditState):
    return {"events": ["validated"]}

def build_graph():
    builder = StateGraph(AuditState)
    builder.add_node("validate", validate)
    builder.add_edge(START, "validate")
    builder.add_edge("validate", END)
    return builder.compile()

def test_node_update():
    graph = build_graph()

    update = graph.nodes["validate"].invoke({
        "events": ["received"]
    })

    assert update == {"events": ["validated"]}

def test_reducer_merge():
    result = build_graph().invoke({
        "events": ["received"]
    })

    assert result["events"] == [
        "received",
        "validated",
    ]

Expected result: both tests pass. The isolated node returns a partial update, whereas graph execution applies the reducer to produce the accumulated list.

This distinction becomes particularly important in parallel graphs, where multiple nodes may update the same state channel.

Note: Invoking an individual compiled node bypasses normal graph scheduling and checkpoint handling. Use complete graph execution when testing persistence, runtime context propagation, retries, interrupts, or interactions between nodes.

See the LangGraph testing documentation for additional component and partial-execution patterns.

Integration tests with fake models

Integration tests verify that components cooperate correctly.

For LangGraph, this includes message propagation, conditional routing, tool execution, reducers, repeated model calls, and graph termination.

A real model is unnecessary when the behavior under examination is orchestration. Instead, supply a scripted model response.

Understanding test doubles

A test double replaces a dependency during testing.

Test double Purpose Agent example
Stub Returns predetermined data Fixed order status
Fake Provides a lightweight implementation In-memory repository
Mock Verifies interactions Expected API call arguments
Spy Records interactions Tool invocation history

LangChain provides GenericFakeChatModel, which can return a predetermined sequence of strings or AIMessage objects.

Because the responses can include structured tool calls, you can simulate a complete tool-calling conversation.

The fake model does not independently choose tools. Your test supplies those decisions.

Building a testable graph

Dependency injection means providing a graph with its dependencies rather than constructing them internally.

Avoid initializing a paid model at module import time. Instead, accept a model when constructing the graph. Tests can then provide a fake, while production provides a real model.

The following diagram represents the order support agent used in this section.

Integration tests with fake models diagram: START to Assistant Node; Assistant Node to Tool requested?; Tool requested? to Tool Node (Yes); Tool Node to Assistant Node; Tool requested? to END (No).

Save the following application as order_agent.py.

Python
from langchain.messages import SystemMessage
from langchain.tools import tool
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.prebuilt import ToolNode, tools_condition

def make_order_tool(repository):
    @tool
    def lookup_order(order_id: str) -> str:
        """Look up the current status of an order by ID."""
        normalized = order_id.strip().upper()
        return repository(normalized)

    return lookup_order

def build_agent(model, repository, checkpointer=None):
    tools = [make_order_tool(repository)]
    bound_model = model.bind_tools(tools)

    def assistant(state: MessagesState):
        instructions = SystemMessage(content=(
            "You are an order support assistant. "
            "Use lookup_order for specific order status questions. "
            "Never invent an order status. "
            "Answer greetings with Hello without calling tools. "
            "Report unknown orders as not found."
        ))

        response = bound_model.invoke([
            instructions,
            *state["messages"],
        ])

        return {"messages": [response]}

    builder = StateGraph(MessagesState)
    builder.add_node("assistant", assistant)
    builder.add_node(
        "tools",
        ToolNode(tools, handle_tool_errors=True),
    )

    builder.add_edge(START, "assistant")
    builder.add_conditional_edges(
        "assistant",
        tools_condition,
    )
    builder.add_edge("tools", "assistant")

    return builder.compile(checkpointer=checkpointer)

The graph accepts a model, an order repository, and an optional checkpointer.

MessagesState supplies a message reducer, allowing successive AI and tool messages to accumulate rather than replace conversation history.

Testing the complete tool-calling loop

Create test_order_integration.py.

Python
from unittest.mock import Mock

import pytest
from langchain.messages import (
    AIMessage,
    HumanMessage,
    ToolMessage,
)
from langchain_core.language_models.fake_chat_models import (
    GenericFakeChatModel,
)

from order_agent import build_agent

class FakeToolModel(GenericFakeChatModel):
    def bind_tools(self, tools, **kwargs):
        return self

@pytest.fixture
def repository():
    return Mock(side_effect=lambda order_id: {
        "A100": "shipped",
        "A200": "processing",
    }.get(order_id, "not found"))

def test_order_lookup(repository):
    model = FakeToolModel(messages=iter([
        AIMessage(
            content="",
            tool_calls=[{
                "name": "lookup_order",
                "args": {"order_id": "A100"},
                "id": "call_1",
                "type": "tool_call",
            }],
        ),
        AIMessage(content="Order A100 has shipped."),
    ]))

    graph = build_agent(model, repository)

    result = graph.invoke(
        {"messages": [
            HumanMessage(content="Where is order A100?")
        ]},
        config={"recursion_limit": 10},
    )

    messages = result["messages"]

    assert len(messages) == 4
    assert messages[1].tool_calls[0]["name"] == "lookup_order"
    assert messages[1].tool_calls[0]["args"] == {
        "order_id": "A100"
    }

    assert isinstance(messages[2], ToolMessage)
    assert messages[2].tool_call_id == "call_1"
    assert messages[2].content == "shipped"

    repository.assert_called_once_with("A100")

    assert isinstance(messages[-1], AIMessage)
    assert not messages[-1].tool_calls
    assert "shipped" in messages[-1].text.lower()

def test_greeting_skips_tools(repository):
    model = FakeToolModel(messages=iter([
        AIMessage(content="Hello! How can I help?")
    ]))

    graph = build_agent(model, repository)

    result = graph.invoke(
        {"messages": [HumanMessage(content="Hi")]},
        config={"recursion_limit": 10},
    )

    assert len(result["messages"]) == 2
    repository.assert_not_called()

def test_repository_failure(repository):
    repository.side_effect = TimeoutError("Service unavailable")

    model = FakeToolModel(messages=iter([
        AIMessage(
            content="",
            tool_calls=[{
                "name": "lookup_order",
                "args": {"order_id": "A100"},
                "id": "call_error",
                "type": "tool_call",
            }],
        ),
        AIMessage(content="Order status is unavailable."),
    ]))

    result = build_agent(model, repository).invoke(
        {"messages": [
            HumanMessage(content="Where is A100?")
        ]},
        config={"recursion_limit": 10},
    )

    tool_message = result["messages"][2]

    assert isinstance(tool_message, ToolMessage)
    assert tool_message.status == "error"
    assert tool_message.tool_call_id == "call_error"
    assert "unavailable" in result["messages"][-1].text.lower()
    repository.assert_called_once_with("A100")

Run the integration suite.

Terminal
pytest -v test_order_integration.py

Expected result:

Text
3 passed

The successful execution contains four messages:

  1. The original human request.
  2. An AI message containing a structured tool call.
  3. A tool message containing the repository result.
  4. The final AI response without further tool calls.

The mock repository verifies an actual dependency invocation, independently of the generated answer.

The failure test confirms that ToolNode converts the configured tool failure into an error message and allows the graph to continue. It does not establish that a real model will formulate an appropriate recovery response; that requires live evaluation.

The bind_tools override is intentional. GenericFakeChatModel does not implement ordinary provider tool binding.

Tip: Create a fresh fake model for each test. Its scripted response iterator is consumed during execution, so sharing it across tests creates order-dependent failures.

See LangChain unit testing for supported fake model implementations.

Testing persistence and human approval

Stateful workflows introduce additional contracts: execution must pause correctly, resume against the correct thread, and avoid unauthorized side effects.

The following test verifies that a rejected approval cannot trigger a protected operation.

Save as test_approval.py.

Python
from typing import TypedDict
from unittest.mock import Mock

import pytest
from langgraph.graph import StateGraph, START, END
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.types import Command, interrupt

class ApprovalState(TypedDict):
    amount: int
    approved: bool
    status: str

def build_approval_graph(execute):
    def approval(state):
        decision = interrupt({
            "amount": state["amount"],
            "question": "Approve transaction?",
        })

        if decision is True:
            execute(state["amount"])
            return {"approved": True, "status": "executed"}

        return {"approved": False, "status": "rejected"}

    builder = StateGraph(ApprovalState)
    builder.add_node("approval", approval)
    builder.add_edge(START, "approval")
    builder.add_edge("approval", END)

    return builder.compile(
        checkpointer=InMemorySaver()
    )

@pytest.mark.parametrize(
    "decision, expected",
    [(True, "executed"), (False, "rejected")],
)
def test_approval(decision, expected):
    execute = Mock()
    graph = build_approval_graph(execute)

    config = {
        "configurable": {"thread_id": "approval-test"}
    }

    paused = graph.invoke(
        {
            "amount": 500,
            "approved": False,
            "status": "pending",
        },
        config,
    )

    assert paused["__interrupt__"]
    execute.assert_not_called()

    result = graph.invoke(
        Command(resume=decision),
        config,
    )

    assert result["status"] == expected
    assert result["approved"] is decision
    assert graph.get_state(config).next == ()

    if decision:
        execute.assert_called_once_with(500)
    else:
        execute.assert_not_called()

Expected result: two passing tests, covering approval and rejection.

An interrupted node restarts from its beginning when resumed. Consequently, non-idempotent side effects placed before interrupt() can execute more than once.

Production transaction execution should additionally use idempotency keys and durable storage. This test verifies approval behavior, not exactly-once execution after infrastructure failures.

Other graph integration scenarios worth testing include thread isolation, parallel reducer updates, retry exhaustion, malformed tool arguments, empty retrieval results, and recursion-limit failures.

Regression tests with real models

A deterministic suite can pass while actual agent quality deteriorates.

Changing a system prompt, model version, tool description, retrieval algorithm, or graph topology can alter the decisions made by a real model.

Regression evaluation measures those changes against known expectations.

A regression dataset should contain normal requests, historical failures, ambiguous inputs, edge cases, and requests that must not trigger particular tools.

Creating a stable regression dataset

For the order agent, use synthetic repository data so that the expected answers do not change when real orders change.

Configure credentials.

Terminal
export OPENAI_API_KEY="your-openai-api-key"
export LANGSMITH_API_KEY="your-langsmith-api-key"
export LANGSMITH_TRACING=true
export LANGSMITH_PROJECT="order-agent-testing"

Save the following one-time setup script as seed_dataset.py.

Python
from langsmith import Client

client = Client()

dataset = client.create_dataset(
    dataset_name="order-agent-regression-v1",
    description="Synthetic order support regression cases",
)

client.create_examples(
    dataset_id=dataset.id,
    examples=[
        {
            "inputs": {"question": "Where is order A100?"},
            "outputs": {
                "order_ids": ["A100"],
                "answer_contains": "shipped",
            },
        },
        {
            "inputs": {"question": "Status of A200 please"},
            "outputs": {
                "order_ids": ["A200"],
                "answer_contains": "processing",
            },
        },
        {
            "inputs": {"question": "Find order A999"},
            "outputs": {
                "order_ids": ["A999"],
                "answer_contains": "not found",
            },
        },
        {
            "inputs": {"question": "Hello"},
            "outputs": {
                "order_ids": [],
                "answer_contains": "hello",
            },
        },
    ],
)

print("Dataset created:", dataset.name)

Running this script creates four evaluation examples in LangSmith. Run it only once for this dataset name.

For repeatable comparisons, freeze the dataset version using a version tag in LangSmith. Do not silently modify expected outputs when the candidate agent fails.

Executing regression evaluations

The evaluation target should convert graph output into explicit, serializable fields.

This makes evaluators independent of the graph’s internal state schema.

Save the following as regression.py beside order_agent.py.

Python
import os
from statistics import mean

from langchain.chat_models import init_chat_model
from langchain.messages import AIMessage, HumanMessage
from langsmith import Client

from order_agent import build_agent

MODEL = "openai:gpt-5.4-mini"

def repository(order_id):
    return {
        "A100": "shipped",
        "A200": "processing",
    }.get(order_id, "not found")

def target(inputs: dict) -> dict:
    model = init_chat_model(MODEL)
    graph = build_agent(model, repository)

    result = graph.invoke(
        {"messages": [
            HumanMessage(content=inputs["question"])
        ]},
        config={"recursion_limit": 10},
    )

    messages = result["messages"]

    calls = [
        call
        for message in messages
        if isinstance(message, AIMessage)
        for call in message.tool_calls
    ]

    return {
        "answer": messages[-1].text,
        "tool_names": [call["name"] for call in calls],
        "order_ids": [
            str(call["args"].get("order_id", "")).strip().upper()
            for call in calls
        ],
    }

def tool_selection(outputs: dict, reference_outputs: dict):
    expected_ids = reference_outputs["order_ids"]

    correct = (
        outputs["order_ids"] == expected_ids
        and outputs["tool_names"] ==
        ["lookup_order"] * len(expected_ids)
    )

    return {"key": "tool_selection", "score": int(correct)}

def answer_correctness(
    outputs: dict,
    reference_outputs: dict,
):
    expected = reference_outputs["answer_contains"].lower()
    correct = expected in outputs["answer"].lower()

    return {
        "key": "answer_correctness",
        "score": int(correct),
    }

def run_regression():
    client = Client()

    examples = list(client.list_examples(
        dataset_name="order-agent-regression-v1",
        as_of=os.environ["ORDER_DATASET_VERSION"],
    ))

    if not examples:
        raise RuntimeError("Regression dataset is empty")

    repetitions = 3

    results = client.evaluate(
        target,
        data=examples,
        evaluators=[
            tool_selection,
            answer_correctness,
        ],
        experiment_prefix="order-agent",
        num_repetitions=repetitions,
        max_concurrency=2,
        blocking=True,
        metadata={
            "model": MODEL,
            "git_sha": os.getenv("GITHUB_SHA", "local"),
            "dataset_version": os.environ["ORDER_DATASET_VERSION"],
        },
    )

    rows = list(results)

    if len(rows) != len(examples) * repetitions:
        raise RuntimeError("Incomplete evaluation")

    metrics = {
        "tool_selection": [],
        "answer_correctness": [],
    }

    for row in rows:
        if row["run"].error:
            raise RuntimeError(row["run"].error)

        feedback = {
            item.key: item.score
            for item in row["evaluation_results"]["results"]
        }

        for key in metrics:
            score = feedback.get(key)

            if score not in (0, 1):
                raise RuntimeError(f"Invalid metric: {key}")

            metrics[key].append(float(score))

    averages = {
        key: mean(values)
        for key, values in metrics.items()
    }

    print("Experiment:", results.experiment_name)
    print("Scores:", averages)

    if averages["tool_selection"] < 1.0:
        raise SystemExit("FAIL: Tool selection regression")

    if averages["answer_correctness"] < 0.90:
        raise SystemExit("FAIL: Answer quality regression")

    print("Regression gate passed")

if __name__ == "__main__":
    run_regression()

After tagging the dataset version with v1 in LangSmith, run:

Terminal
export ORDER_DATASET_VERSION="v1"
python regression.py

An illustrative successful output is:

Text
Experiment: order-agent-...
Scores: {'tool_selection': 1.0, 'answer_correctness': 1.0}
Regression gate passed

The script evaluates four examples three times, resulting in twelve agent executions. Individual executions may involve multiple model requests.

It explicitly rejects missing metrics, incomplete experiments, and execution errors rather than treating them as successful results.

The two acceptance thresholds are illustrative engineering decisions: perfect tool-selection accuracy and at least 90% answer correctness.

The SDK evaluation and dataset-versioning APIs are documented in LangSmith evaluation and dataset management.

Comparing against a baseline

An absolute quality threshold prevents the application from falling below a minimum standard. It does not necessarily prevent degradation from a previously stronger version.

Suppose these experiments use the same dataset and evaluator configuration.

Metric Approved baseline Candidate Decision
Answer correctness 98% 94% Review regression
Tool selection 100% 100% Pass
Critical policy checks 100% 98% Block
P95 latency 2.8 s 3.6 s Review budget
Average cost per task $0.012 $0.009 Improvement

A production release policy might require both an absolute score of 90% and a maximum decline of two percentage points relative to the approved baseline.

Compare experiments in LangSmith using their per-example results, not just aggregate scores. An improved average can conceal serious failures within a particular category.

The substring evaluator above is deliberately simple. It can incorrectly accept contradictory statements such as “Order A100 has not shipped.”

For open-ended answers, supplement deterministic checks with the calibrated LLM-as-a-judge and trajectory evaluators introduced in the previous lesson.

Repeated execution helps reveal instability, but three repetitions across four examples do not establish statistically reliable production quality. Expand datasets, measure important categories separately, and investigate uncertain results.

In CI

Continuous integration transforms tests from occasional developer activities into enforceable engineering safeguards.

A practical pipeline separates tests according to their external dependencies and execution cost.

Organizing test execution

Use a repository structure similar to:

Text
order-project/
    order_agent.py
    seed_dataset.py
    regression.py
    requirements.lock
    pytest.ini
    tests/
        test_policy.py
        test_reducers.py
        test_order_integration.py
        test_approval.py
        test_live.py
    .github/
        workflows/
            tests.yml

Move the earlier pytest examples into tests/. Generate and commit a dependency lock from your validated environment.

Terminal
pip freeze > requirements.lock

Register a marker in pytest.ini for tests that require external services.

INI
[pytest]
testpaths = tests
pythonpath = .
addopts = --strict-markers
markers =
    live: tests requiring external services

Tracking pytest regressions in LangSmith

LangSmith also supports native pytest integration through @pytest.mark.langsmith.

The following optional tests/test_live.py records individual assertions as tracked evaluation results.

Python
import pytest
from langsmith import testing as t

from regression import target

@pytest.mark.live
@pytest.mark.langsmith
def test_live_order_lookup():
    inputs = {"question": "Where is order A100?"}
    expected = {
        "order_ids": ["A100"],
        "status": "shipped",
    }

    t.log_inputs(inputs)
    t.log_reference_outputs(expected)

    result = target(inputs)

    t.log_outputs(result)

    assert result["tool_names"] == ["lookup_order"]
    assert result["order_ids"] == ["A100"]
    assert "shipped" in result["answer"].lower()

Run this optional live suite with the credentials configured.

Terminal
LANGSMITH_TEST_SUITE=order-agent-live pytest -v -m live

The test’s pass/fail outcome is tracked in LangSmith, along with its inputs, outputs, and reference outputs. Unlike the frozen dataset experiment, this integration maintains examples from the marked pytest cases.

See LangSmith pytest integration.

Automating the pipeline

The following GitHub Actions workflow runs deterministic tests on pushes and pull requests, with live evaluations on a nightly schedule or manual dispatch.

Save it as .github/workflows/tests.yml.

YAML
name: Agent tests

on:
  push:
  pull_request:
  workflow_dispatch:
  schedule:
    - cron: "0 2 * * *"

jobs:
  deterministic:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    env:
      LANGSMITH_TRACING: "false"

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -r requirements.lock
      - run: pytest -v -m "not live"

  regression:
    needs: deterministic
    if: github.event_name == 'schedule' || github.event_name == 'workflow_dispatch'
    runs-on: ubuntu-latest
    timeout-minutes: 20

    env:
      OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
      LANGSMITH_API_KEY: ${{ secrets.LANGSMITH_API_KEY }}
      LANGSMITH_TRACING: "true"
      LANGSMITH_PROJECT: order-agent-ci
      ORDER_DATASET_VERSION: v1
      LANGSMITH_TEST_SUITE: order-agent-live

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -r requirements.lock
      - run: pytest -v -m live
      - run: python regression.py

Configure API keys as repository secrets, not committed environment files.

A failed deterministic assertion blocks the dependent evaluation job. A failed regression threshold produces a nonzero process exit code and fails the regression job.

This workflow intentionally excludes live evaluation from ordinary pull requests to control cost and protect credentials. To enforce regression approval before deployment, configure your deployment workflow to require a successful evaluation for the exact candidate commit.

Production testing practices

Avoid exact sentence comparisons for unconstrained model output. Assert structured fields, required facts, policy compliance, or calibrated semantic scores instead.

Never reuse mutable test state accidentally. Use fresh checkpointers, fake models, stores, and isolated thread identifiers.

Control external execution through recursion limits, request timeouts, limited concurrency, and test budgets. Disable or sandbox irreversible tools, including payment execution and record deletion.

Distinguish infrastructure failures from behavioral failures. A provider outage should fail or invalidate the evaluation, but it should not be mistaken for evidence that a new prompt is inferior.

For the chapter’s multi-agent project, apply unit tests to each specialist’s deterministic logic, simulated integration tests to supervisor routing and handoffs, and live regression evaluations to complete user journeys. Use LangSmith traces to investigate failures and convert confirmed defects into permanent test cases.

In the next lesson, Model Context Protocol (MCP), you will introduce standardized external tool connections. The same testing architecture remains applicable: isolate MCP dependencies with test doubles, verify schemas and connectivity in dedicated integration tests, and evaluate real-model tool selection using controlled regression datasets.

Exercise

Build a tested order support agent

Build a LangGraph agent that retrieves order information through a tool and answers general questions without unnecessary tool calls. Write deterministic unit tests for the order lookup tool and integration tests using a fake chat model. Verify the selected tool, tool arguments, tool response, final answer, and termination of the graph.

Python
# pip install "langgraph>=1,<2" "langchain>=1,<2" pytest
# Save as test_order_agent.py
# Run with: pytest -v test_order_agent.py

import pytest
from langchain.messages import AIMessage, HumanMessage, ToolMessage
from langchain.tools import tool
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
from langgraph.graph import StateGraph, MessagesState, START
from langgraph.prebuilt import ToolNode, tools_condition

ORDERS = {
    "A100": "shipped",
    "A200": "processing",
}

@tool
def lookup_order(order_id: str) -> str:
    """Return the current status of an order."""
    # TODO: Normalize the ID and handle unknown orders.
    raise NotImplementedError

class FakeToolModel(GenericFakeChatModel):
    def bind_tools(self, tools, **kwargs):
        return self

def build_graph(model):
    # TODO: Bind the tool to the model.
    # TODO: Create the model node.
    # TODO: Add ToolNode and conditional routing.
    # TODO: Compile and return the graph.
    raise NotImplementedError

def test_lookup_order():
    # TODO: Test known and unknown order IDs.
    raise NotImplementedError

def test_agent_uses_tool():
    # TODO: Script a tool call followed by a final answer.
    # TODO: Invoke the graph and verify the execution.
    raise NotImplementedError

def test_agent_skips_unnecessary_tool():
    # TODO: Script a direct answer to a greeting.
    # TODO: Verify that no tool was executed.
    raise NotImplementedError

Summary

  • Unit tests isolate deterministic business logic, state transformations, reducers, routing functions, and tool implementations.
  • Integration tests with fake models verify graph orchestration without depending on external model providers.
  • Dependency injection makes models, tools, persistence, and external services independently replaceable during testing.
  • Agent tests should verify execution trajectories, tool arguments, state invariants, side effects, and final responses.
  • Regression testing uses representative datasets and consistent evaluation criteria to detect behavioral degradation across application versions.
  • LangSmith experiments provide historical evidence for comparing agent quality, reliability, latency, and cost.
  • Production CI pipelines should separate deterministic tests from probabilistic evaluations and enforce explicit release thresholds.