Test an agent with a scripted model
wefttest.Script returns a scripted model: a weft.Model that plays the turns you write, one per model call, and records every request it receives. Build your real agent over it, run it, and assert on the result and on the requests. Nothing reaches the network, no key is needed, and the same script gives the same run every time.
From testing/scripted_test.go, the support agent with its real lookup_order tool:
model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{ Name: "lookup_order", Args: wefttest.Args(support.LookupInput{OrderID: "1234"}), }), wefttest.Say("Order 1234 shipped yesterday."),)res, err := support.New(model).Generate(context.Background(), weft.Prompt("Where is order 1234?"))if err != nil { t.Fatal(err)}if got, want := res.Text(), "Order 1234 shipped yesterday."; got != want { t.Errorf("answer = %q, want %q", got, want)}// The tool really ran: its result is in the transcript.tr := res.Messages[2].Content[0].(weft.ToolResultPart)if tr.Content != "order 1234 shipped yesterday" || tr.IsError { t.Errorf("tool result = %+v", tr)}The first turn asks for a tool call, the loop runs lookup_order, and the second turn answers. The tool’s result is real, so the test checks your tool and your loop configuration, not the model.
In reach order
Section titled “In reach order”Write the cheapest test that answers your question. The README’s order (README.md Testing: Script, Golden, Record and Replay), extended with Studio and conformance:
| Question | Test | Page |
|---|---|---|
| Does my agent do the right thing when the model says X? | wefttest.Script | this page |
| Did the output change? | wefttest.Golden | Golden files |
| What does my agent do with what a real model said? | wefttest.Record once, wefttest.Replay in CI | Record and replay |
| Does this run from Studio still pass? | Studio’s save as test | Turn a Studio run into a test |
| Does my adapter speak the provider’s wire format? | wefttest/conformance | Conformance |
Script a dialogue
Section titled “Script a dialogue”A script is a list of wefttest.Turn values. Each model call plays the next one:
| Builder | The model call… | Usage reported |
|---|---|---|
Say(text) | streams one text delta, then stops (stop) | 10 in / 5 out |
ToolCalls(calls...) | requests the tool calls, then stops (tool_calls) | 10 in / 5 out |
Think(text, then) | streams unsigned reasoning, then plays then | then’s |
MaxTokens(text) | streams text, then finishes with max_tokens | 10 in / 5 out |
Fail(err) | errors with err before any event | none |
SayThenFail(text, err) | streams text, then errors with err | none |
Raw(events...) | plays exactly these model events, appending nothing | what you script |
A wefttest.Call names one tool call. Name is the tool. Args is raw JSON, {} when empty. ID is optional: within a turn the calls get call_1, call_2, … in order. wefttest.Args(v) marshals a typed value into Args, so the scripted call and the tool’s input struct cannot drift apart; a value that does not marshal panics at the call site.
The fixed 10 / 5 usage makes accounting assertable. Two scripted steps report 20 input and 10 output tokens:
// Every scripted step reports 10 input and 5 output tokens.if res.Usage.InputTokens != 20 || res.Usage.OutputTokens != 10 { t.Errorf("usage = %+v, want 20 in / 10 out over two steps", res.Usage)}Turn.WithUsage(u) replaces a turn’s usage, which is how you drive a weft.UsageLimit without arithmetic on the defaults. A turn with no finish (Fail, a Raw stream without one) comes back unchanged.
Script failures
Section titled “Script failures”The failure builders pin how the agent behaves when the model misbehaves. From testing/scripted_test.go:
// Fail: the model call errors before any output. The run fails with a// *weft.RunError that wraps the cause.down := errors.New("provider unavailable")_, err := support.New(wefttest.Script(wefttest.Fail(down))).Generate(ctx, prompt)var re *weft.RunErrorif !errors.As(err, &re) || !errors.Is(err, down) { t.Errorf("Fail: err = %v", err)}
// SayThenFail: text, then the stream errors; the partial turn is discarded._, err = support.New(wefttest.Script(wefttest.SayThenFail("Order 12", down))).Generate(ctx, prompt)if !errors.Is(err, down) { t.Errorf("SayThenFail: err = %v", err)}
// MaxTokens: a truncated reply is a result, not an error.res, err := support.New(wefttest.Script(wefttest.MaxTokens("Order 1234 sh"))).Generate(ctx, prompt)if err != nil || res.StopReason != weft.StopMaxTokens { t.Errorf("MaxTokens: stop = %q, err = %v", res.StopReason, err)}
// Raw: exactly these events. No ModelFinish breaks the Model contract._, err = support.New(wefttest.Script(wefttest.Raw(weft.ModelTextDelta{Text: "hi"}))).Generate(ctx, prompt)if !errors.Is(err, weft.ErrModelContract) { t.Errorf("Raw: err = %v, want ErrModelContract", err)}
// WithUsage: replace a turn's usage to drive a budget.big := wefttest.ToolCalls(wefttest.Call{Name: "lookup_order", Args: `{"order_id":"1234"}`}). WithUsage(weft.Usage{InputTokens: 900, OutputTokens: 40})_, err = support.New(wefttest.Script(big, wefttest.Say("unreached")), weft.UsageLimit(weft.Usage{OutputTokens: 30})).Generate(ctx, prompt)if !errors.Is(err, weft.ErrUsageLimit) { t.Errorf("WithUsage: err = %v, want ErrUsageLimit", err)}FailandSayThenFailfail the run with a*weft.RunErrorthat wraps your error. AfterSayThenFailthe loop discards the partial turn; it is also the shapemw.Retrysees as a failure after output.MaxTokensis not an error: the run recordsStopMaxTokensonRunResult.StopReason.Rawis the way to break the Model stream contract on purpose. A stream with noModelFinish, two of them, or an event after the finish fails the run wrappingweft.ErrModelContract. It is also how you script a signed reasoning block, whichThinkcannot express.
A scripted model has no idle timer and no HTTP status. To test how your code handles a stalled stream or a provider error, script the error the adapter would yield: Fail(fmt.Errorf("%w after 60s", weft.ErrStreamIdle)), as the conformance harness does. Every scripted turn honours the Model contract on cancellation: when ctx is done, the stream yields ctx.Err() before anything scripted.
Think prefixes a turn with reasoning, which lands as a weft.ReasoningPart first in the assistant message:
// Think prefixes a turn with unsigned reasoning.res, err = support.New(wefttest.Script( wefttest.Think("the user wants a status", wefttest.Say("Order 1234 shipped yesterday.")),)).Generate(ctx, prompt)if err != nil { t.Fatal(err)}if _, ok := res.Messages[1].Content[0].(weft.ReasoningPart); !ok { t.Errorf("first part = %T, want ReasoningPart", res.Messages[1].Content[0])}A script is consumed across runs
Section titled “A script is consumed across runs”One *wefttest.Model keeps its position. Run the agent twice over the same model and the second run plays the next turn. A call past the last turn fails the run with wefttest.ErrScriptExhausted, and that call is still recorded:
model := wefttest.Script( wefttest.Say("Hello."), wefttest.Say("Order 5678 is still pending."),)agt := support.New(model)first, _ := agt.Generate(context.Background(), weft.Prompt("Hi"))second, _ := agt.Generate(context.Background(), weft.Messages(first.Messages...), weft.Prompt("And order 5678?"))if second.Text() != "Order 5678 is still pending." { t.Errorf("second run = %q: it plays the script's next turn", second.Text())}// A third call has no turn left._, err := agt.Generate(context.Background(), weft.Prompt("Anything else?"))if !errors.Is(err, wefttest.ErrScriptExhausted) { t.Errorf("err = %v, want ErrScriptExhausted", err)}if got := len(model.Requests()); got != 3 { // the exhausted call is recorded too t.Errorf("%d requests, want 3", got)}The run error’s text says what happened: wefttest: model script exhausted (agent made more model calls than the script provides). It is almost always a test bug, so fail on it. Build a new script per test unless the test is about a conversation.
The package examples show each builder alone: ExampleArgs, ExampleRaw, ExampleSayThenFail, ExampleTurn_WithUsage and ExampleModel_LastRequest.
Inspect requests
Section titled “Inspect requests”The model records every weft.ModelRequest the agent sent. Assert on the system prompt, the transcript and the tool catalog the model saw:
reqs := model.Requests() // every request, in orderif len(reqs) != 2 { t.Fatalf("%d model calls, want 2", len(reqs))}first := wefttest.Request{ModelRequest: reqs[0]}if first.System != support.Instructions { t.Errorf("system prompt = %q", first.System)}if first.LastText() != "Where is order 1234?" || !first.HasTool("lookup_order") { t.Errorf("first request: text %q, tools %v", first.LastText(), first.ToolNames())}last := model.LastRequest() // the follow-up after the tool stepif last.LastText() != "" { // its last message is the tool result, not text t.Errorf("LastText = %q, want empty after a tool step", last.LastText())}if got := len(last.Messages); got != 3 { // user, assistant call, tool result t.Errorf("last request carries %d messages, want 3", got)}| Method | Returns |
|---|---|
Model.Requests() | Every request in order, including a call that exhausted the script. Use it to count attempts under mw.Retry or mw.Fallback |
Model.LastRequest() | The most recent request as a wefttest.Request, or the zero Request before any call, whose matchers report false and empty |
Request.HasTool(name) | Whether the request advertised that tool |
Request.ToolNames() | The advertised tool names, sorted |
Request.LastText() | The text of the last text part of the last message: the prompt on the first call, "" after a tool step |
Model.Info() | {Provider: "wefttest", Name: "script"}, so RunStart.Model and manifests carry a value in tests |
Request embeds the request (Request.ModelRequest), so every field stays reachable: req.System, req.Messages, req.Tools. A script records ToolChoice and Params for assertion and honours neither. Model.Stream is the weft.Model method the loop calls; a test can call it directly, as the package examples do.
A subagent’s events reach the parent’s stream wrapped in weft.Nested. wefttest.Flatten unwraps them, recursively, so you assert on the child’s events as the child emitted them:
researcher := weft.New(wefttest.Script(wefttest.Say("The carrier lost it.")), weft.Name("research"))lead := support.New(wefttest.Script( wefttest.ToolCalls(wefttest.Call{Name: "research", Args: `{"prompt":"why is 1234 late?"}`}), wefttest.Say("The carrier lost order 1234."),), weft.Subagent("research", "Research a question.", researcher))
var evs []weft.Eventfor ev, err := range lead.Stream(context.Background(), weft.Prompt("Why is order 1234 late?")).Events() { if err != nil { t.Fatal(err) } evs = append(evs, ev)}// Flatten unwraps every weft.Nested, so the child's TextDelta is visible.var texts []stringfor _, ev := range wefttest.Flatten(evs) { if d, ok := ev.(weft.TextDelta); ok { texts = append(texts, d.Text) }}if !slices.Equal(texts, []string{"The carrier lost it.", "The carrier lost order 1234."}) { t.Errorf("texts = %q", texts)}Check that middleware forwards Info
Section titled “Check that middleware forwards Info”Model middleware should forward the inner model’s identity (weft.ModelMiddleware’s convention). wefttest.ConformInfo wraps a scripted model in yours and returns an error when the Info changed; wefttest.ConformInfoT fails the test instead:
// mw.Retry forwards the inner model's Info: it conforms.wefttest.ConformInfoT(t, mw.Retry())
// A middleware that wraps the model in a bare struct hides it.hides := func(next weft.Model) weft.Model { return struct{ weft.Model }{next} }if err := wefttest.ConformInfo(hides); err == nil { t.Error("ConformInfo accepted a middleware that drops Info")}The error reads middleware core.ModelMiddleware dropped Info: got {Provider: Name:}, want {Provider:wefttest Name:script}. The type it prints is always core.ModelMiddleware, so name the middleware in your test’s own message.
Never reach the network
Section titled “Never reach the network”WEFT_MODEL_REQUESTS=deny is the kill switch. Every first-party adapter checks weft.ModelRequestsAllowed at the top of Stream and, when it is false, fails with weft.ErrModelRequestsDenied before any I/O. The function reads the environment on every call, so t.Setenv toggles it per test:
t.Setenv("WEFT_MODEL_REQUESTS", "deny")if weft.ModelRequestsAllowed() { t.Fatal("the switch reads the environment on every call")}prompt := weft.Prompt("Where is order 1234?")
// A client the adapter builds from credentials makes no request.srv := conformance.NoRequestServer(t) // fails the test if anything arrivesbuilt := openai.Model("gpt-5", openai.BaseURL(srv.URL), openai.APIKey("sk-test"))_, err := support.New(built).Generate(context.Background(), prompt)if !errors.Is(err, weft.ErrModelRequestsDenied) { t.Errorf("built client: err = %v, want ErrModelRequestsDenied", err)}
// A client injected with Client(c) is a test double: it stays reachable.stub := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.Header().Set("Content-Type", "text/event-stream") _, _ = w.Write([]byte(sse))}))defer stub.Close()c := openaisdk.NewClient(option.WithBaseURL(stub.URL), option.WithAPIKey("test"))res, err := support.New(openai.Model("gpt-5", openai.Client(&c))).Generate(context.Background(), prompt)if err != nil || res.Text() != "Order 1234 shipped yesterday." { t.Errorf("injected client: %q, %v", res.Text(), err)}
// wefttest models ignore the switch.res, err = support.New(wefttest.Script(wefttest.Say("Offline."))).Generate(context.Background(), prompt)if err != nil || res.Text() != "Offline." { t.Errorf("scripted: %q, %v", res.Text(), err)}Three rules decide what the switch blocks:
- A client the adapter builds from credentials is denied.
openai.Model("gpt-5", openai.APIKey(…))yieldsweft: model requests denied by WEFT_MODEL_REQUESTS;conformance.NoRequestServerproves no request left. - A client you inject with the adapter’s
Client(c)option is not. It is a test double by construction, so a test pointed at anhttptestserver keeps working under deny. wefttestmodels ignore the switch.Script,ReplayandRecordmake no request of their own;Record’s inner model checks it.
Run your whole suite under WEFT_MODEL_REQUESTS=deny go test ./... and a test that would call a provider fails loudly instead. weft’s own suites run that way workspace-wide (make offline), and this docs module’s tests pass under it.
Complete example
Section titled “Complete example”testing/main.go runs the support agent over a script and prints the transcript and the requests the model saw:
// Command testing runs the support agent against a scripted model and// prints what the agent did and what it asked the model: the Testing// pages' complete example. Its tests (scripted_test.go, replay_test.go,// conformance_test.go, support/) are the pages' regions.package main
import ( "context" "fmt" "io" "os" "strings"
"github.com/weftgo/weft" "github.com/weftgo/weft/wefttest" "weftgo.dev/docs/examples/testing/support")
func main() { if err := run(context.Background(), os.Stdout); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) }}
func run(ctx context.Context, w io.Writer) error { model := wefttest.Script( wefttest.ToolCalls(wefttest.Call{ Name: "lookup_order", Args: wefttest.Args(support.LookupInput{OrderID: "1234"}), }), wefttest.Say("Order 1234 shipped yesterday."), ) res, err := support.New(model).Generate(ctx, weft.Prompt("Where is order 1234?")) if err != nil { return err }
fmt.Fprintf(w, "answer: %s\n", res.Text()) fmt.Fprintf(w, "steps: %d, usage: %d in / %d out\n", len(res.Steps), res.Usage.InputTokens, res.Usage.OutputTokens) for _, m := range res.Messages { fmt.Fprintf(w, " %-9s %s\n", m.Role, describe(m)) } for i, req := range model.Requests() { fmt.Fprintf(w, "request %d: %d messages, tools %v\n", i, len(req.Messages), wefttest.Request{ModelRequest: req}.ToolNames()) } return nil}
// describe renders one message on one line.func describe(m weft.Message) string { var parts []string for _, p := range m.Content { switch p := p.(type) { case weft.TextPart: parts = append(parts, fmt.Sprintf("%q", p.Text)) case weft.ToolCallPart: parts = append(parts, fmt.Sprintf("call %s(%s) id=%s", p.Name, p.Args, p.ID)) case weft.ToolResultPart: parts = append(parts, fmt.Sprintf("result %q id=%s", p.Content, p.CallID)) } } return strings.Join(parts, " ")}The agent is testing/support/support.go: one lookup_order tool and a system prompt.
View on GitHub · run it from docs-site/examples:
go run ./testingWEFT_MODEL_REQUESTS=deny go test ./testing/...answer: Order 1234 shipped yesterday.steps: 2, usage: 20 in / 10 out user "Where is order 1234?" assistant call lookup_order({"order_id":"1234"}) id=call_1 tool result "order 1234 shipped yesterday" id=call_1 assistant "Order 1234 shipped yesterday."request 0: 1 messages, tools [lookup_order]request 1: 3 messages, tools [lookup_order]Best practices & gotchas
Section titled “Best practices & gotchas”- Fail on
ErrScriptExhausted. An agent that makes more model calls than you scripted is a bug in the agent or the test; the exhausted call is inRequests()so you can see what it asked. (Source:weft/core/wefttest/model.go:18-21,207-216) - Assert
len(Requests()) > 0beforeLastRequest(). Before any call it returns the zeroRequest, whose matchers report false and empty, so a test that skips the check passes for the wrong reason. (Source:weft/core/wefttest/model.go:250-261,TestLastRequestZero) LastText()is""after a tool step. It reads the last message, which is the tool result on a follow-up call; readMessagesfor anything else. (Source: ADR 0017 C3,weft/core/wefttest/model.go:233-252)- Use
wefttest.Argsfor typed arguments. A struct literal stays in step with the tool’s input type; hand-written JSON does not. (Source: ADR 0017 T9) - A script does not enforce
ToolChoiceorParams. It records them; a test that needs the model to obey a forced choice scripts the call it would make. (Source: ADR 0017, the 2026-09-22 amendment) - Set
WEFT_MODEL_REQUESTS=denyin CI. It turns an accidental live call into a failing test, and leaveswefttestmodels and injected clients working. (Source:weft/AGENTS.md:646-654,weft/Makefile:102-107)
See also
Section titled “See also”- Record a real conversation once, replay it forever
- What is a Model?
- Wrap the model and the tools with middleware
- Steer a running turn:
wefttest.NewSteers
Symbols used: wefttest.Script · wefttest.Model · wefttest.Turn · wefttest.Say · wefttest.ToolCalls · wefttest.Call · wefttest.Args · wefttest.Think · wefttest.MaxTokens · wefttest.Fail · wefttest.SayThenFail · wefttest.Raw · Turn.WithUsage · wefttest.ErrScriptExhausted · wefttest.Request · Model.Requests · Model.LastRequest · Model.Info · Model.Stream · Request.HasTool · Request.ToolNames · Request.LastText · wefttest.Flatten · wefttest.ConformInfo · wefttest.ConformInfoT · weft.ModelRequestsAllowed · weft.ErrModelRequestsDenied · weft.ErrModelContract · weft.ErrUsageLimit · weft.UsageLimit · weft.RunError · weft.Nested · weft.ModelRequest · weft.ModelMiddleware · mw.Retry