testfixture

package
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 28 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 testfixture owns test resources without importing their packages.

Index

Constants

View Source
const ZeroRowCorrelatedCallSeedCypher = "" /* 355-byte string literal not displayed */

ZeroRowCorrelatedCallSeedCypher is the graph every zero-row correlated CALL aggregation case runs against. It stays transport-independent: each public boundary executes it with its own context, connection or executor.

Variables

This section is empty.

Functions

func Append

func Append[T any](owner *sync.Mutex, values *[]T, value T)

Append adds one recorded value under the existing owner lock of a fixture's slice. Pass the address of the slice, not an already-read slice value: a producer writing a slice value it read before taking the lock would race with a concurrent reader and could drop a value. The fixture keeps its single writer, and every reader takes that same lock through Snapshot.

Appending never copies and never sorts: order is the order in which the lock was taken. A fixture that drains its values atomically keeps its own lock-held take, because Snapshot followed by a reset would lose values recorded between the two steps.

func AssertZeroRowCorrelatedCallRows

func AssertZeroRowCorrelatedCallRows(t *testing.T, rows [][]any, testCase ZeroRowCorrelatedCallCase)

AssertZeroRowCorrelatedCallRows asserts the exact rows an ungrouped aggregation over the correlated CALL fixtures must produce: one row holding subjects, given versions and carry, with subject, party/role and ids/carried cardinality matching the case. A populated stream must resolve subject id n0 and carry it exactly once.

func CachedStorage

func CachedStorage[T comparable](t testing.TB, lookup func() (T, error)) T

CachedStorage asserts that a lookup whose result is cached returns the same instance on consecutive calls. It calls lookup twice, returns the first result and fails when either lookup reports an error, when a lookup returns the zero value, or when the two lookups differ. Reported failures name neither the returned value nor the wrapped error, so manager diagnostics which embed connection details cannot reach test output through this assertion.

func CurrentGoroutineID

func CurrentGoroutineID() uint64

CurrentGoroutineID identifies the calling test goroutine for lock diagnostics.

func Encode

func Encode[T any](owner EncodingOwner, encode func(T) ([]byte, error), value T) []byte

Encode runs the explicitly selected fixture codec and fails its test on error. For example, Encode(t, msgpack.Marshal, historicalValue) retains a frozen format.

func ExtractZip

func ExtractZip(t *testing.T, archivePath, trimPrefix string) string

ExtractZip unpacks a checked-in archive into a test-owned directory. trimPrefix lets a public constructor use the same fixture with its different disk layout.

func InstallTracerProvider

func InstallTracerProvider(t testing.TB, provider *sdktrace.TracerProvider, propagator propagation.TextMapPropagator) func()

InstallTracerProvider owns the process-global test tracing lifetime. Callers construct their actual processor/exporter and sampler; a nil propagator keeps the current propagation policy. The returned cleanup also permits explicit nested scopes; automatic test cleanup is idempotent. Cleanup detaches the provider before closing it, and restores only the propagation state this scope changed.

func NamespaceTransaction

func NamespaceTransaction[T interface {
	SetNamespace(string) error
	Rollback() error
}, R comparable](t testing.TB, begin func(context.Context, R) (T, error), request R, namespace string) T

NamespaceTransaction opens a test transaction with the begin request its caller owns, binds its namespace when provided, and owns rollback even when an assertion terminates its caller. A test that needs an autocommit schema statement passes storage.AutocommitSchemaBegin here only through SchemaManager.BeginSchemaTransaction; this helper opens the transaction it is given. For example: tx := NamespaceTransaction(t, engine.BeginTransaction, storage.OrdinaryBegin, "tenant").

func NestedGraphProperties

func NestedGraphProperties(index int) map[string]interface{}

NestedGraphProperties creates fresh scalar, list and map values for graph ownership tests and benchmarks. Each call owns its mutable containers.

func ObserveHookSignal

func ObserveHookSignal(owner interface {
	Helper()
	Cleanup(func())
}, install func(func()) func(), capacity int) <-chan struct{}

ObserveHookSignal installs a test hook through install and returns the channel each invocation of that hook is reported on, so a test can order concurrent work by the hook itself instead of by timing. The channel is buffered with the caller's capacity: a report that arrives while the buffer is full is dropped rather than blocking the observed work.

