testkit

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: MIT Imports: 19 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-backend-testing

Test helpers for services built on the go-backend-* family. Import as testkit. No assertion framework is pulled in; everything works with the standard testing package.

go get github.com/ahmedbaig/go-backend-testing

Isolated config

testkit.ConfigDir(t, map[string]any{
	"my-app":        map[string]any{"port": 0, "environment": "testing"},
	"my-app-logger": `{"logToFile": false}`,
})

Writes each entry as <name>.json in a temporary directory and points CONFIG_DIR at it for the length of the test, so a test can never read real config or secrets from the machine.

Testing an app

opts, logs := testkit.AppOptions(t, "my-app")
app := httpx.New(opts)
routes.Register(app, deps)

c := testkit.NewClient(t, app.Handler()).WithHeader("Authorization", "Bearer test")

item := testkit.Decode[Item](c.Post("/api/v1/items", Item{Name: "a"}).Expect(201))
c.Post("/api/v1/items", `{}`).ExpectError(400, httpx.CodeValidation)
c.Post("/api/v1/items", `{}`).ExpectField("name", "required")

logs.RequireLogged(t, "item created")

AppOptions gives an httpx.Options with a capturing logger, testing environment and probes that don't run on a schedule. Requests go straight to the handler (no network). Captured log lines are printed when a test fails.

Stubbing downstream services

users := testkit.NewStub(t).
	On("GET /api/v1/users/{id}", 200, User{ID: "7"}).
	On("POST /api/v1/users", 409, `{"errors":[{"code":"E409"}]}`)

svc := NewService(users.URL())
...
calls := users.RequireCalled("GET /api/v1/users/{id}", 1)

A real httptest server using ServeMux patterns. Every request is recorded (method, path, query, headers, body). Unknown routes return 501, so a missing stub fails loudly.

Fixtures and golden files

order := testkit.Fixture[Order](t, "order-paid")        // testdata/fixtures/order-paid.json
testkit.Golden(t, "invoice.json", renderInvoice(order))   // testdata/golden/invoice.json

Run go test ./... -update to rewrite golden files.

Assertions

NoError, ErrorIs, Equal (generic, deep), True, Contains, NotContains, Eventually(t, timeout, cond).

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ConfigDir

func ConfigDir(t testing.TB, files map[string]any) string

func Contains

func Contains(t testing.TB, s, sub string, msg ...string)

func Decode

func Decode[T any](r *Response) T

func Equal

func Equal[T any](t testing.TB, got, want T, msg ...string)

func ErrorIs

func ErrorIs(t testing.TB, err, target error, msg ...string)

func Eventually

func Eventually(t testing.TB, timeout time.Duration, cond func() bool, msg ...string)

func Fixture

func Fixture[T any](t testing.TB, name string) T

func Golden

func Golden(t testing.TB, name string, got any)

func NoError

func NoError(t testing.TB, err error, msg ...string)

func NotContains

func NotContains(t testing.TB, s, sub string, msg ...string)

func True

func True(t testing.TB, cond bool, msg ...string)

Types

type Call

type Call struct {
	Method string
	Path   string
	Query  string
	Header http.Header
	Body   []byte
}

func (Call) JSON

func (c Call) JSON(t testing.TB, v any)

type Client

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

func NewClient

func NewClient(t testing.TB, h http.Handler) *Client

func (*Client) Delete

func (c *Client) Delete(target string) *Response

func (*Client) Do

func (c *Client) Do(method, target string, body any) *Response

func (*Client) Get

func (c *Client) Get(target string) *Response

func (*Client) Patch

func (c *Client) Patch(target string, body any) *Response

func (*Client) Post

func (c *Client) Post(target string, body any) *Response

func (*Client) Put

func (c *Client) Put(target string, body any) *Response

func (*Client) WithHeader

func (c *Client) WithHeader(k, v string) *Client

type Entry

type Entry struct {
	Level   slog.Level
	Message string
	Attrs   map[string]any
}

type LogCapture

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

func AppOptions

func AppOptions(t testing.TB, name string) (httpx.Options, *LogCapture)

func Logger

func Logger(t testing.TB) (*slog.Logger, *LogCapture)

func (*LogCapture) AtLevel

func (c *LogCapture) AtLevel(l slog.Level) []Entry

func (*LogCapture) Entries

func (c *LogCapture) Entries() []Entry

func (*LogCapture) Find

func (c *LogCapture) Find(sub string) (Entry, bool)

func (*LogCapture) RequireLogged

func (c *LogCapture) RequireLogged(t testing.TB, sub string) Entry

func (*LogCapture) Reset

func (c *LogCapture) Reset()

type Response

type Response struct {
	Status int
	Header http.Header
	Body   []byte
	// contains filtered or unexported fields
}

func (*Response) Envelope

func (r *Response) Envelope() httpx.Envelope

func (*Response) Expect

func (r *Response) Expect(status int) *Response

func (*Response) ExpectError

func (r *Response) ExpectError(status int, code httpx.Code) httpx.Envelope

func (*Response) ExpectField

func (r *Response) ExpectField(field, rule string) *Response

func (*Response) JSON

func (r *Response) JSON(v any) *Response

type Stub

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

func NewStub

func NewStub(t testing.TB) *Stub

func (*Stub) Calls

func (s *Stub) Calls(pattern string) []Call

func (*Stub) Handle

func (s *Stub) Handle(pattern string, fn http.HandlerFunc) *Stub

func (*Stub) On

func (s *Stub) On(pattern string, status int, body any) *Stub

func (*Stub) RequireCalled

func (s *Stub) RequireCalled(pattern string, times int) []Call

func (*Stub) URL

func (s *Stub) URL() string

Jump to

Keyboard shortcuts

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