testhelpers

package
v0.0.0-...-0b8e112 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2026 License: MIT Imports: 24 Imported by: 0

Documentation

Overview

Package testhelpers provides common testing utilities and helpers shared across the go-atlas project.

The package includes:

All helpers that accept testing.TB register cleanup functions automatically, so callers do not need to manage teardown manually.

Index

Constants

This section is empty.

Variables

View Source
var ErrMockMissing = errors.New("no cache found")

ErrMockMissing is a sentinel returned by MockCacheProvider.Get when a key is not present in the in-memory store. Tests should match against this value the same way they would match providers.ErrMissing in production code.

Functions

func ConnectJetStream

func ConnectJetStream(tb testing.TB, ns *server.Server) (*nats.Conn, jetstream.JetStream)

ConnectJetStream connects to the NATS server and returns both the underlying nats.Conn and a jetstream.JetStream handle. It calls ConnectNATS internally, so the connection is cleaned up automatically.

func ConnectNATS

func ConnectNATS(tb testing.TB, ns *server.Server) *nats.Conn

ConnectNATS connects to the given NATS server and returns the connection. The connection is closed automatically via tb.Cleanup.

func CreateNATSKV

func CreateNATSKV(tb testing.TB, js jetstream.JetStream, bucket string, ttl time.Duration) jetstream.KeyValue

CreateNATSKV creates a NATS JetStream KeyValue bucket backed by in-memory storage.

func GenerateRSAKey

func GenerateRSAKey(tb testing.TB, bits int) *rsa.PrivateKey

GenerateRSAKey generates an RSA private key of the given bit size for testing.

func GenerateRSAKeyPEM

func GenerateRSAKeyPEM(tb testing.TB, bits int) []byte

GenerateRSAKeyPEM generates an RSA private key and returns it as PKCS#8 PEM-encoded bytes.

func IntPtr

func IntPtr(i int) *int

IntPtr returns a pointer to the given int.

func NewTestAuditor

func NewTestAuditor(tb testing.TB, opts ...audit.Option) (*audit.Auditor, *memory.Storage)

NewTestAuditor creates an audit.Auditor backed by memory.Storage for testing. It applies test-friendly defaults (50ms flush interval, 1 worker, batch size 1) before appending any caller-supplied opts, so callers can override individual settings. The auditor is started before returning and shut down automatically via tb.Cleanup.

func SelfSignedCert

func SelfSignedCert(tb testing.TB) (certPEM, keyPEM []byte, cert tls.Certificate)

SelfSignedCert generates a CA-signed leaf TLS certificate for testing with no OCSP servers configured. It delegates to SelfSignedCertWithOCSP.

func SelfSignedCertWithOCSP

func SelfSignedCertWithOCSP(tb testing.TB, ocspServers []string) (certPEM, keyPEM []byte, cert tls.Certificate)

SelfSignedCertWithOCSP generates a CA-signed leaf TLS certificate with optional OCSP server URLs. It creates a short-lived CA and a leaf certificate valid for "localhost". Both certificates are pre-dated by 1 hour (to tolerate clock skew) and valid for 24 hours. The returned tls.Certificate contains the full chain (leaf + CA).

func StartNATSServer

func StartNATSServer(tb testing.TB) *server.Server

StartNATSServer starts an embedded NATS server with JetStream enabled for testing. The server binds to a random port on 127.0.0.1 and uses tb.TempDir for JetStream storage. It waits up to 5 seconds for the server to become ready and calls tb.Fatal if it does not. Shutdown is handled automatically via tb.Cleanup.

func StringPtr

func StringPtr(s string) *string

StringPtr returns a pointer to the given string.

func WaitFor

func WaitFor(tb testing.TB, deadline time.Duration, condition func() bool, msg string)

WaitFor polls condition every 5ms until it returns true or deadline expires. It calls tb.Fatal with msg if the deadline is exceeded, which stops the test immediately.

func WriteTempCertFiles

func WriteTempCertFiles(tb testing.TB, certPEM, keyPEM []byte) (certPath, keyPath string)

WriteTempCertFiles writes cert and key PEM data to temporary files (0o600 permissions) inside tb.TempDir and returns their paths. The files are cleaned up automatically.

Types

type MockCacheProvider

type MockCacheProvider struct {
	SaveErr   error
	GetErr    error
	DeleteErr error
	ExistsErr error

	SaveCalls       int
	GetCalls        int
	DeleteCalls     int
	DeleteManyCalls int
	ExistsCalls     int
	// contains filtered or unexported fields
}

MockCacheProvider is a concurrency-safe, in-memory implementation of data/cache/providers.Provider for testing.

Error injection: set SaveErr, GetErr, DeleteErr, or ExistsErr to make the corresponding method return that error instead of performing its normal operation. DeleteMany reuses DeleteErr.

Call counting: each method increments its respective *Calls counter on every invocation, regardless of whether an error is injected.

func NewMockCacheProvider

func NewMockCacheProvider() *MockCacheProvider

NewMockCacheProvider returns a ready-to-use MockCacheProvider with an empty store and all error injection fields set to nil.

func (*MockCacheProvider) Delete

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

Delete removes key from the store. It returns DeleteErr if set.

func (*MockCacheProvider) DeleteMany

func (m *MockCacheProvider) DeleteMany(_ context.Context, keys ...string) error

DeleteMany removes all provided keys from the store. It returns DeleteErr if set.

func (*MockCacheProvider) Exists

