apitest

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: MIT Imports: 23 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 apitest runs a real api.Server for tests in another module (LOOM-270, docs/design/tui-client-design.md "How it pins and tests against the server's API"). A client such as loomux/tui requires this module at a release tag, imports apitest from its _test.go files only, and drives the server over HTTP: the same handlers, auth, JSON and event stream a deployed server answers with, so a field or status the client gets wrong fails its own tests.

srv := apitest.New(t)
token := srv.Login()
task := srv.SeedTask(apitest.Task{ConversationID: "conv-1", Status: registry.TaskStatusAwaitingInput})
// ... the client under test talks to srv.URL with token ...

What is real: api.Server, a SQLite store in a temporary directory (every migration applied), the dispatch-job service, and the orchestrator behind takeover, heartbeat and release, and its hold sweeper, run when a test calls SweepHolds rather than on a timer. What is not: the router and its model (Dispatcher answers each dispatch itself), and the targets (Executor is an in-memory tmux; nothing is run anywhere). The plugin, credential, SSH-key, router-settings, web-bundle and health endpoints aren't configured and answer as an unconfigured server does; pass api options through WithAPIOptions to add any.

Everything is torn down by the test's cleanup, including streams left open and dispatches left blocked. Servers are independent of one another, so tests that each call New may run in parallel. The package is for tests: it isn't linked into loomuxd.

Index

Constants

View Source
const DefaultAgentType = "claude-code"

DefaultAgentType is the agent type of a seeded task that names none.

View Source
const DefaultPassword = "apitest-password"

DefaultPassword is the password a Server accepts unless WithPassword says otherwise.

View Source
const DefaultReply = "ok"

DefaultReply is what a dispatch answers until Handle says otherwise.

View Source
const TmuxSocket = "loomux-apitest"

TmuxSocket is the tmux socket name the server's attach-info names.

Variables

This section is empty.

Functions

func TokenHash added in v0.3.151

func TokenHash(token string) string

TokenHash is the hash the server stores for a session token, and the token_hash POST /api/v1/sessions takes: hex(sha256(token)).

Types

type Dispatch

type Dispatch struct {
	// ID is the dispatch's id, the dispatch_id the client was answered
	// with.
	ID             string
	ConversationID string
	Message        string
	WorkspaceHint  string
	// ConfirmationID names the offer the message answers, if any.
	ConfirmationID string
}

Dispatch is one message a client submitted, as the Dispatcher's handler sees it.

type Dispatcher

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

Dispatcher stands in for the router. Each POST /api/v1/dispatch runs as a real dispatch job (queued, running, then succeeded or failed, with idempotency keys, one job per conversation and cancellation as in production); what the job does is the handler's. Until Handle is called, every dispatch succeeds with DefaultReply.

A successful reply is also logged to the conversation as an assistant message, as the router does, so GET /conversations/{id} shows it and the stream announces it.

func (*Dispatcher) Block

func (d *Dispatcher) Block() (release func())

Block makes every later dispatch stay running until release is called (it then succeeds with DefaultReply) or the dispatch is cancelled (it then fails with the cancellation). It is how a test holds a conversation busy. Calling release more than once is harmless.

func (*Dispatcher) Dispatches

func (d *Dispatcher) Dispatches() []Dispatch

Dispatches returns every dispatch that started running so far, oldest first.

func (*Dispatcher) Fail

func (d *Dispatcher) Fail(err error)

Fail makes every later dispatch fail with err: the job ends failed, its error the client's to show.

func (*Dispatcher) Handle

func (d *Dispatcher) Handle(h Handler)

Handle sets how every later dispatch is answered; nil restores DefaultReply.

func (*Dispatcher) Reply

func (d *Dispatcher) Reply(text string)

Reply makes every later dispatch succeed with text.

type Executor

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

Executor is an in-memory targets.TargetExecutor: the one "machine" every target of a test server resolves to. It keeps sessions and what was sent to them, and runs nothing. A seeded task gets a session here, so what the server does to a task's pane can be read back.

func (*Executor) CapturePane

func (e *Executor) CapturePane(_ context.Context, target string) (string, error)

CapturePane implements targets.TargetExecutor.

func (*Executor) Close

func (e *Executor) Close() error

Close implements targets.TargetExecutor.

func (*Executor) Commands

func (e *Executor) Commands() []string

Commands returns every command RunOnce was given, in order.

func (*Executor) DetachClients added in v0.3.154

func (e *Executor) DetachClients(_ context.Context, session string) error

DetachClients implements targets.TargetExecutor: it counts in the session's Detaches. No such session is nothing to do, as on tmux.

func (*Executor) FileExists

func (e *Executor) FileExists(_ context.Context, path string) (bool, error)

FileExists implements targets.TargetExecutor.

func (*Executor) HasSession

func (e *Executor) HasSession(_ context.Context, session string) (bool, error)

HasSession implements targets.TargetExecutor.

func (*Executor) KillSession

func (e *Executor) KillSession(_ context.Context, session string) error

