testing

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 24, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package testing provides in-memory port implementations and deterministic test helpers for exercising the anyhook core Engine without real infrastructure: a controllable Clock, a seeded Rng, an in-memory Transport / StateStore / Scheduler, a scriptable mock HTTP receiver, and a harness that drives the in-memory delivery loop to quiescence. Mirrors packages/testing in the TypeScript implementation.

The package is named "testing" to mirror the TS @anyhook/testing package and this module's sibling anyq/go layout. Consumers that also need the standard library testing package in the same file should import this package under an alias, e.g. `anyhooktesting "github.com/sns45/anyhook/go/testing"`.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func RunDeliveries

func RunDeliveries(ctx context.Context, opts RunOptions) error

RunDeliveries repeatedly drains the transport, then jumps the clock to the next scheduled retry and releases it, until nothing is queued or scheduled. This is the in-memory analogue of a worker plus the durable scheduler firing over time. Returns an error if MaxRounds is exceeded.

func SeededRng

func SeededRng(seed uint32) core.Rng

SeededRng returns a deterministic LCG-backed Rng in [0, 1). A seed of 0 maps to 1 (matching the TS `seed >>> 0 || 1` fallback, since 0 is falsy in JS).

Types

type MemoryScheduler

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

MemoryScheduler records scheduled retries and re-enqueues them onto the transport once due. Embodies "the state store is the schedule": a message is re-delivered only after the clock reaches its scheduled time.

func NewMemoryScheduler

func NewMemoryScheduler(transport *MemoryTransport, clock *TestClock) *MemoryScheduler

NewMemoryScheduler builds a MemoryScheduler driven by clock and re-enqueuing onto transport.

func (*MemoryScheduler) Advance

func (s *MemoryScheduler) Advance(ctx context.Context) (int, error)

Advance re-enqueues every message whose scheduled time is <= now. Returns the count released.

func (*MemoryScheduler) NextDueAt

func (s *MemoryScheduler) NextDueAt() (int64, bool)

NextDueAt returns the earliest scheduled time still pending, and true, or (0, false) when empty.

func (*MemoryScheduler) ScheduleRetry

func (s *MemoryScheduler) ScheduleRetry(_ context.Context, m core.Message, at int64) error

ScheduleRetry implements core.Scheduler.

func (*MemoryScheduler) Size

func (s *MemoryScheduler) Size() int

Size returns the number of still-pending scheduled retries.

type MemoryStateStore

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

MemoryStateStore is an in-memory, tenant-scoped StateStore. Every read/write is keyed by tenant first, so no query can ever observe another tenant's rows (the cross-tenant no-leak invariant, G7).

func NewMemoryStateStore

func NewMemoryStateStore(clock core.Clock) *MemoryStateStore

NewMemoryStateStore builds an empty MemoryStateStore. clock may be nil (falls back to wall time).

func (*MemoryStateStore) AddToDlq

func (s *MemoryStateStore) AddToDlq(_ context.Context, m core.Message, reason core.DlqReason) error

AddToDlq implements core.StateStore.

func (*MemoryStateStore) AppendAttempt

func (s *MemoryStateStore) AppendAttempt(_ context.Context, a core.Attempt) error

AppendAttempt implements core.StateStore.

func (*MemoryStateStore) CreateEndpoint

CreateEndpoint implements core.StateStore.

func (*MemoryStateStore) DeleteEndpoint

func (s *MemoryStateStore) DeleteEndpoint(_ context.Context, tenant, endpointID string) error

DeleteEndpoint implements core.StateStore.

func (*MemoryStateStore) FinalizeEvent

func (s *MemoryStateStore) FinalizeEvent(_ context.Context, tenant, idemKey, eventID string, messageCount int) error

FinalizeEvent implements core.StateStore.

func (*MemoryStateStore) GetCircuit

func (s *MemoryStateStore) GetCircuit(_ context.Context, tenant, endpointID string) (core.CircuitRecord, error)

GetCircuit implements core.StateStore.

func (*MemoryStateStore) GetEndpoint

func (s *MemoryStateStore) GetEndpoint(_ context.Context, tenant, endpointID string) (*core.Endpoint, error)

GetEndpoint implements core.StateStore.

func (*MemoryStateStore) GetMessage

func (s *MemoryStateStore) GetMessage(_ context.Context, tenant, messageID string) (*core.Message, error)

GetMessage implements core.StateStore.

func (*MemoryStateStore) GetRateBucket

func (s *MemoryStateStore) GetRateBucket(_ context.Context, tenant, endpointID string) (*core.RateBucket, error)

GetRateBucket implements core.StateStore.

func (*MemoryStateStore) ListDeliveries

func (s *MemoryStateStore) ListDeliveries(_ context.Context, q core.DeliveryQuery) ([]core.DeliveryRow, error)

ListDeliveries implements core.StateStore.

func (*MemoryStateStore) ListDlq

func (s *MemoryStateStore) ListDlq(_ context.Context, tenant, endpointID string) ([]core.DlqEntry, error)

ListDlq implements core.StateStore.

func (*MemoryStateStore) ListEndpoints

func (s *MemoryStateStore) ListEndpoints(_ context.Context, tenant string) ([]core.Endpoint, error)

ListEndpoints implements core.StateStore.

func (*MemoryStateStore) MatchEndpoints

func (s *MemoryStateStore) MatchEndpoints(_ context.Context, tenant, eventType string) ([]core.Endpoint, error)

MatchEndpoints implements core.StateStore.

func (*MemoryStateStore) PutCircuit

func (s *MemoryStateStore) PutCircuit(_ context.Context, tenant, endpointID string, rec core.CircuitRecord) error

PutCircuit implements core.StateStore.

func (*MemoryStateStore) PutMessage

