Testing
Testing an agent should not need a key, the network or money. freyja::testing holds a scripted model that answers from a list you write, a cassette that records one real run and replays it from then on, an embedder for testing retrieval, and conformance checks for storage backends and vector stores. Each runs under any async runtime, and the examples below use tokio.
A scripted model
ScriptedModel implements Model, so an agent takes it where it would take a Client. Each call to the model returns the next response in the script, and requests() returns every request it received, in order.
use freyja::testing::ScriptedModel;
use freyja::{Agent, tool};
use serde_json::json;
use std::sync::Arc;
#[tool(description = "adds two numbers together")]
fn add(a: i64, b: i64) -> i64 {
a + b
}
#[tokio::test]
async fn the_agent_adds() {
let model = Arc::new(
ScriptedModel::new()
.tool_call("add", json!({"a": 1, "b": 2}))
.text("3"),
);
let run = Agent::new(model.clone()).tool(add).ask("add 1 and 2").await.unwrap();
assert_eq!(run.answer, "3");
assert_eq!(model.requests().len(), 2);
}
Agent::new takes the model by value, so wrap it in an Arc and clone the handle to read requests() after the run. text adds a completed answer. tool_call adds a response that asks for one call to the named tool, with an id unique within the script. The second request in the example carries the tool result, so a test can assert on what the model was shown:
let second = &model.requests()[1];
assert!(format!("{:?}", second.messages).contains("3"));
A call after the script runs out returns Error::InvalidResponse, which a test that scripted too little will see as a failed run. Streaming replays each response through the default Model::stream, so a streaming send answers the same as a plain one.
Token usage and failures
usage gives the response added last a token count, which is what a Budget or a Cost charges. error adds a call that fails, so a test can check how your code handles a rate limit or an outage without provoking a real one. The script goes on after it.
use freyja::Error;
let model = ScriptedModel::new()
.text("hi")
.usage(10, 2)
.error(Error::RateLimit {
endpoint: "scripted".into(),
retry_after: None,
body: "slow down".into(),
});
Custom responses
respond adds any response shape the other builders do not cover, such as a cut-off answer or parallel tool calls. Build it with GenerateResponse::new and set the public fields you care about. Usage::new fills total_tokens from the other two counts.
use freyja::{GenerateResponse, OutputContent, ResponseStatus, Usage};
let mut response = GenerateResponse::new(
ResponseStatus::Completed,
vec![OutputContent::Text("hi".into())],
);
response.usage = Some(Usage::new(10, 2));
let run = Agent::new(ScriptedModel::new().respond(response))
.ask("hi")
.await?;
assert_eq!(run.usage.total_tokens, 12);
This is how a test exercises a token budget, a run that ends on ResponseStatus::Incomplete, or a status the real provider rarely produces.
Testing tools, guards and hooks
A tool made with #[tool] is a plain function, so a unit test can call it directly. A test through the agent shows what the model would see, including how a failure reaches it as text.
A guard is a function from a ToolCall and a Context to a Decision. ToolCall::new builds the call, so the guard is tested with no model at all:
use freyja::{Context, Decision, ToolCall};
fn guard(call: &ToolCall, _cx: &Context) -> Decision {
if call.name == "add" && call.arguments.contains("99") {
Decision::Deny("99 is off limits".into())
} else {
Decision::Allow
}
}
#[test]
fn the_guard_refuses_ninety_nine() {
let call = ToolCall::new("c1", "add", r#"{"a":99,"b":1}"#);
assert_eq!(guard(&call, &Context::new()), Decision::Deny("99 is off limits".into()));
}
The same guard checked through a run proves the denial reaches the model as a tool result and the tool never runs:
let model = Arc::new(
ScriptedModel::new()
.tool_call("add", json!({"a": 99, "b": 1}))
.text("refused"),
);
let run = Agent::new(model.clone()).tool(add).guard(guard).ask("add").await?;
assert_eq!(run.answer, "refused");
assert!(format!("{:?}", model.requests()[1].messages).contains("99 is off limits"));
A hook is tested the same two ways. Its methods take the call and a Context, so a test calls one directly and compares the Flow, or runs it in an agent and reads Run::stop:
use freyja::{Flow, Hook, StopReason};
struct Stopper;
impl Hook for Stopper {
fn before_tool(&self, call: &ToolCall, _cx: &Context) -> Flow {
if call.name == "add" { Flow::Stop("no adding".into()) } else { Flow::Continue }
}
}
let call = ToolCall::new("c1", "add", "{}");
assert_eq!(Stopper.before_tool(&call, &Context::new()), Flow::Stop("no adding".into()));
let model = ScriptedModel::new().tool_call("add", json!({"a": 1, "b": 2})).text("x");
let run = Agent::new(model).tool(add).hook(Stopper).ask("go").await?;
assert_eq!(run.stop, StopReason::Stopped("no adding".into()));
Testing media
A test can check that a file, an image or a recording reached the model without a key. Build the same part again and look for it in the request, since parts compare by value.
use freyja::testing::ScriptedModel;
use freyja::{Agent, InputContent, Message, Role};
use std::sync::Arc;
#[tokio::test]
async fn the_pdf_reaches_the_model() {
let pdf = std::fs::read("tests/fixtures/contract.pdf").unwrap();
let model = Arc::new(ScriptedModel::new().text("30 days"));
let message = Message::new(
Role::User,
[
InputContent::file(&pdf, "application/pdf"),
InputContent::Text("What is the notice period?".into()),
],
);
let run = Agent::new(model.clone()).ask(message).await.unwrap();
assert_eq!(run.answer, "30 days");
let sent = &model.requests()[0];
assert!(sent.messages.iter().any(|m| m.content.contains(&InputContent::file(&pdf, "application/pdf"))));
}
Whether a provider takes the part is a separate question, and Client::check answers it with no request sent, so any key will do. It runs the same checks a real call runs first.
use freyja::{Client, EndpointPreset, Error, GenerateRequest};
#[test]
fn anthropic_refuses_audio_before_sending() {
let client = Client::new(EndpointPreset::Anthropic, "not-a-real-key");
let request = GenerateRequest::new().message(Message::new(
Role::User,
[InputContent::audio(b"RIFF", "audio/wav")],
));
let error = client.check(&request).unwrap_err();
assert!(matches!(error, Error::UnsupportedCapability { capability: "audio input", .. }));
}
check catches what Freyja refuses. It cannot catch a provider that accepts a part and ignores it, such as a plain text file on OpenAI, so try a new kind of input once against the real provider. See Media.
Recording a real run
A scripted model checks your code against answers you wrote. A recording checks it against answers a real model gave. Cassette replays a file when it exists and records it when it does not, so only the first run of a test pays:
use freyja::testing::Cassette;
use freyja::{Client, EndpointPreset};
let model = Cassette::new("tests/fixtures/add.jsonl", || {
Client::from_env(EndpointPreset::OpenAi)
})?;
let run = Agent::new(model).tool(add).ask("add 1 and 2").await?;
The closure makes the real model only when recording, so a replaying test needs no key. The recording is saved after every response. Commit it with the test. When the CI environment variable is set and the file is missing, Cassette::new fails instead of recording, so a forgotten recording never spends money in CI.
Each line of the file keeps the model and the tool names the call asked for. When a replayed call asks for another model or offers other tools, it fails with Error::InvalidResponse saying what changed, because the recorded answers no longer fit the code. Delete the file and run the test once to record it again. The prompts and the conversation are not compared, so changing a system prompt replays the old answers.
Recorder and ScriptedModel::replay are the two halves Cassette is made of, for recording somewhere other than a test:
use freyja::testing::{Recorder, ScriptedModel};
use std::sync::Arc;
let model = Arc::new(Recorder::new(Client::from_env(EndpointPreset::OpenAi)?));
Agent::new(model.clone()).tool(add).ask("add 1 and 2").await?;
model.save("tests/fixtures/add.jsonl")?;
let model = ScriptedModel::replay("tests/fixtures/add.jsonl")?;
The file is JSON Lines. The first line is the header {"freyja_recording":2}, and each later line holds model, tools and the response, in the order the model answered. Recordings from freyja 0.6, with the header {"freyja_recording":1}, still replay, without the check. ScriptedModel::replay fails with InvalidData, naming the line, when the header is missing or a line is not a recorded response.
A call that failed is not saved, and a recording answers a streaming caller all at once, after the whole response has arrived. Recorded responses can carry provider metadata, so read a fixture before committing it.
Testing retrieval
HashEmbedder turns text into vectors by hashing its words, so an Index runs with no embedding model:
use freyja::Index;
use freyja::testing::HashEmbedder;
let index = Index::new(HashEmbedder, "hash");
index.add(["Refunds are paid within five days", "We ship to Europe"]).await?;
let hits = index.search("when are refunds paid", 1).await?;
assert_eq!(hits[0].text, "Refunds are paid within five days");
A search finds the texts sharing the most words with the query. It knows nothing of meaning, so "car" and "automobile" do not match. Use it to test what your code does with the hits, and a cassette on the agent for the answers.
Checking a storage backend
freyja::testing::storage_conformance runs the rules a Storage documents against a backend and panics on the first one broken, naming it. Call it from the backend crate's own tests with a function that builds a new, empty backend on each call:
use freyja::testing::storage_conformance;
#[tokio::test]
async fn my_backend_conforms() {
storage_conformance(MyBackend::new).await;
}
A backend that needs a resource per instance, such as a file or a schema, builds a fresh one in the closure it passes. The rules themselves are on the extending page for Storage.
Testing a team
A Team is tested with one scripted model per member. The first member asks for the transfer_to_<name> tool, which each member gets for every other member and which takes no arguments, and the second member answers.
use freyja::{InMemoryStorage, Team};
let desk = Arc::new(ScriptedModel::new().tool_call("transfer_to_billing", json!({})));
let billing = Arc::new(ScriptedModel::new().text("refunded"));
let team = Team::new()
.agent("desk", "Greets users and routes them", Agent::new(desk.clone()))
.agent("billing", "Answers invoice questions", Agent::new(billing.clone()));
let mut chat = team.conversation("desk", InMemoryStorage::new());
let run = chat.send("charged twice").await?;
assert_eq!(run.answer, "refunded");
assert_eq!(run.agent.as_deref(), Some("billing"));
assert_eq!(desk.requests().len(), 1);
Run::agent names the member that gave the final answer, and each model's requests() shows what that member was sent, so a test can check that the second member received the whole history and not the first member's system prompt. A later send on the same conversation goes to the member last handed to, so a script for it needs a response for that member only.
See also
- Building an agent for the loop these tests run
- Agents and Conversations for what a scripted run exercises
- Memory, Hooks and Human approval for behaviour worth a scripted test
- Observability for token counts a scripted response can supply
- Model, Tool and Hook for testing your own implementations
- Structured output for typed answers, which a scripted model can supply as JSON text
- Messages and content for the types a test builds
- Storage for the backends
storage_conformancechecks