install must set the hook and return the function that restores the previous one, such as a package's SetSomeHookForTesting. That restore runs when the owning test finishes, so the hook's lifetime covers exactly the test.

func OpenStores

func OpenStores() (int, string)

OpenStores counts Badger stores, including allocations which a failed constructor never returns. Each open DB has exactly one doWrites worker; DB.Close waits for it. This needs no hook in the production allocator.

func Own

func Own[T Closer](owner Owner, resource T, before ...Closer) T

Own registers resource at construction. Dependencies listed in before are closed first, for example an engine before the WAL it borrows. The concrete values are captured even when a caller later reassigns its fixture variable.

func OwnChecked

func OwnChecked[T Closer](owner CheckedOwner, resource T, before ...Closer) T

OwnChecked preserves an existing close assertion through the shared owner. All dependencies and the resource are closed even if an earlier close fails.

func OwnResult

func OwnResult[T Closer](owner Owner, closedError error) func(T, error) (T, error)

OwnResult registers and closes an error-returning fixture at its real test boundary. Constructor errors and concrete resources are returned unchanged.

func OwnResult3

func OwnResult3[T Closer, U any](owner Owner, closedError error) func(T, U, error) (T, U, error)

OwnResult3 also preserves the recovery metadata returned beside an engine.

func OwnWithCloseAssertion

func OwnWithCloseAssertion[T Closer](owner Owner, resource T, assertion func(error) bool, before ...Closer) T

OwnWithCloseAssertion registers resource for cleanup and accepts close errors only when assertion identifies them as expected. Unaccepted errors are reported through the owner like Own.

func ReadWithFailure

func ReadWithFailure[T any](ctx context.Context, fault error, read func(context.Context) (T, error)) (T, error)

ReadWithFailure is the one owner of the injected-read-failure contract shared by test doubles: an injected fault returns that exact error and the zero value of T without invoking read, without a retry or result transformation. With no fault it returns read's own result and error unchanged and hands read the caller's ctx, so underlying errors and results keep their identity. For example:

return testfixture.ReadWithFailure(ctx, e.allNodesErr, e.Engine.AllNodes)

The double keeps its own fields, counters and arguments; this helper decides only what a selected fault returns.

func ReceiverName

func ReceiverName(expression ast.Expr, naming ReceiverNaming) string

ReceiverName reads the base name of an AST receiver, ignoring generic type arguments. For example, *Box[T] is "*Box" with ReceiverWithPointers and "Box" with ReceiverBaseName. Unrecognized syntax retains only pointer markers.

func RecordSpans

func RecordSpans(t testing.TB) (*tracetest.InMemoryExporter, func())

RecordSpans installs the shared synchronous, always-sampled test recorder and W3C trace/baggage propagation. The returned cleanup preserves explicit nested scopes; InstallTracerProvider also registers idempotent automatic cleanup.

func RequireFloat32Vector

func RequireFloat32Vector(t testing.TB, name string, actual []float32, dimensions int, valueAt func(int) float32)

RequireFloat32Vector checks the complete deterministic vector without allocating an expected slice. The caller owns the fixture's value pattern.

func RequireMarkersAbsent

func RequireMarkersAbsent(t interface {
	Helper()
	Fatal(...any)
}, text string, markers ...string)

RequireMarkersAbsent fails when text contains any supplied marker. It reports neither text nor markers, so credential-output tests cannot disclose the very values they detect. For example, pass a fixture's synthetic password markers.

func Run

func Run(m *testing.M, name string) int

Run checks the real store population at a package's TestMain boundary.

func RunCatalogDropCycles

func RunCatalogDropCycles(t testing.TB, count int, prefix string, create, use, drop func(string) error)

RunCatalogDropCycles performs count create/use/drop cycles against a catalog fixture, naming each database with prefix followed by its zero-based index. It fails the test on the first error from create, use or drop.

func Snapshot

func Snapshot[T any](owner *sync.Mutex, values *[]T) []T

Snapshot returns a detached shallow copy of a fixture's slice while holding its existing owner lock. Pass the address of the slice, not an already-read slice value: reading a concurrently appended slice before taking the lock would race. Producers and atomic resets keep their existing lock and state. Empty snapshots are nil, matching append([]T(nil), values...).

func SpanAttrs

func SpanAttrs(attributes []attribute.KeyValue) map[string]string

