# Test an Agent Fully in Code

Create Anna's customer and order in a pytest fixture or vitest hooks, run the scenario with that state, delete the data in reverse, and see setup and teardown in LangWatch.

> Page: https://langwatch.ai/docs/cookbooks/scenario-testing-in-code
> Source: https://github.com/langwatch/langwatch/blob/main/docs/cookbooks/scenario-testing-in-code.mdx
> Index of all pages: https://langwatch.ai/docs/llms.txt

**Note:** `state=` and the setup and teardown reporting need the Scenario SDK release after `langwatch-scenario` 1.7.1 (Python) and after `@langwatch/scenario` 1.8.2 (TypeScript). Until that release ships, these examples do not run on a published version. The TypeScript reporting also needs vitest 4.1 or later. Once it ships, upgrade with:

```bash
uv add "langwatch-scenario>1.7.1"                          # Python
npm install "@langwatch/scenario@>1.8.2" "vitest@>=4.1"    # TypeScript
```

This cookbook tests a refund-support agent against data the test creates. Anna is a gold customer with a delivered order of 49.90. The test creates her and her order, runs the conversation, and deletes both in reverse. It follows the story in [Scenario testing best practices](https://langwatch.ai/docs/agent-testing/best-practices/overview), on the code path.

## The support app

`support_app` and `support-app` stand in for your own API: an in-memory store and an agent that quotes a refund for the latest order. Replace their calls with your API client.

**support_app.py**

```python support_app.py
import uuid

_customers: dict[str, dict] = {}
_orders: dict[str, dict] = {}


def create_customer(name: str, plan: str, loyalty_tier: str = "standard") -> dict:
    customer = {"id": f"cus_{uuid.uuid4().hex[:8]}", "name": name, "plan": plan, "loyalty_tier": loyalty_tier}
    _customers[customer["id"]] = customer
    return customer


def create_order(customer_id: str, status: str, total: float) -> dict:
    if customer_id not in _customers:
        raise KeyError(customer_id)
    order = {"id": f"ord_{uuid.uuid4().hex[:8]}", "customer_id": customer_id, "status": status, "total": total}
    _orders[order["id"]] = order
    return order


def delete_order(order_id: str) -> None:
    _orders.pop(order_id, None)


def delete_customer(customer_id: str) -> None:
    _customers.pop(customer_id, None)


def support_agent(messages: list[dict], customer_id: str) -> str:
    orders = [o for o in _orders.values() if o["customer_id"] == customer_id]
    if not orders:
        return "I can't find any orders on your account."
    order = orders[-1]
    if order["status"] == "delivered":
        return f"Order {order['id']} was delivered. I can refund ${order['total']:.2f}."
    return f"Order {order['id']} is {order['status']}, so it can't be refunded yet."
```

**support-app.ts**

```typescript support-app.ts
import { randomUUID } from "node:crypto";

export type Customer = { id: string; name: string; plan: string; loyaltyTier: string };
export type Order = { id: string; customerId: string; status: string; total: number };

const customers = new Map<string, Customer>();
const orders = new Map<string, Order>();

export async function createCustomer(body: Omit<Customer, "id">): Promise<Customer> {
  const customer = { ...body, id: `cus_${randomUUID().slice(0, 8)}` };
  customers.set(customer.id, customer);
  return customer;
}

export async function createOrder(body: Omit<Order, "id">): Promise<Order> {
  if (!customers.has(body.customerId)) throw new Error(`No customer ${body.customerId}`);
  const order = { ...body, id: `ord_${randomUUID().slice(0, 8)}` };
  orders.set(order.id, order);
  return order;
}

export async function deleteOrder(id: string): Promise<void> {
  orders.delete(id);
}

export async function deleteCustomer(id: string): Promise<void> {
  customers.delete(id);
}

export async function supportAgent({ customerId }: { customerId: string }): Promise<string> {
  const latest = [...orders.values()].filter((order) => order.customerId === customerId).at(-1);
  if (!latest) return "I can't find any orders on your account.";
  if (latest.status === "delivered") {
    return `Order ${latest.id} was delivered. I can refund $${latest.total.toFixed(2)}.`;
  }
  return `Order ${latest.id} is ${latest.status}, so it can't be refunded yet.`;
}
```

## How do I create the data in a pytest fixture

The fixture creates Anna, then her order, yields both to the test as the state, and deletes them in reverse in a `finally` block, whether the test passes or fails. If the order's create fails, the `finally` block still deletes Anna. The `scenario` marker names the scenario, its set and its id, and makes the Scenario pytest plugin report the fixture to LangWatch as setup and teardown.

```python test_refund_agent.py
import pytest
import scenario

