test

package
v1.8.2 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: Apache-2.0 Imports: 18 Imported by: 1 module, 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

Test server

test is a HTTP test server for an API's unit tests.

  • It serves the routes a function registers with a router, at /api.
  • It records every request and response.
  • When the test ends, it checks each one against the router's OpenAPI specification, and fails the test for any which doesn't conform.

So a test of a handler also checks that the handler does what its documentation says.

What's checked

  • Operations: the route which matched has the request's method documented.
  • Statuses: the response's status is documented, or there's a default response.
  • Request bodies: a successful request's body matches its schema.
  • Response bodies: each response's body matches its schema, or is empty when none is documented.
  • Content types: a body is matched by its content type, or a documented wildcard, such as image/* or */*.
    • JSON bodies are validated directly.
    • YAML is validated as the JSON it's equivalent to.
    • A multipart form is validated as an object of its fields, with each file as its name.
    • A text/plain body, or a stream of server-sent events, is validated as a string.

What's not checked

  • Redirects from a path which isn't documented, as the request they redirect to is checked.
  • Unrouted paths: a 404 for a path which no route matches.
  • Exchanges whose client went away, such as a stream the test closed, or an interrupted upload, as their response can't be received.

A test

package mymodule_test

import (
	"net/http"
	"testing"

	"github.com/mutablelogic/go-server/pkg/httprouter"
	"github.com/mutablelogic/go-server/test"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestGetThing(t *testing.T) {
	// Serve the module's API, which is checked when the test ends
	server := test.NewServer(t, func(router *httprouter.Router) error {
		return httphandler.RegisterHandlers(manager, router)
	})

	// GET /api/thing/one, and decode the response
	var thing schema.Thing
	require.Equal(t, http.StatusOK, server.JSON(t, http.MethodGet, "thing/one", nil, &thing))
	assert.Equal(t, "one", thing.Name)

	// A thing which doesn't exist isn't found
	assert.Equal(t, http.StatusNotFound, server.JSON(t, http.MethodGet, "thing/none", nil, nil))
}

Paths are relative to the prefix, and can have a query, such as thing?limit=10. A trailing slash is kept, as it's significant to the router.

Requests

Method Sends Returns
JSON(t, method, path, body, v) a body as JSON, and decodes a 2xx response into v the status
Do(t, method, path, body) a body as JSON the status and body
DoWithContentType(t, method, path, contentType, body) a body with the content type the status and body
Send(t, method, path, header, body) the headers, and the body as it is the status, headers and body
Request(t, method, path, header) the headers, without a body the status, headers and body
Head(t, path, header) a HEAD request, to a route which handles it the status and headers

A body which is a string or []byte is sent as it is, nil sends none, and any other value is encoded as JSON.

// Create a thing, with a JSON body
var created schema.Thing
status := server.JSON(t, http.MethodPost, "thing", schema.ThingMeta{Name: "two"}, &created)
require.Equal(t, http.StatusCreated, status)

// Send YAML, which is checked against the request body's schema, when the
// operation documents application/yaml
status, body := server.DoWithContentType(t, http.MethodPost, "thing", "application/yaml", "name: three\n")

// Send headers, such as a precondition, and read the response's headers
status, header, body := server.Send(t, http.MethodGet, "thing/one", http.Header{
	"If-None-Match": {`"abc"`},
}, nil)
assert.Equal(t, http.StatusNotModified, status)

A module's server

A module with its own handlers can wrap the server, so its tests make one call:

// Package test has a test server of the module's API
package test

// NewServer starts a test server of the manager's API, which is checked
// against its OpenAPI specification when the test ends
func NewServer(t *testing.T, manager *mymodule.Manager) *test.Server {
	t.Helper()
	return test.NewServer(t, func(router *httprouter.Router) error {
		return errors.Join(
			httphandler.RegisterHandlers(manager, router),
			broadcasterhandler.RegisterHandlers(manager.Broadcaster(), router),
		)
	})
}

Streams

A stream, such as of server-sent events, is requested with the server's URL and test.Prefix, so the test can read it as it arrives. Its exchange is recorded once the handler returns, and isn't checked when the test cancels the request.

ctx, cancel := context.WithCancel(context.Background())
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL+test.Prefix+"/changes", nil)
require.NoError(t, err)
req.Header.Set("Accept", "text/event-stream")
resp, err := http.DefaultClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()

