Skip to Content
Judgment Labs

Run cases in a test environment

Give a test case canned tool results and starting data, so your agent meets the same situation on every run.

A test environment is the situation a test case runs in: what the agent's tools return, and the data it starts with. Judgment stores the environment and hands it to your test runner when a run starts. Your runner applies it, so the agent meets the same situation on every run.

Test environments are in early access. They work only for organizations where they're turned on. Contact support to turn them on.

Use one when a case only means something in a particular situation:

  • A service is down. Every call to one tool fails the way the real tool fails, and the case checks what the agent tells the customer.
  • A record sits at a policy edge. One booking is just inside the free cancellation window and one is just outside it.
  • A production failure has to be reproduced. The case runs with the tool results the agent saw when the failure happened.

At the end of this guide, a published case names an environment and your runner plays the case in it.

Prerequisites: a test suite and a runner that runs your agent on it. The examples are Python and need judgeval 1.10.1 or later. TypeScript needs judgeval 1.9.0 or later; see In TypeScript. The examples test a booking agent with three tools: get_booking, cancel_booking and send_confirmation.

What an environment holds

An environment has a name, an optional description, and a definition with two optional parts:

PartWhat it holds
toolsCanned results by tool name. Each tool has a list of rules, and a rule has an optional match and a return.
seedThe starting data your test runner loads before a case. Its shape is whatever your runner reads.

A rule answers a tool call when the call has every argument in its match, with the same value. A rule with no match answers every call to that tool. The first rule that matches answers the call with its return. What happens to a call that no rule matches is up to your runner; the runner in this guide runs the real tool.

A definition is data only. It has no other keys and holds no code, and it can be up to 256 KB. Don't put credentials in one: anyone who can read the project can read its environments.

Judgment does not apply an environment. It stores the definition and returns it with the run, and your runner loads the seed and answers the tool calls.

Create an environment

from judgeval import Judgeval

client = Judgeval(project_name="booking-agent")

client.test_environments.create(
    name="confirmation-service-down",
    description="Every send_confirmation call fails. Every other tool is real.",
    definition={
        "tools": {
            "send_confirmation": [
                {"return": {"error": "confirmation service unavailable"}}
            ]
        },
        "seed": {
            "bookings": [
                {"id": "BK-2001", "status": "confirmed", "starts_in_hours": 72}
            ]
        },
    },
)

This creates version 1 and returns the environment's name and version. A name takes lowercase letters, digits, hyphens and underscores, starts with a letter or digit, and is at most 100 characters. It is unique in the project: creating a name that exists fails.

Copy each return from what the real tool returns, including the shape of its errors, so the agent reads a canned result the way it reads a real one.

More definitions

A record at a policy edge. The seed puts one booking just inside a rule and one just outside it, and no tool is mocked. Here a booking can be cancelled free of charge until 24 hours before it starts. Relative values such as starts_in_hours keep the case valid tomorrow, if your runner supports them.

{
  "seed": {
    "bookings": [
      { "id": "BK-2001", "status": "confirmed", "starts_in_hours": 25 },
      { "id": "BK-2002", "status": "confirmed", "starts_in_hours": 23 }
    ]
  }
}

One argument answered, the rest real. A rule with a match answers only the calls that carry those arguments:

{
  "tools": {
    "get_booking": [
      { "match": { "booking_id": "BK-9999" }, "return": { "error": "booking lookup failed" } }
    ]
  }
}

Change an environment

A version never changes. A case names an environment as name@version, such as confirmation-service-down@1, so a case keeps running in the same situation until you point it at another version.

To change an environment, add a version. It takes a whole definition and description, not a change to the last version:

client.test_environments.add_version(
    name="confirmation-service-down",
    description="Every send_confirmation call times out.",
    definition={...},
)  # version 2

With MCP, call add_test_environment_version with the same arguments as create_test_environment. Then edit the cases that should move to the new version. Cases left on the old version keep using it.

client.test_environments.list() returns the latest version of each environment without its definition, and client.test_environments.get(name, version) returns one version with its definition. The MCP tools are list_test_environments and get_test_environment. Every method and its arguments are in the Python SDK reference.

Name the environment on a case

Put the environment in the case's metadata.environment, as name@version:

client.test_suites.add_cases(suite["test_suite_id"], [
    {
        "name": "Confirmation fails: customer is told it was not sent",
        "input": {"message": "Please email me the confirmation for booking BK-2001."},
        "metadata": {"environment": "confirmation-service-down@1"},
        "expected": {
            SEND_OUTCOME_JUDGE_ID: {      # a Code judge: Sent, Send failed, No attempt
                "judge_major_version": 1, "judge_minor_version": 0,
                "op": "eq", "expected": "Send failed",
                "rationale": "The confirmation service is down in this environment",
            },
            CUSTOMER_TOLD_JUDGE_ID: {     # an Agent judge: Told sent, Told not sent, Not mentioned
                "judge_major_version": 1, "judge_minor_version": 0,
                "op": "eq", "expected": "Told not sent",
                "rationale": "The agent must not claim the confirmation was sent",
            },
        },
    },
])
client.test_suites.publish(suite["test_suite_id"])

With MCP, pass the same metadata to add_test_cases or update_test_case.

The name is checked when a run starts, not when the case is saved. If a case names an environment without a version, or one the project doesn't have, the run doesn't start, and the error lists each such case's ID. A stored-trace run doesn't run your agent, so it doesn't use environments.

Apply the environment in your runner

When a run starts, each case has an environment: the name@version it names, or None when it names none. The run has an environments map from each name@version to its description and definition.