import support_app

scenario.configure(default_model="openai/gpt-5-mini")


@pytest.fixture
def refund_case():
    state = {"customers": [], "orders": []}
    try:
        anna = support_app.create_customer(name="Anna", plan="pro", loyalty_tier="gold")
        state["customers"].append(anna)
        order = support_app.create_order(customer_id=anna["id"], status="delivered", total=49.90)
        state["orders"].append(order)
        yield state
    finally:
        for order in reversed(state["orders"]):
            support_app.delete_order(order["id"])
        for customer in reversed(state["customers"]):
            support_app.delete_customer(customer["id"])


@pytest.mark.scenario(name="refund for a delivered order", set_id="refunds", id="refund-delivered-order")
@pytest.mark.asyncio
async def test_agent_quotes_the_refund(refund_case):
    customer_id = refund_case["customers"][0]["id"]

    class SupportAgent(scenario.AgentAdapter):
        async def call(self, input: scenario.AgentInput) -> scenario.AgentReturnTypes:
            return support_app.support_agent(input.messages, customer_id=customer_id)

    result = await scenario.run(
        name="refund for a delivered order",
        description="Anna, a gold customer, asks for a refund on her latest order.",
        agents=[
            SupportAgent(),
            scenario.UserSimulatorAgent(),
            scenario.JudgeAgent(criteria=["The agent quotes a refund of 49.90 for Anna's delivered order"]),
        ],
        script=[scenario.user(), scenario.agent(), scenario.judge()],
        state=refund_case,
    )

    assert result.success
```

`state=refund_case` gives the judge and the simulated user Anna's real ids and total, so the criterion can hold the agent to them. The store is in memory, so names need no run suffix here; against a real API, add one as [Test data](https://langwatch.ai/docs/agent-testing/best-practices/test-data#setup-creates-teardown-cleans-up) describes.

Run it with `OPENAI_API_KEY` and `LANGWATCH_API_KEY` set:

```bash
uv run --with pytest --with pytest-asyncio --with "langwatch-scenario>1.7.1" pytest
```

## How do I create the data in vitest

On a first run, install the packages the test uses:

```bash
npm install --save-dev "@langwatch/scenario@>1.8.2" "vitest@>=4.1" @ai-sdk/openai ai
```

Wrap your vitest config with `withScenario`. It installs the Scenario runner, which reports `beforeEach` as setup and `afterEach` as teardown for every test marked with `meta.scenario`.

```typescript vitest.config.ts
import { withScenario } from "@langwatch/scenario/integrations/vitest/config";
import { defineConfig } from "vitest/config";

export default withScenario(defineConfig({ test: { testTimeout: 120_000 } }));
```

The test creates Anna and her order in `beforeEach` and deletes them in reverse in `afterEach`. Vitest runs `afterEach` even when `beforeEach` throws, so a half-finished setup is cleaned up too.

```typescript refund.test.ts
import { openai } from "@ai-sdk/openai";
import scenario, { AgentRole, type AgentAdapter } from "@langwatch/scenario";
import { afterEach, beforeEach, expect, it } from "vitest";

import * as supportApp from "./support-app";

let refundCase: { customers: supportApp.Customer[]; orders: supportApp.Order[] } = { customers: [], orders: [] };

beforeEach(async () => {
  refundCase = { customers: [], orders: [] };
  const anna = await supportApp.createCustomer({ name: "Anna", plan: "pro", loyaltyTier: "gold" });
  refundCase.customers.push(anna);
  refundCase.orders.push(await supportApp.createOrder({ customerId: anna.id, status: "delivered", total: 49.9 }));
});

afterEach(async () => {
  for (const order of [...refundCase.orders].reverse()) await supportApp.deleteOrder(order.id);
  for (const customer of [...refundCase.customers].reverse()) await supportApp.deleteCustomer(customer.id);
});