func (s *MemoryStateStore) PutMessage(_ context.Context, m core.Message) error

PutMessage implements core.StateStore.

func (*MemoryStateStore) PutRateBucket

func (s *MemoryStateStore) PutRateBucket(_ context.Context, tenant, endpointID string, bucket core.RateBucket) error

PutRateBucket implements core.StateStore.

func (*MemoryStateStore) RecordEvent

func (s *MemoryStateStore) RecordEvent(_ context.Context, tenant, eventID, idemKey string) (core.EventRecordResult, error)

RecordEvent implements core.StateStore.

func (*MemoryStateStore) RotateSecret

func (s *MemoryStateStore) RotateSecret(_ context.Context, tenant, endpointID string) (string, error)

RotateSecret implements core.StateStore. Keeps the previous primary secret valid during a dual-secret rotation window.

func (*MemoryStateStore) UpdateEndpoint

func (s *MemoryStateStore) UpdateEndpoint(_ context.Context, tenant, endpointID string, patch core.UpdateEndpointPatch) (core.Endpoint, error)

UpdateEndpoint implements core.StateStore.

type MemoryTransport

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

MemoryTransport is an in-process FIFO transport (anyq stand-in) for tests. Send enqueues; Drain invokes the subscribed handler for every queued message (including any enqueued while draining).

func NewMemoryTransport

func NewMemoryTransport() *MemoryTransport

NewMemoryTransport builds an empty MemoryTransport.

func (*MemoryTransport) Drain

func (t *MemoryTransport) Drain(ctx context.Context) (int, error)

Drain processes all currently-queued messages (and any enqueued during processing). Returns the count processed.

func (*MemoryTransport) Send

Send implements core.Transport.

func (*MemoryTransport) Size

func (t *MemoryTransport) Size() int

Size returns the number of currently-queued messages.

func (*MemoryTransport) Subscribe

func (t *MemoryTransport) Subscribe(_ context.Context, handler func(ctx context.Context, m core.Message) error) error

Subscribe implements core.Transport.

type MockReceiver

type MockReceiver struct {
	Default Script
	Calls   []RecordedCall
	// contains filtered or unexported fields
}

MockReceiver is a deterministic HTTPClient shim. Route a URL to a Script with On (unrouted URLs use Default). ReceiverSlow(ms) returns a timeout iff ms > timeoutMs. Every call is recorded for assertions (headers/body/order/count).

func NewMockReceiver

func NewMockReceiver(clock core.Clock) *MockReceiver

NewMockReceiver builds a MockReceiver whose Default script is ReceiverOK. clock may be nil (call timestamps then default to 0).

func (*MockReceiver) CallCount

func (r *MockReceiver) CallCount(url string) int

CallCount returns the total number of calls, or the count for url if given (non-empty).

func (*MockReceiver) On

func (r *MockReceiver) On(url string, script Script) *MockReceiver

On routes url to script. Returns the receiver for chaining.

func (*MockReceiver) Post

func (r *MockReceiver) Post(_ context.Context, url string, body string, headers map[string]string, timeoutMs int64) core.HTTPResult

Post implements core.HTTPClient.

type RecordedCall

type RecordedCall struct {
	URL     string
	Body    string
	Headers map[string]string
	Ts      int64
}

RecordedCall is one recorded MockReceiver.Post invocation.

type RunOptions

type RunOptions struct {
	Transport *MemoryTransport
	Scheduler *MemoryScheduler
	Clock     *TestClock
	// MaxRounds caps delivery rounds (defends against a non-converging
	// schedule). 0 means the default (200).
	MaxRounds int
}

RunOptions configure RunDeliveries.

type Script

type Script struct {
	Kind ScriptKind
	// Status is used by ScriptPermanent (an HTTP status code).
	Status int
	// N is used by ScriptFailThenOK: the number of 500s before succeeding.
	N int
	// Ms is used by ScriptSlow: the simulated response time.
	Ms int64
}

Script is one scripted response for a routed URL.

func ReceiverFailThenOK

func ReceiverFailThenOK(n int) Script

ReceiverFailThenOK scripts n consecutive 500s, then 200.

func ReceiverNetwork

func ReceiverNetwork() Script

ReceiverNetwork scripts a network failure on every call.

func ReceiverOK

func ReceiverOK() Script

ReceiverOK scripts an immediate 200.

func ReceiverPermanent

func ReceiverPermanent(status int) Script

ReceiverPermanent scripts a non-retryable status (default 404).

func ReceiverSlow

func ReceiverSlow(ms int64) Script

ReceiverSlow scripts a response that takes ms to arrive; it becomes a timeout if ms exceeds the caller's timeoutMs.

func ReceiverTimeout

func ReceiverTimeout() Script

ReceiverTimeout scripts a timeout on every call.

type ScriptKind

type ScriptKind int

ScriptKind selects a MockReceiver behavior.

const (
	ScriptOK ScriptKind = iota
	ScriptPermanent
	ScriptFailThenOK
	ScriptTimeout
	ScriptNetwork
	ScriptSlow
)

type TestClock

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

TestClock is a Clock whose time only advances when the test tells it to. It is safe for concurrent use so it can back the engine under parallel workers.

func NewTestClock

func NewTestClock(start int64) *TestClock

NewTestClock builds a TestClock starting at the given epoch-ms time.

func (*TestClock) Now

func (c *TestClock) Now() int64

Now implements core.Clock.

func (*TestClock) Set

func (c *TestClock) Set(ms int64) int64

Set jumps to an absolute time. Never moves backwards.

func (*TestClock) Tick

func (c *TestClock) Tick(ms int64) int64

Tick advances the clock by ms and returns the new time.

Jump to

Keyboard shortcuts

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