testkit

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package testkit holds the fakes and helpers every Nova test uses: a fake clock, a scripted provider, a fault-injecting SSE server, filesystem and golden helpers, and a goroutine leak check. It is tested as strictly as product code, because everything else depends on it.

Index

Constants

View Source
const SessionHeader = "x-opencode-session"

SessionHeader is the conversation-id header OpenCode Go requires on every inference request. The double refuses a streaming request without it, using the live MissingSessionID shape, so a test pins the requirement itself.

Variables

This section is empty.

Functions

func Golden

func Golden(t testing.TB, name, got string)

Golden compares got to testdata/<name>.golden, failing the test on a mismatch. With -update it rewrites the file and passes.

func Mkfifo

func Mkfifo(t testing.TB, path string)

Mkfifo creates a named pipe at path, or skips the test where the platform or the filesystem has none. Tests use it for the file that blocks forever when a reader opens it with no writer.

func NoLeaks

func NoLeaks(t testing.TB)

NoLeaks snapshots the running goroutines and, in a cleanup, fails the test if any new ones are still running after leakTimeout.

func Symlink(t testing.TB, root, name, target string)

Symlink creates a symlink at root/name pointing at target.

func TempTree

func TempTree(t testing.TB, files map[string]string) string

TempTree writes files (creating parent directories) under the test's temp directory and returns that root.

func WriteBinary

func WriteBinary(t testing.TB, root, name string, size int)

WriteBinary writes a file of size bytes filled with NULs.

Types

type Call

type Call struct {
	ID, Name, Args string
	SplitArgs      []string
}

Call scripts one tool call. When SplitArgs is set, Args are delivered as those fragments (the in-process provider still emits one assembled event).

type Clock

type Clock interface {
	Now() time.Time
	Sleep(ctx context.Context, d time.Duration) error
	After(d time.Duration) <-chan time.Time
}

Clock is the time seam. Production code takes a Clock so tests can drive time with a FakeClock instead of sleeping on real time.

func RealClock

func RealClock() Clock

RealClock returns a Clock backed by the wall clock.

type Decider

type Decider struct {
	// contains filtered or unexported fields
}

Decider is a scripted in-process decide.Decider. Each Decide call pops the next turn and records the request.

func NewDecider

func NewDecider(clock Clock, turns ...DecisionTurn) *Decider

NewDecider returns a decider that plays the given turns in order. A nil clock means the real clock.

func (*Decider) Decide

func (d *Decider) Decide(ctx context.Context, req decide.Request) (*decide.Response, error)

Decide plays the next turn. It honours ctx for Delay and Hang, and returns an error once the script is exhausted.

func (*Decider) Remaining

func (d *Decider) Remaining() int

Remaining reports how many turns are left.

func (*Decider) Requests

func (d *Decider) Requests() []decide.Request

Requests returns the recorded requests, deep-copied so callers cannot mutate what the decider saw.

type DecisionServer

type DecisionServer struct {
	URL string
	// contains filtered or unexported fields
}

DecisionServer is a local HTTP server that answers the decision-model endpoints: POST /api/alpha/decisions and POST {base}/systemone. It records each request and plays the scripted turns in order.

func NewDecisionServer

func NewDecisionServer(t testing.TB, turns ...DecisionServerTurn) *DecisionServer

NewDecisionServer starts a server that plays the turns in order. It is closed when the test's cleanup runs.

func (*DecisionServer) Requests

func (s *DecisionServer) Requests() []RecordedRequest

Requests returns the recorded requests, copied so callers cannot mutate them.

type DecisionServerTurn

type DecisionServerTurn struct {
	// Status is the HTTP status. Zero means 200.
	Status int
	// Body is the raw response body. Empty means "{}".
	Body string
	// Headers are added to the response, for a Retry-After or a content type.
	Headers map[string]string
	// Hang blocks until the request is cancelled, for a timeout test.
	Hang bool
}

DecisionServerTurn scripts one HTTP answer from the Decisions API or the System One surface.

type DecisionTurn

type DecisionTurn struct {
	Answers map[string]decide.Answer
	Usage   provider.Usage
	Model   string
	Err     error
	Delay   time.Duration // slept via the clock before answering
	Hang    bool          // block until ctx is cancelled
}

