natsfixture

package
v0.1.0-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package natsfixture gives one test one disposable, real NATS server in a container (openspec change setup-02-isolated-harness, capability nats-fixture). The pattern is adapted from SemStreams natsclient/test_client.go at 5457b345 (ledger row L1) over nats.go and testcontainers-go directly, without its eleven caller knobs (ledger row L2).

Start succeeds only after JetStream answers; Stop closes the connection and removes the container, which removes everything in it. Test-only: contract test T-B1 refuses any production import.

Index

Constants

This section is empty.

Variables

View Source
var ErrAlreadyUsed = errors.New("natsfixture: fixture already started; use Restart to restart its container")

ErrAlreadyUsed is returned by a second Start. A fixture is one container's lifetime: Restart stops and starts that same container, and a second Start never creates another.

Functions

func CreateStream

func CreateStream(ctx context.Context, js jetstream.JetStream, storage jetstream.StorageType, name string, subjects ...string) (jetstream.Stream, error)

CreateStream creates a stream on js with the given storage, a MaxAge of one hour, a MaxBytes of 64 MiB and DiscardOld. On a fixture, a file-backed stream keeps its messages across Restart and a memory-backed one does not; Stop's removal of the container removes both.

func Open

func Open[T any](t testing.TB, url string, open func(ctx context.Context, url string) (T, func(context.Context) error, error)) T

Open gives a package's tests a value connected to a NATS server URL, such as a client built with that package's own options (nats-fixture › "Connected value for a package's tests"). It calls open with url under a bounded context derived from the test's, and returns the value. When open fails, Open fails the test naming the URL and the error and registers nothing; open releases whatever it acquired before failing. On success it registers close on the test's cleanup under a fresh bounded context, reporting a close error as a test error.

Cleanups run last-registered first, so close runs before the connection check that Shared.Reset registered and before the Stop that New registered: call Open after Reset or New. Open starts no goroutine and imports nothing of this module outside internal/harness, so a package under test can use it without an import cycle.

Types

type FaultKV

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

FaultKV wraps a real bucket so that Put, Create, Update and Delete can fail before the real call (nothing happens on the server) or after it (the write stands and the caller still sees an error, the "server applied it, client saw an error" case). PutString is a Put. Every other method, Purge included, reaches the real bucket unchanged. A fault stays set until cleared with a nil error. It is typed on jetstream.KeyValue only, so natsfixture imports no package of this module outside internal/harness.

func NewFaultKV

func NewFaultKV(bucket jetstream.KeyValue) *FaultKV

NewFaultKV wraps bucket with no fault set.

func (*FaultKV) Calls

func (k *FaultKV) Calls() map[KVOp]int

Calls reports how many real calls each operation made, in a map the caller owns.

func (*FaultKV) Create

func (k *FaultKV) Create(ctx context.Context, key string, value []byte, opts ...jetstream.KVCreateOpt) (uint64, error)

Create writes through to the real bucket unless KVCreate is faulted.

func (*FaultKV) Delete

func (k *FaultKV) Delete(ctx context.Context, key string, opts ...jetstream.KVDeleteOpt) error

Delete writes through to the real bucket unless KVDelete is faulted.

func (*FaultKV) FailAfter

func (k *FaultKV) FailAfter(op KVOp, err error)

FailAfter makes op call the real bucket, discard its result, and return err. A nil err clears op's fault.

func (*FaultKV) FailBefore

func (k *FaultKV) FailBefore(op KVOp, err error)

FailBefore makes op return err without calling the real bucket. A nil err clears op's fault.

func (*FaultKV) Put

func (k *FaultKV) Put(ctx context.Context, key string, value []byte) (uint64, error)

Put writes through to the real bucket unless KVPut is faulted.

func (*FaultKV) PutString

func (k *FaultKV) PutString(ctx context.Context, key string, value string) (uint64, error)

PutString is Put, so a KVPut fault applies to it too.

func (*FaultKV) Update

func (k *FaultKV) Update(ctx context.Context, key string, value []byte, revision uint64) (uint64, error)

Update writes through to the real bucket unless KVUpdate is faulted.

type Fixture

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