KillSession implements targets.TargetExecutor.

func (*Executor) NewSession

func (e *Executor) NewSession(_ context.Context, session, dir, command string) error

NewSession implements targets.TargetExecutor.

func (*Executor) PaneExited

func (e *Executor) PaneExited(context.Context, string) (*targets.PaneExit, error)

PaneExited implements targets.TargetExecutor: a session's process never exits by itself here.

func (*Executor) PasteText

func (e *Executor) PasteText(_ context.Context, target, text string, _ bool) error

PasteText implements targets.TargetExecutor.

func (*Executor) RemoveFile

func (e *Executor) RemoveFile(_ context.Context, path string) error

RemoveFile implements targets.TargetExecutor.

func (*Executor) RunOnce

func (e *Executor) RunOnce(_ context.Context, command string) (string, error)

RunOnce implements targets.TargetExecutor: the command is recorded (see Commands), not run, and its output is empty.

func (*Executor) SendKey

func (e *Executor) SendKey(_ context.Context, target, key string) error

SendKey implements targets.TargetExecutor.

func (*Executor) SendKeys

func (e *Executor) SendKeys(_ context.Context, target, keys string, _ bool) error

SendKeys implements targets.TargetExecutor.

func (*Executor) Session

func (e *Executor) Session(name string) *Session

Session returns a copy of the named session, or nil if there is none (never created, or killed).

func (*Executor) SetPane

func (e *Executor) SetPane(name, pane string)

SetPane sets what the named session's pane shows.

func (*Executor) TmuxSocket

func (e *Executor) TmuxSocket() string

TmuxSocket implements targets.TargetExecutor.

type Handler

type Handler func(ctx context.Context, d Dispatch) (reply string, err error)

Handler answers one dispatch in place of the router: its string is the reply, its error the dispatch's failure. ctx is cancelled when the client cancels the dispatch or the server shuts down.

type Option

type Option func(*config)

Option configures New.

func WithAPIOptions

func WithAPIOptions(opts ...api.Option) Option

WithAPIOptions passes more options to api.NewServer, after the ones New sets itself, so they win: a session lifetime, another TaskCanceller, an endpoint group New leaves unconfigured.

func WithClock

func WithClock(now func() time.Time) Option

WithClock sets the clock holds are acquired, renewed and ended by, so a test decides when a lease runs out. Session lifetimes still run on real time.

func WithPassword

func WithPassword(password string) Option

WithPassword sets the password the server accepts.

type Server

type Server struct {
	// URL is the server's base URL, without a trailing slash; the API is
	// under URL + "/api/v1".
	URL string
	// Password is what POST /api/v1/login accepts.
	Password string
	// Store is the server's store, for seeding what the Seed helpers
	// don't cover and for reading back what a call changed.
	Store registry.Store
	// Dispatcher answers the dispatches clients submit.
	Dispatcher *Dispatcher
	// Executor is the in-memory target every task's session lives on.
	Executor *Executor
	// API is the api.Server itself, to serve it through a handler of the
	// test's own. Don't call its EndStreams to test a client's reconnect:
	// it is the server's shutdown step, and every stream opened after it
	// ends at once.
	API *api.Server
	// contains filtered or unexported fields
}

Server is a running test server. Its fields are for seeding and inspecting; a client under test should only use URL and a token.

func New

func New(tb testing.TB, opts ...Option) *Server

New starts a Server and registers its teardown with tb.

func (*Server) ActiveHold

func (s *Server) ActiveHold(taskID string) *registry.TaskHold

ActiveHold returns the task's active drive hold, or nil if nobody holds it.

func (*Server) Login

func (s *Server) Login() string

Login logs in over HTTP with the server's password and returns the session token, to send as "Authorization: Bearer <token>". Each call is a new session, of origin login and client kind web: the kind that may approve a link. A login refused by the backoff a wrong password just started (429; at most 10 ms on a test server) is retried.

func (*Server) SeedConversation

func (s *Server) SeedConversation(conversationID, userMessage, reply string) *registry.Task

SeedConversation stores a conversation as one finished exchange leaves it: a user message, a task waiting for input, and the assistant's reply. It returns the task; its ConversationID is the conversation's (conversationID, or a fresh one when that is empty).

func (*Server) SeedFailedTask

func (s *Server) SeedFailedTask(conversationID string, class registry.ErrorClass, reason string) *registry.Task

SeedFailedTask stores a failed task with class and reason, in conversationID (a fresh conversation when empty). With registry.ErrorClassLoginRequired, ErrorClassAgentRateLimited or ErrorClassAgentAPIError its pane is one kept for a person, which a takeover may hold.

func (*Server) SeedLinkedSession added in v0.3.151

func (s *Server) SeedLinkedSession(label, clientKind string) string

SeedLinkedSession stores a session as the link flow leaves it once approved (origin link, with label and clientKind, e.g. "laptop" and registry.SessionKindTUI) and returns its token. It is how a test gets a terminal's session without driving the flow; to test the flow itself, POST /api/v1/sessions with a Login token.

