httpfixture

package
v1.146.0 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2026 License: Apache-2.0 Imports: 22 Imported by: 1 module, 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.

README

HTTP fixture replay

NewCaptureTransport(base) collects the same exchange format from an HTTP transport. Call StartStep(label) before dispatch, then Snapshot() after requests finish. Concurrent calls retain dispatch order, without enabling ordered replay. Transport/body-read failures invalidate the entire recording. Bodies remain readable by the SDK; multipart boundaries are omitted, and binary content uses base64. Valid JSON is captured semantically only for declared application/json or application/*+json media types; other bodies retain exact bytes, including when the media type is missing or malformed. Response Location headers are retained verbatim; the recorder must normalize same-host absolute redirects before replay. Authentication and cookie headers are excluded. API payloads are retained in memory: the recorder must redact secrets and normalize profile-specific values before saving them. This transport does not load profiles, enable live requests, or write fixtures itself.

NewHandler() creates an empty handler for stateless request/response exchanges. SetReusableFixtures(calls) replaces the test-wide reusable fallbacks; nil clears them. Invalid replacements leave the old fixtures intact. Replacing reusable fixtures does not reset the current step or its failures. StartStep installs a step's consumable fixtures and returns any failures from the previous step. Verify checks the current step for unexpected calls and unused fixtures.

Matching includes the method, escaped path, query parameters, JSON body, and listed request headers. JSON object key order and whitespace are ignored; array order and values matter. An absent body differs from JSON null.

Volatile request values

Use explicit request.matchers annotations rather than wildcard strings:

request:
  method: POST
  path: /requests
  headers:
    X-Request-ID: captured-header-id
  query:
    request_id: [captured-query-id]
  body:
    json:
      request_id: captured-body-id
      name: fixed-name
  matchers:
    headers:
      X-Request-ID: any_string
    query:
      request_id: any_string
    json:
      - path: [request_id]
        type: any_string
response:
  status: 200

any_string requires a present string, including an empty string; it does not match a missing value, JSON null, or another JSON type. Header names are case-insensitive. Header/query matchers require exactly one value and override the corresponding sample if supplied; the sample may also be omitted. Unlisted headers remain ignored. Unmatched query keys/values remain exact, including multiplicity and value order; extra query keys fail.

JSON paths use literal string keys and zero-based integer array indices, for example [items, 0, request_id]. An explicit path: [] selects a scalar JSON body. The target must exist as a string or null sample in body.json; null is only a placeholder and does not make null match. Other fields, object keys, array lengths/order, and numeric values remain exact. Invalid matcher types, duplicate targets, and paths absent from the sample fail when fixtures are loaded.

In Go, use Request.Matchers with AnyString and JSONMatcher paths. Matchers do not modify the original samples, so a future recorder can keep captured values alongside these annotations. Response payloads remain literal; there are no captures, substitutions, regexes, or magic payload strings/objects. "any_string" and "****" without annotations still match only those strings.

Consumption and ordering

Independent request signatures may interleave. Identical signatures consume responses FIFO. Requests and fixture consumption are protected by a mutex. If matcher signatures overlap, the first matching unconsumed fixture wins; there is no preference for a more specific fixture. Different captured samples overridden by the same matchers therefore consume responses FIFO too. SetEnforceCallOrder(true) optionally requires all consumable calls in their listed order within each step. Out-of-order requests fail without consuming their fixture. The setting survives step transitions; changing it does not clear consumption or failures. Reusable fallbacks remain outside ordering, but cannot bypass an out-of-order matching consumable call. Test-wide reusable exchanges are intended for invariant client initialization, such as host metadata; they are not required to be consumed.

Files and non-JSON bodies

A non-null body selects exactly one representation:

body:
  text: |
    # comment
# Or: body: {base64: "AP8K"} for the bytes 00 ff 0a.

json compares parsed JSON; text and base64 compare exact bytes, including whitespace. An empty text/binary body matches zero bytes. Use base64 for bytes that cannot be represented as UTF-8. Responses support these same three modes, with default content types application/json, text/plain; charset=utf-8, and application/octet-stream, respectively. Explicit response headers override them.

Multipart requests describe the decoded form rather than its random boundary:

body:
  multipart:
    - name: path
      body: {text: /Shared/script.py}
    - name: content
      filename: content
      headers: {Content-Type: application/octet-stream}
      body:
        text: |
          # comment

Every part needs a name and a body.text or body.base64. Matchers compare names, filenames, bytes, multiplicity, and explicitly listed part headers. Additional part headers are ignored. Part order and the transport boundary are ignored; missing or extra parts fail. The request must use multipart/form-data. Multipart responses and JSON matchers on non-JSON bodies are unsupported. Header and query matchers work with every body representation.

Wire behavior

Response.Delay is a Go duration string, such as "2s", waited before writing anything; the wait ends when the client closes the connection. The wait runs outside the handler lock, so other requests are served meanwhile. Response.Fault hijacks the connection: FaultReset closes it with linger 0, FaultClose closes it without a response, FaultTruncateBody declares the full Content-Length but writes half the body, and FaultStallBody writes half the body, then waits until the client closes the connection. Response.StatusLine writes a literal HTTP/1.0 or HTTP/1.1 status line, such as HTTP/1.1 404, whose code must equal Status; a HEAD response keeps the fixture's Content-Length. Reset and close responses omit status, headers, body and status line. Body faults need a nonempty body and reject HEAD requests and 1xx, 204 and 304 statuses, because net/http never reads those bodies. Invalid values fail when fixtures are loaded.

Go's client silently resends a replayable request, such as a GET, that fails on a reused connection. Clients should therefore use NewClientTransport, as qa/terraformtest and qa/replay/clienttest do: it opens one connection per request and sends a copy of each request body with its declared length. Faults and status lines close the connection and frame the body by its Content-Length, replacing fixture Connection, Content-Length and Transfer-Encoding headers. They need a server that supports hijacking, such as httptest.NewServer; otherwise the client gets a 400 and Verify reports the failure. Faulted calls are consumed and ordered like any other call.

Authentication configuration tests

NewOfflineAuthTransport(t) can be assigned to an SDK config's HTTPTransport when testing credential selection against example hosts. It returns 404 for external host-metadata and OAuth discovery requests, allows HTTP requests to local fixture servers, and fails the test on any other external request. This keeps the default authentication chain active without contacting real Databricks workspaces.

Documentation

Overview

Package httpfixture replays HTTP exchanges without simulating remote state.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewClientTransport

func NewClientTransport() http.RoundTripper

NewClientTransport returns the transport for clients of a fixture server, so faults reach them. Go's client silently resends a replayable request that fails on a reused connection, so it opens one connection per request.

func NewOfflineAuthTransport

func NewOfflineAuthTransport(t testing.TB) http.RoundTripper

NewOfflineAuthTransport stubs remote host and OAuth discovery as unavailable. Local fixture servers remain reachable so authentication and token refresh tests can exercise their real HTTP flows. Other remote requests fail the test.

func PreserveMatchers

func PreserveMatchers(calls, previous []Call) error

PreserveMatchers carries author-selected volatility annotations to refreshed calls using the existing matching rules, never call indices. Interleaving and extra reads therefore cannot attach an annotation to another operation. Unmatched annotations fail refresh instead of being silently lost.

Types

type Body

type Body struct {
	JSON      any             `yaml:"json,omitempty"`
	Text      *string         `yaml:"text,omitempty"`
	Base64    *string         `yaml:"base64,omitempty"`
	Multipart []MultipartPart `yaml:"multipart,omitempty"`
}

Body selects semantic JSON, exact UTF-8 text, exact binary bytes encoded as base64, or multipart form parts. A nil *Body means no HTTP body.

func (Body) MarshalYAML

func (b Body) MarshalYAML() (any, error)

MarshalYAML preserves an explicit JSON null instead of emitting an empty body mapping. The other representations also retain intentionally empty bytes.

func (*Body) UnmarshalYAML

func (b *Body) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML requires an explicit representation, including json: null. Decode nodes directly so references to other YAML anchors remain valid.

type Call

type Call struct {
	Request  Request  `yaml:"request"`
	Response Response `yaml:"response"`
}

Call pairs a request signature with its response.

type CaptureTransport

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

CaptureTransport observes HTTP at the same boundary used by replay. It does not authenticate, retry, choose hosts, or write files; those belong to callers. Response bodies are buffered and restored before the SDK sees them.

func NewCaptureTransport

func NewCaptureTransport(base http.RoundTripper) *CaptureTransport

NewCaptureTransport wraps the caller's transport. Snapshots contain API payloads in memory; the owning recorder must sanitize them before persistence.

func (*CaptureTransport) RoundTrip

func (c *CaptureTransport) RoundTrip(req *http.Request) (*http.Response, error)

func (*CaptureTransport) Snapshot

func (c *CaptureTransport) Snapshot() ([]CapturedStep, error)

Snapshot returns an independent copy so normalization cannot race with capture or alter a later snapshot. An incomplete exchange never becomes a fixture.

func (*CaptureTransport) StartStep

func (c *CaptureTransport) StartStep(label string) error

StartStep refuses transitions during a request so a late reply cannot be attributed to the next step. Capture failures are permanent for this session.

func (*CaptureTransport) Verify

func (c *CaptureTransport) Verify() error

type CapturedStep

type CapturedStep struct {
	Label string
	Calls []Call
}

CapturedStep retains dispatch order, even when concurrent replies finish in another order. Recording that order does not opt a test into ordered replay.

type Fault

type Fault string

Fault names what the server does to the connection instead of completing a response. The resulting client error depends on the client's HTTP stack.

const (
	// FaultReset closes the connection with linger 0, so the peer gets a TCP reset.
	FaultReset Fault = "reset"
	// FaultClose closes the connection without writing a response.
	FaultClose Fault = "close"
	// FaultTruncateBody declares the full Content-Length, writes the first half
	// of the body and closes the connection.
	FaultTruncateBody Fault = "truncate_body"
	// FaultStallBody writes the first half of the body, then waits until the
	// client closes the connection.
	FaultStallBody Fault = "stall_body"
)

type Handler

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

Handler permits independent requests to interleave and consumes identical request signatures FIFO. A mutex keeps matching and consumption atomic.

func NewHandler

func NewHandler() *Handler

NewHandler returns an empty handler; fixture sets are configured separately.

func (*Handler) ServeHTTP

func (h *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request)

ServeHTTP prefers consumable step fixtures over reusable fallbacks.

func (*Handler) SetEnforceCallOrder

func (h *Handler) SetEnforceCallOrder(enabled bool)

SetEnforceCallOrder requires consumable calls in fixture order when enabled. Reusable fallbacks remain unordered. Changing this setting preserves the current step's consumption and failures.

func (*Handler) SetReusableFixtures

func (h *Handler) SetReusableFixtures(calls []Call) error

SetReusableFixtures replaces test-wide fallback exchanges, such as metadata. They survive step transitions, may be matched repeatedly, and need not be consumed. Invalid fixtures leave the previous set intact.

func (*Handler) StartStep

func (h *Handler) StartStep(label string, calls []Call) error

StartStep reports the previous step's failures and installs the next exchanges. Installing them even after failure allows the runner to attempt cleanup.

func (*Handler) Verify

func (h *Handler) Verify() error

Verify reports unexpected requests and unconsumed step exchanges without clearing failures. Reusable fixtures are excluded from consumption checks.

type JSONMatcher

type JSONMatcher struct {
	Path []any   `yaml:"path"`
	Type Matcher `yaml:"type"`
}

JSONMatcher selects a literal object key or zero-based array index at each path segment. An explicit empty path selects the whole JSON body.

type Matcher

type Matcher string

Matcher relaxes a selected request value without changing literal payloads.

const AnyString Matcher = "any_string"

AnyString requires a present string, including the empty string. It does not capture values or substitute them into later requests or responses.

type Matchers

type Matchers struct {
	Headers map[string]Matcher `yaml:"headers,omitempty"`
	Query   map[string]Matcher `yaml:"query,omitempty"`
	JSON    []JSONMatcher      `yaml:"json,omitempty"`
}

Matchers override only the selected request values. Headers and query keys require exactly one value; JSON targets must exist in the sample body. Keeping these annotations outside the payload avoids reserved JSON keys.

type MultipartPart

type MultipartPart struct {
	Name     string            `yaml:"name"`
	Filename string            `yaml:"filename,omitempty"`
	Headers  map[string]string `yaml:"headers,omitempty"`
	Body     *Body             `yaml:"body"`
}

MultipartPart describes one form field or file. Part order and the transport boundary are ignored; names, filenames, bytes and listed headers remain exact.

func (*MultipartPart) UnmarshalYAML

func (p *MultipartPart) UnmarshalYAML(node *yaml.Node) error

UnmarshalYAML keeps strict field checking inside the custom Body decoder.

type Request

type Request struct {
	Method   string              `yaml:"method"`
	Path     string              `yaml:"path"`
	Query    map[string][]string `yaml:"query,omitempty"`
	Headers  map[string]string   `yaml:"headers,omitempty"`
	Body     *Body               `yaml:"body"`
	Matchers Matchers            `yaml:"matchers,omitempty"`
}

Request defines a complete signature; only listed headers are compared.

type Response

type Response struct {
	Status  int               `yaml:"status,omitempty"`
	Headers map[string]string `yaml:"headers,omitempty"`
	Body    *Body             `yaml:"body"`
	// Delay is a Go duration, such as 2s, to wait before writing anything. The
	// wait ends early when the client closes the connection.
	Delay string `yaml:"delay,omitempty"`
	// Fault breaks the connection. Reset and close omit status, headers and body.
	Fault Fault `yaml:"fault,omitempty"`
	// StatusLine is the literal status line, such as HTTP/1.1 404 without a
	// reason phrase. Its code must equal Status.
	StatusLine string `yaml:"status_line,omitempty"`
}

Response defines the HTTP reply, with an optional JSON, text, or binary body.

Jump to

Keyboard shortcuts

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