A client of the API, such as one made with go-client, can be given server.URL + test.Prefix as its endpoint too.

Testing what fails the check

Verify returns an error for each exchange which doesn't conform, without failing the test. Reset discards the exchanges, so a test which makes ones which don't conform, on purpose, doesn't fail when it ends.

func TestUndocumented(t *testing.T) {
	server := test.NewServer(t, register)

	// A status which isn't documented doesn't conform
	server.Do(t, http.MethodGet, "thing?fail=teapot", nil)
	errs := server.Verify()
	require.Len(t, errs, 1)
	assert.ErrorContains(t, errs[0], "status 418 is not documented")

	// Discard it, so the test doesn't fail when it ends
	server.Reset()
}

Exchanges returns what's recorded: each request's method, path, the route pattern which matched it, headers and body, and its response's status, headers and body. Spec returns the OpenAPI specification which they're checked against.

Documentation

Overview

Package test has a HTTP test server of an API, which records every request and response, and checks them against the API's OpenAPI specification when the test ends, for the tests of go-server's packages, and of the servers which use them

Index

Constants

View Source
const Prefix = "/api"

Prefix is the path prefix for the API routes

Variables

This section is empty.

Functions

This section is empty.

Types

type Exchange

type Exchange struct {
	Method string
	Path   string

	// Pattern is the route pattern which matched the request, such as
	// "/api/changes", or empty if no route matched
	Pattern string

	RequestHeader  http.Header
	RequestBody    []byte
	RequestErr     error // reading the request's body, or the request's context, when the client went away
	Status         int
	ResponseHeader http.Header
	ResponseBody   []byte
}

Exchange is a recorded request and response

func (Exchange) String

func (e Exchange) String() string

type Server

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

Server is a HTTP test server of an API, which a function registers with a router. Every request and response is recorded, and checked against the router's OpenAPI specification when the test ends.

func NewServer

func NewServer(t *testing.T, register func(*httprouter.Router) error) *Server

NewServer starts a HTTP test server serving the API which the function registers with a router, at Prefix. When the test ends the server is closed, and every recorded exchange is checked against the router's OpenAPI specification.

func (*Server) Do

func (s *Server) Do(t *testing.T, method, path string, body any) (int, []byte)

Do sends a request to the API with a JSON body, and returns the status code and response body. The path is relative to the API prefix, and may include a query string. A body which is a string or []byte is sent as-is, nil sends no body, and any other value is encoded as JSON.

func (*Server) DoWithContentType

func (s *Server) DoWithContentType(t *testing.T, method, path, contentType string, body any) (int, []byte)

DoWithContentType sends a request with the body as the content type, which is used as-is for a string or []byte body, and otherwise encoded as JSON. Returns the status code and the response body.

func (*Server) Exchanges

func (s *Server) Exchanges() []Exchange

Exchanges returns the recorded requests and responses

func (*Server) Head

func (s *Server) Head(t *testing.T, path string, header http.Header) (int, http.Header)

Head sends a HEAD request to the API with the headers, and returns the status code and response headers. The path is relative to the API prefix.

func (*Server) JSON

func (s *Server) JSON(t *testing.T, method, path string, body, v any) int

JSON sends a request to the API as Do does, and decodes a successful response body into v. Returns the status code.

func (*Server) Request

func (s *Server) Request(t *testing.T, method, path string, header http.Header) (int, http.Header, []byte)

Request sends a request to the API without a body, with the headers, and returns the status code, response headers and response body. The path is relative to the API prefix, and may include a query string.

func (*Server) Reset

func (s *Server) Reset()

Reset discards the recorded requests and responses

func (*Server) Send

func (s *Server) Send(t *testing.T, method, path string, header http.Header, body []byte) (int, http.Header, []byte)

Send sends a request to the API with the headers and body, which is sent when it isn't nil, and returns the status code, response headers and response body. The path is relative to the API prefix, and may include a query string.

func (*Server) Spec

func (s *Server) Spec() *openapi.Spec

Spec returns the OpenAPI specification for the API

func (*Server) Verify

func (s *Server) Verify() []error

Verify checks every recorded exchange against the OpenAPI specification, and returns an error for each which does not conform

Jump to

Keyboard shortcuts

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