Documentation
¶
Overview ¶
Package testutil provides helpers for testing Credo applications: building a hermetic test App, overriding dependencies with fakes, starting an App served through ServeHTTP, injecting config, asserting on structured log output, and checking that every message key is in the catalogs.
Building a test App ¶
NewApp constructs a *credo.App that, unlike credo.New, never loads configuration from disk or from the environment. It injects an empty config by default, registers a best-effort shutdown via tb.Cleanup, and leaves the container un-finalized so the test can add routes, providers, or overrides:
func TestPingHandler(t *testing.T) {
app := testutil.NewApp(t)
app.GET("/ping", pingHandler)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/ping", nil))
// ... assert on rec ...
}
Overriding dependencies ¶
Use WithWiring to register the dependencies under test and WithOverride to swap any of them for a fake. Overrides run after wiring, so they win. WithOverride is built on credo.Override: it replaces an earlier binding and panics when there is none, so an override that no longer matches the wiring fails loudly; adding a binding is WithWiring's job.
app := testutil.NewApp(t,
testutil.WithWiring(func(app *credo.App) {
app.Provide(NewUserService)
app.Provide(NewPostgresRepo) // binds *PostgresRepo
app.Alias[UserRepo, *PostgresRepo]()
}),
testutil.WithOverride[UserRepo](fakeRepo),
)
svc := app.MustResolve[*UserService]() // built with fakeRepo
The override replaces the alias, and Finalize drops *PostgresRepo when nothing else uses it, so the real repository is never built.
Testing modules ¶
An application split into credo.Module values is tested with WithModules, which hands the modules to credo.App.UseModules with one more module last whose Services applies the WithOverride values. The overrides land after every module's services and before any module's handlers resolve, so the handlers a module registers are built with the fake:
app := testutil.NewApp(t,
testutil.WithModules(users.Module{}, billing.Module{}),
testutil.WithOverride[billing.Gateway](fakeGateway),
)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/invoices", body))
An override given beside a UseModules call in a WithWiring function would come after the modules' handlers had finalized the container and panics; a UseModules call in the wiring beside WithModules is a second call and panics too.
Starting an App ¶
An App with something to start — a component with Start or Ready, a start hook — refuses ServeHTTP until its start phase has run. Start runs it with credo.App.Start and shuts the App down when the test ends; for an App built by NewApp that shutdown runs after every cleanup the test adds, so a test server closed through t.Cleanup is drained first:
app := testutil.NewApp(t, testutil.WithWiring(wire)) testutil.Start(t, app) srv := httptest.NewServer(app) t.Cleanup(srv.Close)
Injecting config ¶
WithConfig sets values at dotted key paths. Repeated calls merge into one document that is injected as the App's RawConfig. Only these values are loaded; a .env file in the working directory and CREDO_* environment variables do not reach the test App:
app := testutil.NewApp(t,
testutil.WithConfig("app.name", "checkout"),
testutil.WithConfig("app.timeout", "5s"),
)
Asserting on logs ¶
Wire a LogBuffer with WithLogBuffer to capture structured output — the access log records included once the feature is installed — then match records with LogBuffer.AssertHas:
buf := testutil.NewLogBuffer()
app := testutil.NewApp(t, testutil.WithLogBuffer(buf))
app.UseAccessLog()
app.GET("/ping", pingHandler)
rec := httptest.NewRecorder()
app.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/ping", nil))
buf.AssertHas(t, testutil.LogEntry{
Level: "INFO",
Message: "request completed",
Attrs: map[string]any{"method": "GET", "status": 200},
})
Checking message keys ¶
A message key is a catalog key, never rendered as text: a key the catalogs do not define renders the code's built-in message. CheckMessageKeys parses the application's sources and fails the test for each key written as a literal that the catalogs do not define, and for each key that is not a literal:
func TestMessageKeys(t *testing.T) {
testutil.CheckMessageKeys(t, "locales", ".")
}
Maturity: beta
Index ¶
- func CheckMessageKeys(tb testing.TB, catalogDir string, sourceRoots ...string)
- func NewApp(tb testing.TB, opts ...Option) *credo.App
- func Start(tb testing.TB, app *credo.App)
- type LogBuffer
- func (b *LogBuffer) AssertEmpty(tb testing.TB)
- func (b *LogBuffer) AssertHas(tb testing.TB, want LogEntry)
- func (b *LogBuffer) AssertNotHas(tb testing.TB, want LogEntry)
- func (b *LogBuffer) Entries() []map[string]any
- func (b *LogBuffer) Handler() slog.Handler
- func (b *LogBuffer) Reset()
- func (b *LogBuffer) Write(p []byte) (int, error)
- type LogEntry
- type Option
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CheckMessageKeys ¶ added in v0.26.0
CheckMessageKeys fails tb for each message key in the Go sources under sourceRoots that the translation catalogs under catalogDir do not define, and for each key whose value is not a literal.
catalogDir has the layout credo.I18nConfig.Dir loads, {catalogDir}/{lang}/messages.json; a key is defined when any language's messages.json has it. The sources are parsed, not compiled: a key is found where it is written as a literal —
- the argument of WithMessageKey or RenderMessageKey,
- the value given to a MessageKey field, in a composite literal or an assignment,
- a constant or variable declared with type MessageKey,
- a conversion to MessageKey.
An argument that names a constant declared with type MessageKey, in any package under sourceRoots, is checked where the constant is declared. Any other value that is not a literal is reported: the check cannot see it, so a key computed at run time cannot be proved to be in the catalogs. A key that reaches WithMessageKey through an untyped constant is outside the scan, so declare key constants with their type. Test files, testdata, vendor and hidden directories are skipped.
The application chooses its catalog, so the check belongs in the application's tests:
func TestMessageKeys(t *testing.T) {
testutil.CheckMessageKeys(t, "locales", ".")
}
func NewApp ¶
NewApp constructs a *credo.App for tests. Unlike credo.New, it never loads configuration from disk or from the environment: by default it injects an empty RawConfig, and the values given with WithConfig are the only ones loaded, so tests are hermetic. Provide values with WithConfig, wire dependencies with WithWiring or the application's modules with WithModules, swap them with WithOverride, and capture logs with WithLogBuffer.
NewApp registers a graceful shutdown via tb.Cleanup: it tears down every singleton the test created whether or not the App was run. The App is not finalized, so tests may still register routes, providers, and overrides. The first resolving call finalizes it, as Start and serving a request do, and a registration after that panics naming the test's line that finalized it:
app := testutil.NewApp(t, testutil.WithOverride[UserRepo](fakeRepo)) svc := app.MustResolve[*UserService]()
func Start ¶ added in v0.24.0
Start runs app's start phase with credo.App.Start — each component's Start in dependency order, then the start hooks — so the App can be served through ServeHTTP, by httptest or a recorder, and fails the test when the start fails. The App is shut down when the test ends.
An App built by NewApp already has its shutdown cleanup registered first, so it runs after every cleanup the test adds later: a test server closed through tb.Cleanup is drained before the components stop, whether it was created before or after Start. Any other App gets a shutdown cleanup here, so its test server is created after Start or closed with defer.
app := testutil.NewApp(t, testutil.WithWiring(wire)) testutil.Start(t, app) srv := httptest.NewServer(app) t.Cleanup(srv.Close)
Types ¶
type LogBuffer ¶
type LogBuffer struct {
// contains filtered or unexported fields
}
LogBuffer captures structured log output for assertions in tests. It implements io.Writer and feeds a slog JSON handler, so every attribute, group, and With-derived field (such as the request_id added by the built-in request middleware) is recorded exactly as slog renders it.
Wire a LogBuffer into a test App with WithLogBuffer:
buf := testutil.NewLogBuffer()
app := testutil.NewApp(t, testutil.WithLogBuffer(buf))
// ... exercise the app ...
buf.AssertHas(t, testutil.LogEntry{Level: "INFO", Message: "request completed"})
Example ¶
ExampleLogBuffer captures structured log records and inspects them. A LogBuffer is usually wired into a test App with testutil.WithLogBuffer, but it works with any *slog.Logger. Records are inspected via Entries (here) or matched with AssertHas (which needs a *testing.T).
package main
import (
"fmt"
"log/slog"
"github.com/credo-go/credo/testutil"
)
func main() {
buf := testutil.NewLogBuffer()
logger := slog.New(buf.Handler())
logger.Info("user login", "user", "alice", "ok", true)
logger.Warn("rate limited", "user", "bob")
for _, e := range buf.Entries() {
fmt.Printf("%s level=%s user=%s\n", e["msg"], e["level"], e["user"])
}
}
Output: user login level=INFO user=alice rate limited level=WARN user=bob
func NewLogBuffer ¶
func NewLogBuffer() *LogBuffer
NewLogBuffer returns an empty LogBuffer ready to be wired with WithLogBuffer.
func (*LogBuffer) AssertEmpty ¶
AssertEmpty fails the test (via tb.Errorf) when any log records were captured at all. Useful after LogBuffer.Reset or for code paths that must stay silent.
func (*LogBuffer) AssertHas ¶
AssertHas fails the test (via tb.Errorf) unless at least one captured log record matches want. The matching rules are described on LogEntry. On failure it reports the wanted matcher and every captured record.
func (*LogBuffer) AssertNotHas ¶
AssertNotHas fails the test (via tb.Errorf) when at least one captured log record matches want — the negative counterpart of [AssertHas], for asserting that something was NOT logged (a skipped access log, a masked error detail). The matching rules are described on LogEntry.
func (*LogBuffer) Entries ¶
Entries parses and returns every captured log record as a decoded JSON object, in the order written. Lines that fail to parse as JSON are skipped.
func (*LogBuffer) Handler ¶
Handler returns a slog.Handler that writes JSON log records to the buffer at debug level, so all records are captured. It delegates to slog.NewJSONHandler, which keeps attribute, group, and WithAttrs semantics correct without a hand-written handler.
type LogEntry ¶
type LogEntry struct {
// Level matches the slog "level" field case-insensitively (e.g. "INFO").
Level string
// Message matches the slog "msg" field exactly.
Message string
// Attrs matches as a subset; each key must be present with an equal value.
Attrs map[string]any
}
LogEntry is a partial matcher for LogBuffer.AssertHas. Only the non-zero fields participate: an empty Level or Message is ignored, and Attrs matches as a subset (extra attributes on the actual record are allowed). Attribute values are compared after JSON normalization, so LogEntry{Attrs: {"status": 200}} matches a record whose status decoded as float64(200).
type Option ¶
type Option func(*options)
Option configures a test App built by NewApp.
func WithConfig ¶
WithConfig sets a single configuration value at a dotted key path (for example "server.port"). Repeated calls merge into one nested document that is injected as the App's RawConfig. Using WithConfig switches NewApp from its empty config to the real config loader, which decodes that document and nothing else: no .env file is read and no environment variable is merged, so the test sees exactly the values it set.
func WithLogBuffer ¶
WithLogBuffer routes the App's logger to buf so tests can assert on structured log output, including the request ID and access log records once those features are installed with app.UseRequestID and app.UseAccessLog. Without this option the test App uses a silent logger.
func WithModules ¶ added in v0.26.0
WithModules hands mods to credo.App.UseModules after the WithWiring functions, with one more module last whose Services applies the WithOverride values. The overrides therefore land after every module's services and before any module's handlers resolve, so a module's handlers resolve the replacement:
app := testutil.NewApp(t,
testutil.WithModules(users.Module{}, billing.Module{}),
testutil.WithOverride[billing.Gateway](fakeGateway),
)
Repeated calls append to one list, which is passed to a single UseModules call. A UseModules call in a WithWiring function beside WithModules is a second call and panics.
func WithOverride ¶
WithOverride replaces the binding for type T with value v, through credo.App.ProvideValue with credo.Override. Overrides run after WithWiring, and under WithModules after every module's services and before any module's handlers, making them the right tool for swapping a real dependency for a stub or fake. An override needs an earlier binding of T and panics without one, so an override that no longer matches the wiring fails instead of adding a binding nothing resolves; adding a binding is WithWiring's job. The replaced value never becomes the App's: whoever built it releases it.
testutil.WithOverride[UserRepo](fakeRepo)
func WithWiring ¶
WithWiring registers functions that wire dependencies into the container (typically credo.App.Provide / credo.App.ProvideValue calls). They run after the App is constructed but before any WithOverride, so an override can replace a binding established here.