The runner does four things with them: it refuses a case it can't give an environment, loads the seed, answers tool calls from the rules, and plays the case under Tracer.test_case.

import os
from contextvars import ContextVar

from judgeval import Judgeval, Tracer
from judgeval.testing import NO_MATCH, canned_tool_result

ENVIRONMENT: ContextVar[dict] = ContextVar("environment", default={})


def call_tool(tool_name: str, arguments: dict):
    result = canned_tool_result(ENVIRONMENT.get(), tool_name, arguments)
    return TOOLS[tool_name](**arguments) if result is NO_MATCH else result


def definition_for(run: dict, case: dict) -> dict:
    name = case.get("environment")
    if not name:
        raise SystemExit(f"Case {case['case_id']} names no test environment")
    definition = run["environments"][name]["definition"]
    if unknown := set(definition.get("tools", {})) - set(TOOLS):
        raise SystemExit(f"{name} mocks tools the agent does not have: {unknown}")
    return definition


client = Judgeval(project_name="booking-agent")
Tracer.init(project_name="booking-agent", environment="ci")
run = client.test_runs.start(
    TEST_SUITE_ID, candidate=os.environ["GIT_SHA"], trigger="ci"
)

definitions = [definition_for(run, case) for case in run["cases"]]
for case, definition in zip(run["cases"], definitions):
    token = ENVIRONMENT.set(definition)
    try:
        load_seed(definition.get("seed", {}))
        with Tracer.test_case(run["run_id"], case["case_id"]):
            booking_agent(case["input"])
    finally:
        ENVIRONMENT.reset(token)
Tracer.force_flush()

TOOLS (the agent's tools by name), load_seed, booking_agent and TEST_SUITE_ID are your own. What each part is for:

  • call_tool is where your agent's tool dispatch looks for a canned result before it runs a tool. The runner resets the environment after each case, even one that raises, so outside a test every call runs the real tool. If your agent runs tools in worker threads, pass the definition to them explicitly.
  • canned_tool_result returns the return of the first rule that matches the call, or NO_MATCH. Compare with is, because a rule may return None. Each call returns a fresh copy, so a case that changes the result doesn't change it for later cases.
  • definition_for refuses a case that names no environment, instead of running it against real services. It also refuses a definition that mocks a tool the agent doesn't have: a misspelled tool name would mock nothing and let the real tool run. Every case is checked before any case is played. A run it stops is left unfinished: fix the case and start a new run. If your suite also has cases that need no environment, give those an empty definition here instead.
  • load_seed builds a store for this case alone, so one case's writes never reach another case.
  • Tracer.test_case tags the case's trace with the run and the case. See Connect your agent.
  • environment="ci" is the trace's deployment environment, which keeps test traces apart from production traffic. It is unrelated to the test environment.

To wait for the run and fail the job when a case fails, see Fail a CI job.

With MCP, start_test_suite_run returns the same environment on each case and the same environments map.

Verify

client.test_environments.get("confirmation-service-down", 1) returns the stored definition. After a run, open the case's trace: the send_confirmation call returns {"error": "confirmation service unavailable"}, the result the environment gave it.

Choose a judge for each check

In an environment you know what the tools returned, so most checks have an exact answer.

  • Use a Code judge where the recorded tool calls answer the question: whether a tool was called, with which arguments, and what it returned. It is exact and needs no model. See Code judges.
  • Use an Agent judge where the reply has to be read: whether the customer was told something, whether a claim is supported, or the tone.

A case can have both, as in the case above: a Code judge for what happened and an Agent judge for what the customer was told.

Give a judge outputs that report what happened, such as Sent, Send failed and No attempt, and leave what should have happened to each case's expected. The same judge then works for a case where sending is right and a case where it is wrong. Code judges can also run on live traffic, so the judge that checks a case can watch for the same failure in production.

In TypeScript

The same calls are on the client's testEnvironments, and cannedToolResult and NO_MATCH are exported from judgeval:

import { Judgeval, NO_MATCH, cannedToolResult } from "judgeval";

const client = await Judgeval.create({ projectName: "booking-agent" });

await client.testEnvironments.create({
  name: "confirmation-service-down",
  description: "Every send_confirmation call fails. Every other tool is real.",
  definition: {
    tools: {
      send_confirmation: [{ return: { error: "confirmation service unavailable" } }],
    },
  },
});
await client.testEnvironments.addVersion("confirmation-service-down", {
  definition: { /* ... */ },
});

let result = cannedToolResult(definition, toolName, args);
if (result === NO_MATCH) result = await TOOLS[toolName](args);

testRuns.start returns the same environment on each case and the same environments map, and Tracer.testCase(runId, caseId, fn) plays a case. See the TypeScript SDK reference.

Use the HTTP API

Every SDK call maps to a route under https://api.judgmentlabs.ai/v1/projects/$JUDGMENT_PROJECT_ID/test-environments, called with your API key and organization ID (see Authentication):

SDKRoute
test_environments.create(name, definition)POST /test-environments
test_environments.add_version(name, definition)POST /test-environments/{name}/versions
test_environments.list()GET /test-environments
test_environments.get(name, version)GET /test-environments/{name}/versions/{version}

POST /test-environments takes name, definition and an optional description, as in the MCP example above. POST /test-environments/{name}/versions takes definition and an optional description; the name is in the path only.

Creating an environment and adding a version need the Developer role or higher; reading needs Viewer.

Next step

Run your agent on the test suite and read each case's result.

On this page