func (m *MockCacheProvider) Exists(_ context.Context, key string) (bool, error)

Exists reports whether key is present in the store. It returns ExistsErr if set.

func (*MockCacheProvider) Get

func (m *MockCacheProvider) Get(_ context.Context, key string) ([]byte, error)

Get returns the value for key, or ErrMockMissing if the key does not exist. It returns GetErr if set.

func (*MockCacheProvider) Save

func (m *MockCacheProvider) Save(_ context.Context, key string, value []byte, _ time.Duration) error

Save stores value under key. It returns SaveErr if set.

type MockHealthChecker

type MockHealthChecker struct {
	Status health.ServingStatus
	Delay  time.Duration
	Calls  int
	// contains filtered or unexported fields
}

MockHealthChecker is a concurrency-safe implementation of health.Checker for testing. Set Delay to simulate slow health checks; if the context is canceled during the delay, health.StatusNotServing is returned.

func NewMockHealthChecker

func NewMockHealthChecker(status health.ServingStatus) *MockHealthChecker

NewMockHealthChecker returns a MockHealthChecker initialized with the given status.

func (*MockHealthChecker) CheckHealth

CheckHealth increments the Calls counter and returns the current Status. If Delay is positive it sleeps for that duration; if ctx is canceled during the sleep it returns health.StatusNotServing immediately.

func (*MockHealthChecker) SetStatus

func (m *MockHealthChecker) SetStatus(s health.ServingStatus)

SetStatus updates the serving status in a concurrency-safe manner.

type MockIdempotencyStorage

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

MockIdempotencyStorage is a concurrency-safe, in-memory implementation of data/idempotency/storages.Storage for testing.

MockIdempotencyStorage.AttemptLock returns false and the existing value when the key is already present, mimicking real lock-or-load semantics.

func NewMockIdempotencyStorage

func NewMockIdempotencyStorage() *MockIdempotencyStorage

NewMockIdempotencyStorage returns a ready-to-use MockIdempotencyStorage with an empty entry set.

func (*MockIdempotencyStorage) AttemptLock

func (m *MockIdempotencyStorage) AttemptLock(_ context.Context, key string, val []byte) (bool, []byte, error)

AttemptLock stores val under key if the key does not yet exist (returns true, nil, nil). If the key already exists it returns false and the previously stored value.

func (*MockIdempotencyStorage) Complete

func (m *MockIdempotencyStorage) Complete(_ context.Context, key string, val []byte) error

Complete overwrites the value stored under key, marking the operation as finished.

func (*MockIdempotencyStorage) Delete

Delete removes the entry for key.

type MockNetError

type MockNetError struct {
	IsTimeout bool
	IsTemp    bool
	Msg       string
}

MockNetError implements the net.Error interface for testing. The exported fields control the return values of the corresponding methods: Msg is returned by Error, IsTimeout by Timeout, and IsTemp by Temporary.

func (*MockNetError) Error

func (e *MockNetError) Error() string

func (*MockNetError) Temporary

func (e *MockNetError) Temporary() bool

func (*MockNetError) Timeout

func (e *MockNetError) Timeout() bool

type MockReadCloser

type MockReadCloser struct {
	io.Reader
	Closed bool
}

MockReadCloser wraps any io.Reader as an io.ReadCloser and records whether MockReadCloser.Close was called via the Closed field.

func (*MockReadCloser) Close

func (m *MockReadCloser) Close() error

Close implements io.Closer.

type MockUniqProvider

type MockUniqProvider struct {
	AddErr error
	// contains filtered or unexported fields
}

MockUniqProvider is a concurrency-safe, in-memory implementation of data/uniq/providers.Provider for testing.

Set AddErr to make MockUniqProvider.Add and MockUniqProvider.AddWithValue return that error instead of storing the key.

func NewMockUniqProvider

func NewMockUniqProvider() *MockUniqProvider

NewMockUniqProvider returns a ready-to-use MockUniqProvider with an empty key set.

func (*MockUniqProvider) Add

func (m *MockUniqProvider) Add(_ context.Context, key string) error

Add registers key with a nil value. It returns AddErr if set.

func (*MockUniqProvider) AddWithValue

func (m *MockUniqProvider) AddWithValue(_ context.Context, key string, value []byte) error

AddWithValue registers key with the given value. It returns AddErr if set.

func (*MockUniqProvider) Clear

func (m *MockUniqProvider) Clear(_ context.Context) error

Clear removes all keys from the store.

func (*MockUniqProvider) Exist

func (m *MockUniqProvider) Exist(_ context.Context, key string) (bool, error)

Exist reports whether key has been registered.

func (*MockUniqProvider) GetValue

func (m *MockUniqProvider) GetValue(_ context.Context, key string) ([]byte, error)

GetValue returns the value associated with key, or nil if the key does not exist.

func (*MockUniqProvider) Remove

func (m *MockUniqProvider) Remove(_ context.Context, key string) error

Remove deletes key from the store.

type Person

type Person struct {
	Name string `json:"name"`
	Age  int    `json:"age"`
}

Person is a common test struct with Name and Age.

type RoundTripFunc

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

RoundTripFunc is an adapter that allows ordinary functions to be used as http.RoundTripper. Assign it to an http.Client.Transport field to intercept outgoing requests in tests.

func (RoundTripFunc) RoundTrip

func (f RoundTripFunc) RoundTrip(r *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type User

type User struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

User is a common test struct with ID and Name.

Jump to

Keyboard shortcuts

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