DecisionTurn scripts one decision call.

type EmbeddingServer added in v0.3.0

type EmbeddingServer struct {
	URL string
	// contains filtered or unexported fields
}

EmbeddingServer is a local HTTP server that answers the embeddings endpoints: POST {base}/embeddings and POST /api/embed. It records each request and plays the scripted turns in order.

func NewEmbeddingServer added in v0.3.0

func NewEmbeddingServer(t testing.TB, turns ...EmbeddingServerTurn) *EmbeddingServer

NewEmbeddingServer starts a server that plays the turns in order. It is closed when the test's cleanup runs.

func (*EmbeddingServer) Requests added in v0.3.0

func (s *EmbeddingServer) Requests() []RecordedRequest

Requests returns the recorded requests, copied so callers cannot mutate them.

type EmbeddingServerTurn added in v0.3.0

type EmbeddingServerTurn struct {
	// Status is the HTTP status. Zero means 200.
	Status int
	// Body is the raw response body. Empty means "{}".
	Body string
	// Headers are added to the response, for a Retry-After or a content type.
	Headers map[string]string
	// Hang blocks until the request is cancelled, for a cancellation test.
	Hang bool
}

EmbeddingServerTurn scripts one HTTP answer from an embeddings endpoint.

type FakeClock

type FakeClock struct {
	// contains filtered or unexported fields
}

FakeClock is a clock driven entirely by Advance. It never reads real time.

func NewFakeClock

func NewFakeClock(start time.Time) *FakeClock

NewFakeClock returns a clock stopped at start.

func (*FakeClock) Advance

func (c *FakeClock) Advance(d time.Duration)

Advance moves time forward and fires every timer due at or before the new time, in deadline order, then returns.

func (*FakeClock) After

func (c *FakeClock) After(d time.Duration) <-chan time.Time

After registers a timer due d after the current fake time.

func (*FakeClock) BlockUntil

func (c *FakeClock) BlockUntil(t testing.TB, n int)

BlockUntil waits until n timers are pending, so a test can avoid racing a goroutine that is about to call Sleep.

func (*FakeClock) Now

func (c *FakeClock) Now() time.Time

Now returns the fake time, never the real one.

func (*FakeClock) Sleep

func (c *FakeClock) Sleep(ctx context.Context, d time.Duration) error

Sleep waits for d of fake time or for ctx to be cancelled. A cancelled sleep gives its timer back, so BlockUntil counts live sleepers only.

type Fault

type Fault int

Fault selects how the SSE server misbehaves for one turn.

const (
	// FaultNone serves the turn normally.
	FaultNone Fault = iota
	// FaultCutMidEvent closes the connection in the middle of an SSE event.
	FaultCutMidEvent
	// FaultNoDone ends the stream cleanly without a [DONE] sentinel.
	FaultNoDone
	// FaultMalformedJSON sends a data line that is not JSON.
	FaultMalformedJSON
	// FaultStall sends headers, then nothing until the client gives up.
	FaultStall
	// Fault401 responds 401 with a JSON error body.
	Fault401
	// Fault429 responds 429 with Retry-After: 1.
	Fault429
	// Fault500 responds 500 with a JSON error body.
	Fault500
	// FaultHTML responds 502 with an HTML body.
	FaultHTML
	// FaultHugeChunk sends one data line of at least 4 MiB.
	FaultHugeChunk
)

type GoConfig added in v0.3.4

type GoConfig struct {
	// RequireSession refuses a streaming request without x-opencode-session.
	// The refusal happens before a scripted turn is consumed, because a
	// refused request never reaches the model.
	RequireSession bool
	// StatusBody, when non-nil, is served verbatim at GET /api/go/status.
	StatusBody []byte
}

GoConfig configures the Go-dialect behaviors of a test Server: the session requirement, the allowance usage block, and the status endpoint. A plain NewServer has none of them, so OpenRouter-shaped tests are unaffected.

type Provider

type Provider struct {
	// contains filtered or unexported fields
}

Provider is a scripted in-process provider. Each Stream call pops the next turn and records the request.

func NewProvider

func NewProvider(clock Clock, turns ...Turn) *Provider

NewProvider returns a provider that plays the given turns in order.