func (*Server) SeedMessage

func (s *Server) SeedMessage(conversationID string, role registry.MessageRole, content string, task *registry.Task) *registry.Message

SeedMessage appends a message to conversationID's transcript. task links it to a task and may be nil.

func (*Server) SeedOffer

func (s *Server) SeedOffer(offer registry.Confirmation) *registry.Confirmation

SeedOffer stores an offer awaiting the user's yes (a pending confirmation) in offer.ConversationID. A zero Kind is run_command, a zero ExpiresAt ten minutes from now, and ID is filled when empty. The server knows only the offer's card: approving it in a dispatch reaches the Dispatcher's handler with ConfirmationID set, and what happens then is the handler's.

func (*Server) SeedPrompt

func (s *Server) SeedPrompt(conversationID string, prompt registry.Attention) *registry.Task

SeedPrompt stores a task stopped at a prompt only a person can answer (status needs-attention), in conversationID (a fresh conversation when empty). A zero prompt is a permission prompt for a Bash command with Yes and No.

func (*Server) SeedTarget

func (s *Server) SeedTarget(name string) *registry.Target

SeedTarget stores a remote target named name (host name + ".test", user "loomux"), so attach-info for a task on it carries an ssh attach command.

func (*Server) SeedTask

func (s *Server) SeedTask(seed Task) *registry.Task

SeedTask stores a task and gives it a session on the Executor, except a completed task, whose pane is taken to be gone. (A failed task gets one whatever its class, so every failed pane can be attached to.) The task is as a turn would have left it: nothing is running for it.

func (*Server) SeedTurn

func (s *Server) SeedTurn(task *registry.Task, userMessage, agentMessage, pane string) *registry.TaskTurn

SeedTurn stores one finished turn of task for GET /tasks/{id}/transcript: what was sent to the agent, its final message, and its pane.

func (*Server) SeedWorkspace

func (s *Server) SeedWorkspace(name string, target *registry.Target) *registry.Workspace

SeedWorkspace stores a workspace named name on target; with a nil target, on a new one named name + "-target".

func (*Server) SetTaskStatus

func (s *Server) SetTaskStatus(taskID string, status registry.TaskStatus, attention *registry.Attention) *registry.Task

SetTaskStatus moves a task to status as the server itself would between turns, which an open conversation stream reports as a task_update. attention is the prompt for needs-attention and nil otherwise. It fails the test if the task's status changed since it was read, as a takeover by the client under test would make it.

func (*Server) SweepHolds added in v0.3.154

func (s *Server) SweepHolds() int

SweepHolds runs one pass of the server's hold sweeper (LOOM-265) and returns how many holds it ended: a lease past its expiry on the server's clock (WithClock) ends as expired, a hold whose session no longer exists as session_revoked, one whose task ended as task_ended. A drive hold's session is detached (the task's Session.Detaches) and its task handed back. A real server sweeps every orchestrator.HoldSweepInterval; a test calls this when it wants one. Sessions are judged only by whether they exist here: their lifetime runs on real time, not the server's clock.

func (*Server) Task

func (s *Server) Task(id string) *registry.Task

Task returns the stored task, failing the test if there is none.

func (*Server) WatchHolds added in v0.3.158

func (s *Server) WatchHolds(taskID string) []*registry.TaskHold

WatchHolds returns the task's active watch holds, oldest first: the sessions attached to it read-only (LOOM-271). Empty when nobody watches it.

type Session

type Session struct {
	Name    string
	Dir     string
	Command string
	// Input is everything typed, pasted or sent as a named key into the
	// session, in order.
	Input []string
	// Pane is what CapturePane returns.
	Pane string
	// Detaches counts DetachClients calls for the session: the server
	// detaching whoever was attached, when a hold ends that way
	// (LOOM-265).
	Detaches int
}

Session is one tmux session of an Executor, as it stands.

type Task

type Task struct {
	// ID is the task's id; a fresh one when empty.
	ID string
	// ConversationID is the conversation the task belongs to; a fresh
	// one when empty. A conversation exists by having tasks or messages.
	ConversationID string
	// WorkspaceID is the task's workspace; the default workspace when
	// empty.
	WorkspaceID string
	// Status is the task's status; awaiting-input when empty. Statuses
	// are the store's spelling (registry.TaskStatusAwaitingInput); the
	// API shows them in snake_case.
	Status registry.TaskStatus
	// Kind is the task's kind; agent when empty. AgentType is its agent
	// type; DefaultAgentType when empty and the kind is agent.
	Kind      registry.TaskKind
	AgentType string
	// Attention is the prompt a needs-attention task is stopped at.
	Attention *registry.Attention
	// ErrorClass, FailureReason and OutputTail say why a failed task
	// failed.
	ErrorClass    registry.ErrorClass
	FailureReason string
	OutputTail    string
}

Task describes a task to seed. Every field may be left zero.

Jump to

Keyboard shortcuts

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