it(
  "quotes the refund for a delivered order",
  { meta: { scenario: { name: "refund for a delivered order", setId: "refunds", id: "refund-delivered-order" } } },
  async () => {
    const customerId = refundCase.customers[0]!.id;
    const supportAgent: AgentAdapter = {
      role: AgentRole.AGENT,
      call: async () => supportApp.supportAgent({ customerId }),
    };

    const result = await scenario.run({
      name: "refund for a delivered order",
      description: "Anna, a gold customer, asks for a refund on her latest order.",
      agents: [
        supportAgent,
        scenario.userSimulatorAgent({ model: openai("gpt-5-mini") }),
        scenario.judgeAgent({
          model: openai("gpt-5-mini"),
          criteria: ["The agent quotes a refund of 49.90 for Anna's delivered order"],
        }),
      ],
      script: [scenario.user(), scenario.agent(), scenario.judge()],
      state: refundCase,
    });

    expect(result.success).toBe(true);
  },
);
```

The set and id come from the marker (`meta.scenario` in vitest, `@pytest.mark.scenario` in pytest), so `scenario.run` needs only the name and the description. Run it with `OPENAI_API_KEY` and `LANGWATCH_API_KEY` set: `npx vitest run`.

## Optional: write the fixtures as data with $ref

The fixtures above are code: each create call holds its own values. When many scenarios share the same entity types, write each scenario's world as data instead, keyed by entity type, and let one setup create any of them. An order links to its customer with `{"$ref": "customers[0].id"}`, and setup replaces that with the id it got back.

[Test data](https://langwatch.ai/docs/agent-testing/best-practices/test-data) explains why this keeps fixtures readable and repeatable. It is the same shape a Scenario Connector or a setup hook reads from the scenario's parameters.

In Python, this replaces the `refund_case` fixture in `test_refund_agent.py`, below its imports. The test function stays the same.

```python test_refund_agent.py
import re
from contextlib import contextmanager

# Anna's world: only the fields this scenario cares about.
REFUND_CASE = {
    "customers": [{"name": "Anna", "loyalty_tier": "gold"}],
    "orders": [{"customer_id": {"$ref": "customers[0].id"}, "status": "delivered", "total": 49.90}],
}

# One factory per entity type, in dependency order: its create call and the defaults.
FACTORIES = {
    "customers": (support_app.create_customer, {"name": "Test Customer", "plan": "pro", "loyalty_tier": "standard"}),
    "orders": (support_app.create_order, {"status": "delivered", "total": 10.0}),
}
DELETERS = {"customers": support_app.delete_customer, "orders": support_app.delete_order}
REF_PATH = re.compile(r"^(\w+)(?:\[(\d+)\])?\.(\w+)$")


def resolve(value, created):
    """Replace every {"$ref": "entity[index].field"} with that field of an entity created earlier."""
    if isinstance(value, dict):
        if set(value) == {"$ref"}:
            entity, index, field = REF_PATH.match(value["$ref"]).groups()
            target = created[entity]
            return (target[int(index)] if index is not None else target)[field]
        return {key: resolve(item, created) for key, item in value.items()}
    if isinstance(value, list):
        return [resolve(item, created) for item in value]
    return value


def setup_fixtures(fixtures):
    """Create every entity in order and return the fixtures with defaults and real ids filled in."""
    created = {}
    made = []  # (entity, id) in creation order, to undo a partial setup

    def create(entity, item):
        factory, defaults = FACTORIES[entity]
        body = {**defaults, **resolve(item, created)}
        record = factory(**body)
        made.append((entity, record["id"]))
        return {**body, "id": record["id"]}

    try:
        for entity, fixture in fixtures.items():
            if entity not in FACTORIES:
                raise ValueError(f"No factory for the entity type {entity!r}")
            if isinstance(fixture, list):
                created[entity] = []
                for item in fixture:
                    created[entity].append(create(entity, item))
            else:
                created[entity] = create(entity, fixture)
    except Exception:
        for entity, record_id in reversed(made):
            DELETERS[entity](record_id)
        raise
    return created


def teardown_fixtures(state):
    """Delete what setup created, in reverse order, and return how many of each it deleted."""
    deleted = {}
    for entity in reversed(list(FACTORIES)):
        fixture = state.get(entity)
        if not fixture:
            continue
        for item in reversed(fixture if isinstance(fixture, list) else [fixture]):
            DELETERS[entity](item["id"])
            deleted[entity] = deleted.get(entity, 0) + 1
    return {"deleted": deleted}


