testrecord

package
v1.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 16 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 testrecord replays recorded real answers of external APIs in tests.

A fake written by hand answers what its author imagined, and a fake more lenient than the real service is green in CI and red live. A recording is what the service actually answered. This package loads a recorded HTTP or CLI exchange, checks it against the scrub rules below, and replays it as a CLI command runner (Cmd) or an HTTP server (Server). Recordings of AWS API answers are one kind it replays: an SDK client aimed at Server runs its own deserializers and typed errors against the recorded wire bytes.

Replay is strict:

  • a CLI request matches only an identical recorded argv; an HTTP request matches only the recorded method, decoded path, whole query (an unparseable query never matches), listed headers (each sent once with the recorded value; one recorded as "" must be absent) and body (a JSON body must be one JSON value, equal to the recorded one; no body matches only a request with no body); a miss fails the test, names the closest recorded request, and gets no plausible answer;
  • an AWS JSON-protocol request (POST / with a JSON body) must record its X-Amz-Target, since the body alone does not say which operation it is;
  • exchanges recorded for the same request are served in recorded order, and only the last of them may say "repeat": true to serve again;
  • every exchange must be served by the end of the test, unless the test calls Subset and says why.

A recording lives under a testdata/recordings directory with a README.md beside it that names it and states its capture and scrub. Load refuses a recording anywhere else, one without a scrub statement or README, and one that still carries:

  • a run of exactly twelve digits (an AWS account id's shape) other than the documentation account 111122223333;
  • an IPv4 address, bare or in an ip-a-b-c-d host name, outside 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24 and loopback;
  • an IPv6 address outside 2001:db8::/32 and loopback.

A value that only looks like one of these (an OID, a four-part version) is listed in the recording's "allow" with a reason; an allowed value excuses only an exactly equal match, never a longer value that contains it. A twelve-digit run inside a decimal number (a mantissa, a metric value), a longer token (a hex resource id) or ending a UUID is not an account id. Log message bodies, and identifiers inside encoded payloads (base64, a JWT), cannot be recognised mechanically: the capture replaces them and the scrub statement says so. Every committed file under a testdata/recordings directory must pass these checks, whether or not a test loads it.

A value in an answer too large or too specific to commit, which no test reads, is replaced at capture and declared in scrubbed: Parse checks that the declared place holds exactly the declared replacement.

A state no capture can produce on demand (a service reporting a failure) is a derived recording: it names its source capture in derivedFrom and the values it replaces in changed, and Parse verifies it equals the source apart from exactly those values, so only a value is ever authored, never a shape. An exchange that could not be captured at all (a write call the capture window did not allow) says why in handWritten.

Pagination tokens (NextToken, nextForwardToken and the like, in an answer or sent back with --next-token) must be "<pagination token N>" markers.

Recorded credentials are refused outright: an Authorization, security token, cookie or API key header with a value, a bearer token, or an AWS access key id.

The package is internal and imported only by tests; it is not a published helper.

Index

Constants

View Source
const DocumentationAccountID = "111122223333"

DocumentationAccountID is the only AWS account id a recording may carry.

View Source
const DocumentationRDSID = "abcdefghijkl"

DocumentationRDSID stands for the account-specific host id in an AWS RDS endpoint (<instance>.<id>.<region>.rds.amazonaws.com), which public DNS resolves; a recording carries this one instead.

Variables

View Source
var PaginationMarker = regexp.MustCompile(`^<pagination token [0-9]+>$`)

PaginationMarker is the form a recorded pagination token takes: the capture replaces each real token (an opaque, often base64 blob a secret scanner cannot tell from a key) with "<pagination token N>", consistently, so a request that sends a token back still matches the answer that gave it.

Functions

func CheckScrubbed

func CheckScrubbed(raw []byte, allow []Allowed) error

CheckScrubbed refuses credentials, account ids and addresses a capture must replace. An allowed value excuses only a match exactly equal to it.

func InRecordings

func InRecordings(path string) bool

InRecordings reports whether path is under a testdata/recordings directory.

Types

type Allowed

type Allowed struct {
	Value  string `json:"value"`
	Reason string `json:"reason"`
}

Allowed is a literal the scrub checks would refuse but that is not an account id or an address, with the reason it is kept.

type Captured

type Captured struct {
	When   string `json:"when"`
	Env    string `json:"env"`
	By     string `json:"by"`
	Tool   string `json:"tool"`
	Region string `json:"region,omitempty"`
	Commit string `json:"commit,omitempty"`
}

Captured says where, when and with what the recording was made.

type Exchange

type Exchange struct {
	Note     string   `json:"note,omitempty"`
	Request  Request  `json:"request"`
	Response Response `json:"response"`
	// HandWritten says why this one exchange could not be captured (a write
	// call, a state no read can produce) and what replaces it. An exchange
	// without it is a capture.
	HandWritten string `json:"handWritten,omitempty"`
	// Repeat serves this answer again for every later identical request,
	// once the exchanges recorded before it are used up. It models a
	// steady state the capture observed, never a guess.
	Repeat bool `json:"repeat,omitempty"`
}

Exchange is one request and the answer it got.

type Recording

type Recording struct {
	Captured  Captured   `json:"captured"`
	Scrub     []string   `json:"scrub"`
	Allow     []Allowed  `json:"allow,omitempty"`
	Exchanges []Exchange `json:"exchanges"`

	// DerivedFrom names a captured recording in the same directory that this
	// one repeats with only the values in Changed replaced: a state a capture
	// cannot produce on demand (a service reporting a failure), in a shape a
	// capture did produce. Changed maps a JSON pointer into the recording
	// document to the value placed there. Parse verifies the derivation.
	DerivedFrom string                     `json:"derivedFrom,omitempty"`
	Changed     map[string]json.RawMessage `json:"changed,omitempty"`

	// Scrubbed lists values in the recorded answers replaced at capture:
	// content too large or too specific to commit that no test reads (a
	// server's full capability listing). Parse verifies each names a place
	// inside a recorded answer's body that holds exactly its replacement.
	Scrubbed []Scrubbed `json:"scrubbed,omitempty"`
	// contains filtered or unexported fields
}

Recording is one captured scenario.

func Join

func Join(t T, recs ...*Recording) *Recording

Join replays several recordings as one: a scenario built from the recordings of its parts (one per service the scenario calls). Each request must be recorded in exactly one of them, so which file answers is never ambiguous, and the joined replay keeps every rule: unrecorded requests fail, and every exchange of every part must be served unless the test calls Subset on the joined replay.

func Load

func Load(t T, path string) *Recording

Load reads and checks one recording, and at the end of the test fails it if an exchange was never served (see Subset).

func Parse

func Parse(path string, raw []byte) (*Recording, error)

Parse checks a recording's shape, scrub and README without serving it.

func (*Recording) Cmd

func (r *Recording) Cmd() func(name string, args ...string) ([]byte, error)

Cmd returns a command runner shaped like a wrapper over exec.Command(...).Output(): name and args must equal a recorded argv exactly. A recorded non-zero exit returns the recorded stdout with an error carrying the exit status and the recorded stderr.

func (*Recording) Server

func (r *Recording) Server() *httptest.Server

Server returns an HTTP server that answers only recorded requests. A miss fails the test and answers 599, a status no client retries or mistakes for a real answer.

func (*Recording) Subset

func (r *Recording) Subset()

Subset lets the test leave exchanges unserved. Say why at the call site: an unserved exchange is usually a recording the code no longer reaches.

type Request

type Request struct {
	Argv     []string            `json:"argv,omitempty"`
	Method   string              `json:"method,omitempty"`
	Path     string              `json:"path,omitempty"`
	Query    map[string][]string `json:"query,omitempty"`
	Headers  map[string]string   `json:"headers,omitempty"`
	Body     json.RawMessage     `json:"body,omitempty"`
	BodyText string              `json:"bodyText,omitempty"`
}

Request identifies a recorded request: a CLI argv (command name first), or an HTTP method and path with an optional query, headers and body. A JSON Body matches a JSON-equal request body; BodyText matches byte for byte.

type Response

type Response struct {
	Status     int               `json:"status,omitempty"`
	Headers    map[string]string `json:"headers,omitempty"`
	Body       json.RawMessage   `json:"body,omitempty"`
	BodyText   string            `json:"bodyText,omitempty"`
	Stdout     json.RawMessage   `json:"stdout,omitempty"`
	StdoutText string            `json:"stdoutText,omitempty"`
	Stderr     string            `json:"stderr,omitempty"`
	Exit       int               `json:"exit,omitempty"`
}

Response is the recorded answer: Status, Headers and Body or BodyText for HTTP; Stdout or StdoutText, Stderr and Exit for a CLI.

type Scrubbed

type Scrubbed struct {
	Pointer        string          `json:"pointer"`
	Replacement    json.RawMessage `json:"replacement"`
	Reason         string          `json:"reason"`
	OriginalBytes  int             `json:"originalBytes"`
	OriginalSHA256 string          `json:"originalSha256"`
}

Scrubbed is one value replaced at capture: where (a JSON pointer into the recording, inside /exchanges/<n>/response/body/), what now stands there, why, and the size and SHA-256 of the whole answer body as captured (after any content decoding), as provenance. The original is not committed, so Parse checks the declaration's consistency, not the removed bytes.

type T

type T interface {
	Helper()
	Errorf(format string, args ...any)
	Fatalf(format string, args ...any)
	Cleanup(func())
}

T is the part of *testing.T the helper uses.

Jump to

Keyboard shortcuts

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