helpers

package
v0.0.1-alpha.2 Latest Latest
Warning

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

Go to latest
Published: Jul 12, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Assert

func Assert(t *testing.T) *assert.Assertions

Assert returns a testify Assertions value that calls t.Fail on failure.

func AssertHeader

func AssertHeader(t *testing.T, resp *http.Response, header, value string)

AssertHeader fails the test if the named header is not present or doesn't match value. Pass an empty value string to just assert presence.

func AssertJSONError

func AssertJSONError(t *testing.T, resp *http.Response, expectedCode string)

AssertJSONError decodes the response as a JSON error and checks the error code.

func AssertRequestID

func AssertRequestID(t *testing.T, resp *http.Response)

AssertRequestID fails the test if x-amzn-requestid or x-amz-request-id is missing.

func AssertStatus

func AssertStatus(t *testing.T, resp *http.Response, expected int)

AssertStatus fails the test if the response status code doesn't match expected.

func AssertXMLError

func AssertXMLError(t *testing.T, resp *http.Response, expectedCode string)

AssertXMLError decodes the response as an XML error and checks the error code.

func DecodeJSON

func DecodeJSON(t *testing.T, resp *http.Response, v any)

DecodeJSON decodes the response body into v and fails the test on error.

func DecodeXML

func DecodeXML(t *testing.T, resp *http.Response, v any)

DecodeXML decodes the response body into v and fails the test on error.

func Eventually

func Eventually(t *testing.T, timeout, interval time.Duration, fn func() bool, msg string)

Eventually retries fn every interval until it returns true or timeout elapses. Calls t.Fatal with msg if the deadline is reached without success.

func NewHTTPBackend

func NewHTTPBackend(t *testing.T, handler http.HandlerFunc) *httptest.Server

NewHTTPBackend starts a throwaway HTTP server with the given handler. The server is closed automatically when the test ends.

func ReadBody

func ReadBody(t *testing.T, resp *http.Response) string

ReadBody reads and returns the response body as a string.

func Require

func Require(t *testing.T) *require.Assertions

Require returns a testify Assertions value that calls t.FailNow on failure.

Types

type MockStore

type MockStore struct {

	// Recorded calls — inspect these in tests to assert behaviour.
	GetCalls    []StoreCall
	SetCalls    []StoreCall
	DeleteCalls []StoreCall
	ListCalls   []StoreCall

	// Errors to inject — set these to simulate failures.
	GetError    error
	SetError    error
	DeleteError error
	ListError   error
	// contains filtered or unexported fields
}

MockStore is a hand-written test double for state.Store. Use it in unit tests that need to isolate a component from real storage.

It records all calls so tests can assert on what was called, in what order, with what arguments.

Example:

mock := helpers.NewMockStore()
mock.SetData("s3:buckets", "my-bucket", `{"name":"my-bucket"}`)
// ... inject mock into component under test ...
if len(mock.SetCalls) != 1 { t.Error("expected one Set call") }

func NewMockStore

func NewMockStore() *MockStore

NewMockStore returns an initialised MockStore.

func (*MockStore) Close

func (m *MockStore) Close() error

func (*MockStore) Delete

func (m *MockStore) Delete(_ context.Context, namespace, key string) error

func (*MockStore) Get

func (m *MockStore) Get(_ context.Context, namespace, key string) (string, bool, error)

func (*MockStore) List

func (m *MockStore) List(_ context.Context, namespace, prefix string) ([]string, error)

func (*MockStore) Reset

func (m *MockStore) Reset()

Reset clears all stored data and recorded calls.

func (*MockStore) Scan

func (m *MockStore) Scan(_ context.Context, namespace, prefix string) ([]state.KV, error)

Scan returns key-value pairs matching the prefix (implements state.Store).

func (*MockStore) Set

func (m *MockStore) Set(_ context.Context, namespace, key, value string) error

func (*MockStore) SetData

func (m *MockStore) SetData(namespace, key, value string)

SetData pre-populates the mock with a value, without recording a SetCall. Use this in the Given section of tests to set up initial state.

type Option

type Option func(*serverOptions)

Option is a functional option for configuring the test server. Use the With* constructors rather than crafting values directly.

func WithAccountID

func WithAccountID(id string) Option

WithAccountID overrides the fake AWS account ID used in ARNs.

func WithDataDir

func WithDataDir(dir string) Option

WithDataDir sets the data directory for on-disk state (e.g. S3 body files). If not set, a temporary directory is used automatically.

func WithDebug

func WithDebug(enabled bool) Option

