Documentation
¶
Overview ¶
Package testfixture owns test resources without importing their packages.
Index ¶
- Constants
- func Append[T any](owner *sync.Mutex, values *[]T, value T)
- func AssertZeroRowCorrelatedCallRows(t *testing.T, rows [][]any, testCase ZeroRowCorrelatedCallCase)
- func CachedStorage[T comparable](t testing.TB, lookup func() (T, error)) T
- func CurrentGoroutineID() uint64
- func Encode[T any](owner EncodingOwner, encode func(T) ([]byte, error), value T) []byte
- func ExtractZip(t *testing.T, archivePath, trimPrefix string) string
- func InstallTracerProvider(t testing.TB, provider *sdktrace.TracerProvider, ...) func()
- func NamespaceTransaction[T interface{ ... }, R comparable](t testing.TB, begin func(context.Context, R) (T, error), request R, ...) T
- func NestedGraphProperties(index int) map[string]interface{}
- func ObserveHookSignal(owner interface{ ... }, install func(func()) func(), capacity int) <-chan struct{}
- func OpenStores() (int, string)
- func Own[T Closer](owner Owner, resource T, before ...Closer) T
- func OwnChecked[T Closer](owner CheckedOwner, resource T, before ...Closer) T
- func OwnResult[T Closer](owner Owner, closedError error) func(T, error) (T, error)
- func OwnResult3[T Closer, U any](owner Owner, closedError error) func(T, U, error) (T, U, error)
- func OwnWithCloseAssertion[T Closer](owner Owner, resource T, assertion func(error) bool, before ...Closer) T
- func ReadWithFailure[T any](ctx context.Context, fault error, read func(context.Context) (T, error)) (T, error)
- func ReceiverName(expression ast.Expr, naming ReceiverNaming) string
- func RecordSpans(t testing.TB) (*tracetest.InMemoryExporter, func())
- func RequireFloat32Vector(t testing.TB, name string, actual []float32, dimensions int, ...)
- func RequireMarkersAbsent(t interface{ ... }, text string, markers ...string)
- func Run(m *testing.M, name string) int
- func RunCatalogDropCycles(t testing.TB, count int, prefix string, create, use, drop func(string) error)
- func Snapshot[T any](owner *sync.Mutex, values *[]T) []T
- func SpanAttrs(attributes []attribute.KeyValue) map[string]string
- func Track[T Closer](owner Owner, resource T, closedError error) T
- func TrackProcess[T Closer](owner *Boundary, resource T, closedError error) T
- func TrackResult[T Closer](owner Owner, closedError error) func(T, error) (T, error)
- func WaitForBarrier(t interface{ ... }, ready <-chan struct{}, timeout time.Duration, ...)
- func WalkRepositoryTree(root string, visit fs.WalkDirFunc) error
- type AlwaysEnabled
- type Boundary
- type CheckedOwner
- type CheckpointContext
- type Closer
- type EncodingOwner
- type EncryptionPropertyCase
- type ErrorWriter
- type FixedBatchEmbedding2D
- type FixedEmbedding2D
- type Owner
- type PauseGate
- type QueryReadObserver
- func (o *QueryReadObserver) Access(_ context.Context, kind, detail string) *queryprofile.ReadCounter
- func (o *QueryReadObserver) Callbacks() []string
- func (o *QueryReadObserver) Reads(kind, detail string) (rows, hits int64, recorded bool)
- func (o *QueryReadObserver) RecordedKinds() []string
- func (o *QueryReadObserver) UnobservedRead(_ context.Context, category, name string)
- func (o *QueryReadObserver) WithLifetime(lifetime context.Context, _ context.Context) context.Context
- type RawLogHandler
- type ReceiverNaming
- type RoundTripperFunc
- type StoreBoundary
- type ZeroRowCorrelatedCallCase
Constants ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
OwnResult registers and closes an error-returning fixture at its real test boundary. Constructor errors and concrete resources are returned unchanged.
func OwnResult3 ¶
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 ¶
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 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 ¶
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 ¶
SpanAttrs projects recorded attributes to the canonical string values used by span contract assertions. Callers select their recorder's attribute slice.
func Track ¶
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 ¶
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 ¶
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 ¶
Close runs the registered fixture cleanups after the boundary's checks and returns their failures.
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 ¶
EncodingOwner is the fatal assertion boundary supplied by testing.T or B.
type EncryptionPropertyCase ¶
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 ¶
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.
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 ¶
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.
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 (*PauseGate) Pause ¶
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 ¶
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.
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 ¶
RoundTripperFunc adapts a fixture callback to http.RoundTripper without a separate transport type. The callback owns request and response semantics.
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.
type ZeroRowCorrelatedCallCase ¶
type ZeroRowCorrelatedCallCase struct {
}
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.
Source Files
¶
- always_enabled.go
- append.go
- archive.go
- barrier.go
- cached_storage.go
- catalog_cycles.go
- checkpoint.go
- encoding.go
- encryption_properties.go
- error_writer.go
- fixed_embedding.go
- fixture.go
- goroutine.go
- hook_signal.go
- http_transport.go
- lifetime.go
- markers.go
- namespace_transaction.go
- nested_graph_properties.go
- pause_gate.go
- query_profile.go
- raw_log_handler.go
- read_fault.go
- receiver_name.go
- repository_tree.go
- snapshot.go
- span_attributes.go
- store_boundary.go
- tracing.go
- vector_assert.go
- zero_row_correlated_call.go
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. |