SpanAttrs projects recorded attributes to the canonical string values used by span contract assertions. Callers select their recorder's attribute slice.

func Track

func Track[T Closer](owner Owner, resource T, closedError error) T

Track registers a fixture with its actual testing.T, B or F. Owner remains an interface so existing shared helpers can pass their testing owner through; a synthetic boundary cannot replace a real test boundary at runtime.

func TrackProcess

func TrackProcess[T Closer](owner *Boundary, resource T, closedError error) T

TrackProcess is reserved for the process leak detector's deliberate control. The repository constructor-entry lint lists that one entrance explicitly. Ordinary fixtures must use Track and their real testing owner.

func TrackResult

func TrackResult[T Closer](owner Owner, closedError error) func(T, error) (T, error)

TrackResult preserves an error-returning constructor's original results. Its curried form keeps the constructor as the only argument and registers a non-nil resource even when a constructor returns an error with that resource.

func WaitForBarrier

func WaitForBarrier(t interface {
	Helper()
	Fatalf(string, ...any)
}, ready <-chan struct{}, timeout time.Duration, onTimeout func(), failure string)

WaitForBarrier blocks until ready reports that the goroutine under test reached its barrier. On timeout it invokes onTimeout, when supplied, before failing with the caller's message so a paused goroutine can be released.

func WalkRepositoryTree

func WalkRepositoryTree(root string, visit fs.WalkDirFunc) error

WalkRepositoryTree visits one checkout without entering nested Git checkouts. Verification tools may check out another revision below the repository root; its .git directory or worktree file identifies a separate source population, regardless of directory name. Ordinary nested Go modules remain visible. The visitor retains its own file and directory policy, and isolated source fixtures need no Git metadata at their root.

Types

type AlwaysEnabled

type AlwaysEnabled struct{}

AlwaysEnabled is the shared capability of a fixture provider that is always enabled. Its zero value is ready for use, and it belongs first in an embedding struct so the zero-size capability stays out of any trailing padding.

func (AlwaysEnabled) Enabled

func (AlwaysEnabled) Enabled() bool

Enabled reports that the embedding fixture provider is always enabled.

type Boundary

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

Boundary owns fixtures until an explicit lifecycle boundary, such as the process leak check in TestMain. Its zero value is ready for use.

func (*Boundary) Cleanup

func (boundary *Boundary) Cleanup(cleanup func())

Cleanup registers cleanup at this boundary.

func (*Boundary) Close

func (boundary *Boundary) Close() error

Close runs the registered fixture cleanups after the boundary's checks and returns their failures.

func (*Boundary) Errorf

func (boundary *Boundary) Errorf(format string, args ...any)

Errorf records a fixture failure for the process boundary.

func (*Boundary) Helper

func (*Boundary) Helper()

Helper implements Owner for an explicit boundary rather than testing.T.

type CheckedOwner

type CheckedOwner = Owner

CheckedOwner is retained for existing fixture helpers. All owners report close failures.

type CheckpointContext

type CheckpointContext struct {
	context.Context
	Cancel context.CancelFunc
	// contains filtered or unexported fields
}

CheckpointContext cancels its real context on the selected live Err check. It is a deterministic work-boundary fixture, not a wall-clock deadline. The observer runs once, after cancellation, so tests can snapshot work.

func NewCheckpointContext

func NewCheckpointContext(limit int, observe func()) *CheckpointContext

NewCheckpointContext creates a real cancelable background context. A positive limit selects the cancellation check; nonpositive limits never trigger it.

func (*CheckpointContext) Checks

func (c *CheckpointContext) Checks() int

Checks reports the number of live work-boundary observations.

func (*CheckpointContext) Err

func (c *CheckpointContext) Err() error

Err observes the underlying lifetime and advances only while it is live.

type Closer

type Closer interface {
	Close() error
}

Closer is a concrete fixture whose lifetime belongs to its test.

type EncodingOwner

type EncodingOwner interface {
	Helper()
	Fatalf(string, ...any)
}

EncodingOwner is the fatal assertion boundary supplied by testing.T or B.

type EncryptionPropertyCase

type EncryptionPropertyCase struct {
	Name      string
	Value     any
	Class     string
	RoundTrip bool
}

EncryptionPropertyCase keeps a synthetic property shared by configuration classification checks and the real database encryption round-trip. Class is explicit, PHI or plain for the custom field-config test; empty omits that test's classification cell. RoundTrip selects the original database inputs.