WithDebug enables the /_debug/* endpoint namespace on the test server.

func WithEC2VPCStrategy

func WithEC2VPCStrategy(strategy string) Option

WithEC2VPCStrategy sets the VPC network strategy used by the EC2 service. Valid values: "shared" (default), "strict", "remapped". See docs/plans/ec2-vpc-network-strategies.md for details.

func WithEKSMode

func WithEKSMode(mode config.EKSMode) Option

WithEKSMode sets the EKS service mode used by the test server.

func WithEnforceIAM

func WithEnforceIAM(enabled bool) Option

WithEnforceIAM enables opt-in IAM authorization enforcement middleware.

func WithHostname

func WithHostname(hostname string) Option

WithHostname sets the external hostname used in client-facing URLs.

func WithInitRunner

func WithInitRunner(r *inithooks.Runner) Option

WithInitRunner injects an init hook runner into the test server so the /_overcast/init status endpoint reports its state.

func WithLambdaDocker

func WithLambdaDocker() Option

WithLambdaDocker enables Docker-backed Lambda execution on the test server. By default, test servers skip the Docker probe entirely (stub runtime only) to avoid 1000+ unnecessary Docker daemon round-trips across the test suite. Use this option for tests that invoke real Lambda container runtimes.

TODO(perf): For Approach B — share a single Docker client, RuntimeAPI server, and InstancePool across all test servers in a package via a package-level sync.Once. This would enable warm-container reuse across tests and further reduce Docker daemon pressure. Wire shared runtime via a new lambda.WithSharedRuntime(...) service option instead of each server probing independently.

func WithLambdaHotReload

func WithLambdaHotReload() Option

WithLambdaHotReload enables bind-mount-based Lambda hot reload. Functions must still opt in via the overcast:hot-reload-path tag.

func WithMockClock

func WithMockClock() Option

WithMockClock injects a manually-controlled clock into all services on the test server. Access srv.Clock to advance time without real sleeps:

srv := helpers.NewTestServer(t, helpers.WithMockClock())
srv.Clock.Add(35 * time.Second) // visibility timeout expires instantly

func WithRegion

func WithRegion(region string) Option

WithRegion overrides the AWS region reported in ARNs and responses.

func WithSMTPMock

func WithSMTPMock() Option

WithSMTPMock enables the built-in SMTP capture server on a random port. Emails delivered to SNS email/email-json subscribers are captured and accessible via GET /_overcast/inbox/messages on the test server.

func WithServiceStates

func WithServiceStates(states map[string]config.StateBackend) Option

WithServiceStates sets per-service storage backend overrides.

func WithServices

func WithServices(services ...string) Option

WithServices restricts which services are enabled. Useful for testing that disabled services return 404/501 correctly.

func WithSigV4Validate

func WithSigV4Validate(enabled bool) Option

WithSigV4Validate enables or disables SigV4 signature validation for the test server. When enabled, unsigned requests and requests with invalid signatures are rejected with a 403. Default is false.

func WithStore

func WithStore(s state.Store) Option

WithStore injects a specific Store implementation (e.g. SQLiteStore). By default the server uses an in-memory store.

type StoreCall

type StoreCall struct {
	Namespace string
	Key       string
	Value     string // only set for Set calls
	Prefix    string // only set for List calls
}

StoreCall records a single call to a store method.

type TestServer

type TestServer struct {
	*httptest.Server
	// Store is exposed so tests can inspect or pre-populate state directly
	// when needed. Prefer HTTP setup helpers (createBucket, createQueue etc.)
	// over direct store access wherever possible.
	Store  *state.MemoryStore
	Config *config.Config
	// Clock is the mock clock injected into all services on this server.
	// It is only set when WithMockClock() is passed to NewTestServer;
	// for real-clock servers it is nil.
	// Use Clock.Add(d) to advance time without any real sleep.
	Clock *clock.Mock
}

TestServer wraps httptest.Server with a pre-configured emulator instance. Each test receives a fresh server with empty in-memory state — isolation is guaranteed without any setup/teardown ceremony.

func NewTestServer

func NewTestServer(t *testing.T, opts ...Option) *TestServer

NewTestServer creates a started test server with sensible defaults. The server is automatically closed when the test ends via t.Cleanup.

Example — basic usage:

srv := helpers.NewTestServer(t)

Example — with options:

srv := helpers.NewTestServer(t,
    helpers.WithServices("s3"),
    helpers.WithRegion("eu-west-1"),
    helpers.WithMockClock(),
)

Example — advancing time in a test:

srv := helpers.NewTestServer(t, helpers.WithMockClock())
srv.Clock.Add(35 * time.Second) // instant — no real sleep

func (*TestServer) Reset

func (ts *TestServer) Reset()

Reset wipes all state on the server. Useful when a test wants to verify behaviour starting from a clean slate mid-test without creating a new server.

Jump to

Keyboard shortcuts

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