testkit

package
v11.3.0 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2026 License: MIT Imports: 7 Imported by: 0

Documentation

Overview

Package testkit provides lightweight test helpers for chassis-go services. It has zero dependencies on other chassis packages.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetFreePort

func GetFreePort() (int, error)

GetFreePort asks the OS for an available TCP port by listening on :0, then closes the listener and returns the assigned port. This is useful for parallel tests that each need their own listener.

Note: there is an inherent TOCTOU race between closing the listener and the caller binding to the port. In practice this rarely causes issues in test environments, but callers should handle bind failures gracefully.

func NewLogger

func NewLogger(t testing.TB) *slog.Logger

NewLogger returns a *slog.Logger that writes JSON output to t.Log so that log lines appear alongside test output and are suppressed on success unless -v is passed. The level is set to Debug so every message is captured.

func Respond

func Respond(status int, body string) http.Handler

Respond returns an http.Handler that always replies with the given status code and body string, setting Content-Type to application/json.

func Sequence

func Sequence(handlers ...http.Handler) http.Handler

Sequence returns an http.Handler that serves responses from a list of handlers in order, repeating the last handler for any extra requests.

func SetEnv

func SetEnv(t testing.TB, envs map[string]string)

SetEnv sets the supplied environment variables and registers a t.Cleanup to unset them after the test. This is the building block for test config — pair it with config.MustLoad[T]() in your test to load typed configuration.

Example:

testkit.SetEnv(t, map[string]string{"PORT": "8080"})
cfg := config.MustLoad[AppConfig]()

Types

type MockServer

type MockServer struct {
	*httptest.Server
	// contains filtered or unexported fields
}

MockServer wraps httptest.Server with automatic request recording.

func NewHTTPServer

func NewHTTPServer(t testing.TB, handler http.Handler) *MockServer

NewHTTPServer starts an httptest.Server that records every request before delegating to handler. The server is automatically closed via t.Cleanup.

func (*MockServer) Requests

func (s *MockServer) Requests() []RecordedRequest

Requests returns a snapshot of all requests received so far.

type RecordedRequest

type RecordedRequest struct {
	Method  string
	Path    string
	Headers http.Header
	Body    []byte
}

RecordedRequest captures the essential parts of an incoming HTTP request for later assertion in tests.

Jump to

Keyboard shortcuts

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