func EncryptionPropertyCases

func EncryptionPropertyCases() []EncryptionPropertyCase

EncryptionPropertyCases returns fresh, synthetic property cases without retaining a caller's edits. For example, a database test builds its input from cases with RoundTrip set; configuration tests select nonempty Class.

type ErrorWriter

type ErrorWriter struct {
	Err   error
	Calls atomic.Int64
}

ErrorWriter rejects writes with Err and counts concurrent attempts safely. Configure Err before sharing the writer; transport fixtures can embed it.

writer := &testfixture.ErrorWriter{Err: errWriteFailed}
_, _ = writer.Write(nil) // Calls.Load() == 1; the error is errWriteFailed.

func (*ErrorWriter) Write

func (w *ErrorWriter) Write([]byte) (int, error)

Write implements io.Writer, counting the attempt in Calls, accepting no bytes, and returning Err unchanged.

type FixedBatchEmbedding2D

type FixedBatchEmbedding2D struct{}

FixedBatchEmbedding2D is the canonical batch embedding fixture: its zero value reports one [1, 0] vector per input text in input order. Every row is a fresh slice, so rows never share a backing array.

func (FixedBatchEmbedding2D) EmbedBatch

func (FixedBatchEmbedding2D) EmbedBatch(ctx context.Context, texts []string) ([][]float32, error)

EmbedBatch returns len(texts) fresh [1, 0] vectors, or the context's error when ctx is already canceled or past its deadline.

type FixedEmbedding2D

type FixedEmbedding2D struct{}

FixedEmbedding2D is the canonical single-text embedding fixture: its zero value reports the same two-dimensional unit vector for every input. Embed returns a fresh slice on each call, so a caller that owns a returned vector cannot observe another caller's mutation.

FixedEmbedding2D carries only the single-text capability. A fixture that also needs batch embedding composes FixedBatchEmbedding2D beside it, keeping its method set to exactly the optional capabilities it serves.

func (FixedEmbedding2D) Embed

func (FixedEmbedding2D) Embed(ctx context.Context, _ string) ([]float32, error)

Embed returns a fresh [1, 0] vector, or the context's error when ctx is already canceled or past its deadline.

type Owner

type Owner interface {
	Helper()
	Cleanup(func())
	Errorf(string, ...any)
}

Owner is the cleanup boundary provided by testing.T, testing.B or Boundary.

type PauseGate

type PauseGate struct {
	Armed   *atomic.Bool
	Entered chan struct{}
	Release chan struct{}
	// contains filtered or unexported fields
}

PauseGate pauses one armed observation until its owner releases it. Domain adapters decide when to call Pause; the gate owns only the once-only signal and idempotent release, including release before a paused worker arrives. A new gate is unarmed: the adapter arms the single observation it wants to park, and a one-shot adapter arms its gate in its own constructor.

func NewPauseGate

func NewPauseGate() *PauseGate

NewPauseGate returns an initially unarmed gate.

func (*PauseGate) Pause

func (g *PauseGate) Pause(armed *atomic.Bool, entered chan struct{}) bool

Pause reports whether this caller consumed the armed state and therefore paused. Exactly one caller can receive true: that caller closes entered before waiting for Release. A caller that receives false did not pause, so the observation it stands for must not report anything the gate owns.

func (*PauseGate) ReleaseWrites

func (g *PauseGate) ReleaseWrites()

ReleaseWrites releases a paused caller and is safe from repeated cleanup.

type QueryReadObserver

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

QueryReadObserver records request-owned access counters in component tests that cannot import the Cypher collector. Its zero value is ready for use; bind it with queryprofile.WithObserver(ctx, &reads). It retains no context.

func (*QueryReadObserver) Access

func (o *QueryReadObserver) Access(_ context.Context, kind, detail string) *queryprofile.ReadCounter

Access implements queryprofile.Observer and reuses one counter per read key.

func (*QueryReadObserver) Callbacks

func (o *QueryReadObserver) Callbacks() []string

Callbacks returns detached invocation records, including repeated invocations.

func (*QueryReadObserver) Reads

func (o *QueryReadObserver) Reads(kind, detail string) (rows, hits int64, recorded bool)

Reads distinguishes an absent read from a known zero population.

func (*QueryReadObserver) RecordedKinds

func (o *QueryReadObserver) RecordedKinds() []string

