Documentation
¶
Overview ¶
Package testhelpers provides common testing utilities and helpers shared across the go-atlas project.
The package includes:
- Mock providers for caching (MockCacheProvider), uniqueness (MockUniqProvider), idempotency (MockIdempotencyStorage), and health checking (MockHealthChecker).
- HTTP and I/O test doubles (RoundTripFunc, MockReadCloser).
- NATS/JetStream helpers for spinning up embedded servers (StartNATSServer, ConnectNATS, ConnectJetStream, CreateNATSKV).
- TLS and cryptographic utilities (SelfSignedCert, GenerateRSAKey, WriteTempCertFiles).
- Polling helpers (WaitFor) and an audit helper (NewTestAuditor).
All helpers that accept testing.TB register cleanup functions automatically, so callers do not need to manage teardown manually.
Index ¶
- Variables
- func ConnectJetStream(tb testing.TB, ns *server.Server) (*nats.Conn, jetstream.JetStream)
- func ConnectNATS(tb testing.TB, ns *server.Server) *nats.Conn
- func CreateNATSKV(tb testing.TB, js jetstream.JetStream, bucket string, ttl time.Duration) jetstream.KeyValue
- func GenerateRSAKey(tb testing.TB, bits int) *rsa.PrivateKey
- func GenerateRSAKeyPEM(tb testing.TB, bits int) []byte
- func IntPtr(i int) *int
- func NewTestAuditor(tb testing.TB, opts ...audit.Option) (*audit.Auditor, *memory.Storage)
- func SelfSignedCert(tb testing.TB) (certPEM, keyPEM []byte, cert tls.Certificate)
- func SelfSignedCertWithOCSP(tb testing.TB, ocspServers []string) (certPEM, keyPEM []byte, cert tls.Certificate)
- func StartNATSServer(tb testing.TB) *server.Server
- func StringPtr(s string) *string
- func WaitFor(tb testing.TB, deadline time.Duration, condition func() bool, msg string)
- func WriteTempCertFiles(tb testing.TB, certPEM, keyPEM []byte) (certPath, keyPath string)
- type MockCacheProvider
- func (m *MockCacheProvider) Delete(_ context.Context, key string) error
- func (m *MockCacheProvider) DeleteMany(_ context.Context, keys ...string) error
- func (m *MockCacheProvider) Exists(_ context.Context, key string) (bool, error)
- func (m *MockCacheProvider) Get(_ context.Context, key string) ([]byte, error)
- func (m *MockCacheProvider) Save(_ context.Context, key string, value []byte, _ time.Duration) error
- type MockHealthChecker
- type MockIdempotencyStorage
- type MockNetError
- type MockReadCloser
- type MockUniqProvider
- func (m *MockUniqProvider) Add(_ context.Context, key string) error
- func (m *MockUniqProvider) AddWithValue(_ context.Context, key string, value []byte) error
- func (m *MockUniqProvider) Clear(_ context.Context) error
- func (m *MockUniqProvider) Exist(_ context.Context, key string) (bool, error)
- func (m *MockUniqProvider) GetValue(_ context.Context, key string) ([]byte, error)
- func (m *MockUniqProvider) Remove(_ context.Context, key string) error
- type Person
- type RoundTripFunc
- type User
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
GenerateRSAKeyPEM generates an RSA private key and returns it as PKCS#8 PEM-encoded bytes.
func NewTestAuditor ¶
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 ¶
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.
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 ¶
Exists reports whether key is present in the store. It returns ExistsErr if set.
func (*MockCacheProvider) Get ¶
Get returns the value for key, or ErrMockMissing if the key does not exist. It returns GetErr 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 ¶
func (m *MockHealthChecker) CheckHealth(ctx context.Context) health.ServingStatus
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.
type MockNetError ¶
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 ¶
MockReadCloser wraps any io.Reader as an io.ReadCloser and records whether MockReadCloser.Close was called via the Closed field.
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 ¶
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.
type RoundTripFunc ¶
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.