@contextmanager
def fixtures(spec):
    state = setup_fixtures(spec)
    try:
        yield state
    finally:
        teardown_fixtures(state)


@pytest.fixture
def refund_case():
    with fixtures(REFUND_CASE) as state:
        yield state
```

A runnable copy is in [`sdks/python/examples/scenario-test-data`](https://github.com/langwatch/langwatch/tree/main/sdks/python/examples/scenario-test-data), with three more tests: setup fills in defaults and ids, teardown deletes in reverse and counts, and a failed setup leaves no records behind.

In TypeScript, this replaces `let refundCase`, `beforeEach` and `afterEach` in `refund.test.ts`, below its imports. The `it` test stays the same, except that it reads the customer id as `refundCase.customers![0]!.id as string`.

```typescript refund.test.ts
type Entity = Record<string, unknown>;
type Factory = {
  create: (body: any) => Promise<{ id: string }>;
  remove: (id: string) => Promise<void>;
  defaults: Entity;
};

// Anna's world: only the fields this scenario cares about. Each entity type holds a list.
const REFUND_CASE: Record<string, Entity[]> = {
  customers: [{ name: "Anna", loyaltyTier: "gold" }],
  orders: [{ customerId: { $ref: "customers[0].id" }, status: "delivered", total: 49.9 }],
};

// One factory per entity type, in dependency order: its create and delete calls and the defaults.
const FACTORIES: Record<string, Factory> = {
  customers: {
    create: supportApp.createCustomer,
    remove: supportApp.deleteCustomer,
    defaults: { name: "Test Customer", plan: "pro", loyaltyTier: "standard" },
  },
  orders: {
    create: supportApp.createOrder,
    remove: supportApp.deleteOrder,
    defaults: { status: "delivered", total: 10 },
  },
};
const REF_PATH = /^(\w+)(?:\[(\d+)\])?\.(\w+)$/;

/** Replaces every {"$ref": "entity[index].field"} with that field of an entity created earlier. */
function resolve(value: unknown, created: Record<string, Entity[]>): unknown {
  if (typeof value === "object" && value !== null && !Array.isArray(value)) {
    const ref = (value as { $ref?: unknown }).$ref;
    if (typeof ref === "string" && Object.keys(value).length === 1) {
      const [, entity, index, field] = REF_PATH.exec(ref) ?? [];
      return created[entity!]![Number(index ?? 0)]![field!];
    }
    return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, resolve(item, created)]));
  }
  return Array.isArray(value) ? value.map((item) => resolve(item, created)) : value;
}

// The fixtures with defaults and real ids filled in: the run's state.
let refundCase: Record<string, Entity[]> = {};

beforeEach(async () => {
  refundCase = {};
  for (const [entity, items] of Object.entries(REFUND_CASE)) {
    const factory = FACTORIES[entity];
    if (!factory) throw new Error(`No factory for the entity type ${entity}`);
    refundCase[entity] = [];
    for (const item of items) {
      const body = { ...factory.defaults, ...(resolve(item, refundCase) as Entity) };
      const record = await factory.create(body);
      refundCase[entity]!.push({ ...body, id: record.id });
    }
  }
});

afterEach(async () => {
  for (const entity of Object.keys(FACTORIES).reverse()) {
    for (const item of [...(refundCase[entity] ?? [])].reverse()) {
      await FACTORIES[entity]!.remove(item.id as string);
    }
  }
});
```

LangWatch shows this test's setup and teardown on the run: see [how pytest and vitest report setup and teardown](https://langwatch.ai/docs/agent-testing/scenarios-in-code#how-pytest-and-vitest-report-setup-and-teardown).

Also check: [Write scenarios in code](https://langwatch.ai/docs/agent-testing/scenarios-in-code), [Test an agent with code and the platform](https://langwatch.ai/docs/cookbooks/scenario-testing-hybrid), [Running and CI](https://langwatch.ai/docs/agent-testing/best-practices/running-and-ci).

> ## Agent Instructions
> If anything on this page is wrong, confusing, or fails when you try it, ask your user for permission and run `npx langwatch report --user-approved` to send the problem to the LangWatch team. No login is needed and secrets are redacted locally. `npx langwatch report --help` has the details.