RecordedKinds returns read kinds in acquisition order, detached from the owner.

func (*QueryReadObserver) UnobservedRead

func (o *QueryReadObserver) UnobservedRead(_ context.Context, category, name string)

UnobservedRead records an actual opaque callback invocation.

func (*QueryReadObserver) WithLifetime

func (o *QueryReadObserver) WithLifetime(lifetime context.Context, _ context.Context) context.Context

This component ledger has no clause scope to freeze.

type RawLogHandler

type RawLogHandler func(context.Context, slog.Record) error

RawLogHandler adapts an observer callback to slog.Handler for the test probes that assert on the raw records an owner emits.

It is a test probe, not a general-purpose production logger. Handle hands the emitted record and its context to the callback unchanged, Enabled accepts every level, and WithAttrs and WithGroup return the same raw observer: attributes and group names bound on a logger are intentionally discarded instead of being stored or applied. That preserves the existing fixtures' contract — every record the owner emits reaches their callback, and no logger-bound attribute or open group can hide or reshape it — so a probe that needs bound attributes or nested groups needs a different handler.

func (RawLogHandler) Enabled

Enabled reports true for every record: the probe observes what the owner emits rather than filtering by level.

func (RawLogHandler) Handle

func (handler RawLogHandler) Handle(ctx context.Context, record slog.Record) error

Handle invokes the observer callback with the emitted record.

func (RawLogHandler) WithAttrs

func (handler RawLogHandler) WithAttrs([]slog.Attr) slog.Handler

WithAttrs returns the same raw observer, discarding the supplied attributes.

func (RawLogHandler) WithGroup

func (handler RawLogHandler) WithGroup(string) slog.Handler

WithGroup returns the same raw observer, discarding the group name.

type ReceiverNaming

type ReceiverNaming uint8

ReceiverNaming selects whether a syntax identity includes pointer markers.

const (
	// ReceiverWithPointers preserves pointer markers in declaration identities.
	ReceiverWithPointers ReceiverNaming = iota
	// ReceiverBaseName names the underlying type for admission dependency lookup.
	ReceiverBaseName
)

type RoundTripperFunc

type RoundTripperFunc func(*http.Request) (*http.Response, error)

RoundTripperFunc adapts a fixture callback to http.RoundTripper without a separate transport type. The callback owns request and response semantics.

func (RoundTripperFunc) RoundTrip

func (f RoundTripperFunc) RoundTrip(request *http.Request) (*http.Response, error)

RoundTrip delegates the request unchanged to the fixture callback.

type StoreBoundary

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

StoreBoundary checks a whole package after all test cleanups have run. A package boundary avoids counting another parallel test's live fixtures as leaks. It observes stores independently of constructor names and return values.

func BeginStoreBoundary

func BeginStoreBoundary() StoreBoundary

BeginStoreBoundary records the starting population before testing.M.Run.

func (StoreBoundary) Check

func (boundary StoreBoundary) Check(code int, output io.Writer, name string) int

Check preserves a failed test exit code and also rejects leaked stores. Call it before disposing any deliberate process-lifetime negative control.

type ZeroRowCorrelatedCallCase

type ZeroRowCorrelatedCallCase struct {
	Params map[string]any
	Want   int
}

ZeroRowCorrelatedCallCase is one transport-independent population of the correlated CALL query fixtures: the statement parameters plus the number of subjects, subject versions and carried ids the ungrouped aggregation must return.

func ZeroRowCorrelatedCallCaseFor

func ZeroRowCorrelatedCallCaseFor(populated bool) ZeroRowCorrelatedCallCase

ZeroRowCorrelatedCallCaseFor builds the shared parameters for an empty or populated $active/$items stream and the cardinality the aggregation must return for it.

Directories

Path Synopsis
Package relatedgraph builds shared related-node benchmark populations.
Package relatedgraph builds shared related-node benchmark populations.
Package remotequery provides shared test instrumentation for remote query engines.
Package remotequery provides shared test instrumentation for remote query engines.
Package storagefault supports shared storage admission and publication fault fixtures using real engines.
Package storagefault supports shared storage admission and publication fault fixtures using real engines.
Package temporalguide runs the published temporal examples through test-owned query adapters.
Package temporalguide runs the published temporal examples through test-owned query adapters.

Jump to

Keyboard shortcuts

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