Fixture is one test's NATS server. Its methods are called from the test's own goroutine. It holds no context.Context.

func New

func New(t testing.TB, opts ...Option) *Fixture

New binds a fixture to its test and registers a Stop, under fresh bounded authority, as the test's cleanup. It makes no Docker call.

func (*Fixture) JetStream

func (f *Fixture) JetStream() jetstream.JetStream

JetStream is the JetStream context on the fixture's own connection, which Stop closes; there is deliberately no accessor for that connection. Tests needing a connection of their own dial URL and close it themselves. Stop does not wait for in-flight async publishes.

func (*Fixture) Restart

func (f *Fixture) Restart(ctx context.Context) error

Restart stops and starts the fixture's own container and reconnects to it, under ctx. The container's writable layer survives, so a file-backed stream keeps its messages and a memory-backed one does not.

Before the container stops, the fixture's connection is drained, so the JetStream context and any stream, bucket or consumer handle taken from it before the restart are dead. Streams and buckets stay on the server; Stop's removal of the container removes them.

URL and JetStream return the new binding once Restart returns nil, and stay valid until the next Restart. The host port is the one Start gave Docker, and URL has stayed unchanged in every run so far (TestRestartURLDials; Docker does not promise it), but every connection to the container is lost. A caller stops what it built on the URL before Restart and starts it again after.

Restart refuses, with no Docker call, before a successful Start and once Stop has begun. A failure in a phase returns an error naming it; nothing is tried again and no replacement container is created. After a failure the fixture can no longer be restarted, and Stop removes the container.

The caller must bound ctx. Readiness after the start is one more ready line in the container's log than before it; if Docker log rotation drops earlier lines the count can fall, and the wait then runs until ctx ends and fails at the start-container phase.

func (*Fixture) Start

func (f *Fixture) Start(ctx context.Context) error

Start starts one NATS container with JetStream from the pinned image, connects, and returns once JetStream answers. Every operation runs under ctx. A failure returns an error naming the phase (phaseError lists them), after removing whatever Start created; no second container is started. A second Start returns ErrAlreadyUsed.

func (*Fixture) Stop

func (f *Fixture) Stop(ctx context.Context) error

Stop closes the fixture's connection and removes its container, under the caller's context. Removing the container removes every stream, bucket and consumer in it, so Stop deletes none of them first and needs no answer from the server. Once Stop begins the fixture holds no connection, so it creates nothing more and Restart refuses.

Stop returns nil only when Docker reported the container removed. If ctx ends first, or the removal fails, Stop returns the error and keeps what it has not released; a later Stop retries. The fixture never substitutes its own timeout for ctx. Stop on a fixture with nothing held (never started, a start that rolled back cleanly, or already stopped) returns nil without any call.

func (*Fixture) URL

func (f *Fixture) URL() string

URL is the broker's client URL, on the host port the start phase picked (freePort); Restart keeps it.

type KVOp

type KVOp string

KVOp names a key-value write FaultKV can fail.

const (
	KVPut    KVOp = "put"
	KVCreate KVOp = "create"
	KVUpdate KVOp = "update"
	KVDelete KVOp = "delete"
)

The four writes FaultKV can fail.

type Option

type Option func(*Fixture)

Option configures a fixture's broker; New applies it before any Docker call.

func WithMaxPayload

func WithMaxPayload(n int64) Option

WithMaxPayload starts the broker with max_payload set to n bytes, so a test can reach a payload bound without building a megabyte message. Without it the broker's own default applies. Start refuses an n below 1 before any Docker call.

type Shared

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

Shared is one package's NATS server, started at the first Reset and removed by TestMain's Stop (nats-fixture › "Shared server per package", "Reset to a verified-empty server"). It retains no context.Context. The zero value is ready to use.

func (*Shared) Reset

func (s *Shared) Reset(t testing.TB) string

Reset starts the shared server on its first call, empties it, verifies it holds no stream, consumer, stored byte or other client connection, registers a post-test connection check on t's cleanup, and returns the server's client URL.

func (*Shared) Stop

func (s *Shared) Stop(ctx context.Context) error

Stop removes the shared server's container when it started, and returns nil without a Docker call when it did not.

Jump to

Keyboard shortcuts

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