func (*Provider) Name

func (p *Provider) Name() string

Name is the provider id used in tests.

func (*Provider) Remaining

func (p *Provider) Remaining() int

Remaining reports how many turns are left.

func (*Provider) Requests

func (p *Provider) Requests() []provider.Request

Requests returns the recorded requests, deep-copied so callers cannot mutate what the provider saw.

func (*Provider) Stream

func (p *Provider) Stream(ctx context.Context, req provider.Request, onEvent func(provider.StreamEvent)) (*provider.Response, error)

Stream plays the next turn: reasoning, text, tool calls, then usage. It honours ctx for Delay and Hang, and returns an error once the script is exhausted.

type RecordedRequest

type RecordedRequest struct {
	Method, Path string
	// Query is the raw query string, without the "?", for a server that needs
	// to assert a filter such as output_modalities=speech.
	Query  string
	Header http.Header
	Body   []byte
}

RecordedRequest is what the server saw.

type Server

type Server struct {
	URL string
	// contains filtered or unexported fields
}

Server is a local HTTP server that speaks OpenAI chat-completions SSE.

func NewGoServer added in v0.3.4

func NewGoServer(t testing.TB, cfg GoConfig, turns ...ServerTurn) *Server

NewGoServer starts a Server with the Go-dialect behaviors in cfg. It is closed when the test's cleanup runs.

func NewServer

func NewServer(t testing.TB, turns ...ServerTurn) *Server

NewServer starts a server that plays the turns in order. It is closed when the test's cleanup runs.

func (*Server) Requests

func (s *Server) Requests() []RecordedRequest

Requests returns the recorded requests, copied so callers cannot mutate them.

type ServerTurn

type ServerTurn struct {
	Turn
	Fault Fault
	// Raw, when non-nil, replaces the scripted turn: each element is written
	// verbatim to an SSE response body, in order, and flushed. An empty
	// non-nil slice therefore produces a 200 response with no body. Raw
	// bypasses every fault except none; it exists so tests can script wire
	// shapes the high-level Turn cannot express (comments, CRLF, missing
	// choices, late tool-call ids, usage detail objects).
	Raw []string
}

ServerTurn is one scripted HTTP turn plus the fault to inject.

type Turn

type Turn struct {
	Text       string
	TextChunks []string // when set, used instead of Text
	Reasoning  string
	ToolCalls  []Call
	Usage      *provider.Usage
	Finish     string        // default: "tool_calls" if ToolCalls else "stop"
	Delay      time.Duration // slept via the clock before the first event
	Err        error         // returned after ErrAfter events
	ErrAfter   int
	Hang       bool // block until ctx is cancelled
}

Turn scripts one provider response.

type VoiceServer added in v0.4.0

type VoiceServer struct {
	URL string
	// contains filtered or unexported fields
}

VoiceServer is a local HTTP server that answers the voice surfaces: POST /audio/speech, POST /audio/transcriptions, GET /models and GET /generation. It records each request and plays the scripted turns in order across all of them, so a speak with a cost lookup scripts two turns.

func NewVoiceServer added in v0.4.0

func NewVoiceServer(t testing.TB, turns ...VoiceServerTurn) *VoiceServer

NewVoiceServer starts a server that plays the turns in order. It is closed when the test's cleanup runs.

func (*VoiceServer) Requests added in v0.4.0

func (s *VoiceServer) Requests() []RecordedRequest

Requests returns the recorded requests, copied so callers cannot mutate them.

type VoiceServerTurn added in v0.4.0

type VoiceServerTurn struct {
	// Status is the HTTP status. Zero means 200.
	Status int
	// Body is a JSON response body. Empty means "{}".
	Body string
	// Audio, when non-nil, is written as the raw response body, for a speech
	// endpoint that answers with bytes rather than JSON.
	Audio []byte
	// ContentType is the response Content-Type. It defaults to audio/mpeg for
	// an Audio turn and application/json otherwise.
	ContentType string
	// Headers are added to the response, for a generation id or a Retry-After.
	Headers map[string]string
	// Hang blocks until the request is cancelled, for a cancellation test.
	Hang bool
}

VoiceServerTurn scripts one HTTP answer from a voice endpoint.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL