spectest

package
v1.40.2 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package spectest checks an OpenAPI document made by components/rest/generator against the running application, in the app's own tests. The generator reads the app's source and predicts its routes and the JSON its types marshal to; a prediction it gets wrong makes a wrong document that nothing else notices. Apps on the route registry (components/rest/api) have apitest instead.

Routes compares the routes Echo registered with the paths and methods of the document. It catches a route the generator never saw and an operation the document holds that Echo does not serve. It cannot tell whether a documented operation's parameters, bodies or responses are right, and it does not follow a path item that is a $ref, so the operations behind one count as missing from the document.

Schema marshals a value with encoding/json, or takes JSON as recorded, and validates it against a component schema of the document as a response. It catches a field the document names otherwise than encoding/json writes it, a field it calls required that encoding/json leaves out (omitempty, omitzero), a nil slice, map or pointer written as null where the document says the value is never null, a key the document does not declare, as an object that declares its properties is checked as closed where it is reached from the component through properties, items, map values, allOf and $refs to whole components, and a value outside a type, enum, format or bound. Everything under oneOf, anyOf, not, if, then, else, contains, propertyNames, patternProperties or dependentSchemas, and behind a $ref that is not to a whole component, is checked as the document writes it. It checks the values it is given: a field a test leaves at its zero value is checked as the zero value only. It cannot tell whether the handler returns that component, which is the test's own choice. A component with $id or $anchor does not compile when the checked component reaches it both closed and as written, such as under a oneOf or anyOf. A YAML document is read by the values its scalars have in YAML, not as written: an integer key or value not in plain decimal, such as 01 or 0x10, an unquoted timestamp, and a number past the range of a uint64, which is rounded.

Both take the document as bytes, JSON or YAML, OpenAPI 3.0 or 3.1, such as the 3.0.3 the generator writes (openapi.json, openapi.yaml, and their .internal forms). They report with t.Errorf, so a test sees every mismatch of a call, except that Schema lists at most validate.MaxFields (100) failures and then how many more there are.

Index

Constants

View Source
const AnyMethod = "ANY"

AnyMethod is the method Routes shows, and Ignore takes, for a route Echo's Any registered, which answers every method.

Variables

This section is empty.

Functions

func Routes

func Routes(t testing.TB, e *echo.Echo, spec []byte, opts ...Option)

Routes fails t when the routes e registered and the operations of the OpenAPI document spec differ, with one message listing, sorted by path then method, the routes Echo has that the document lacks, the operations the document has that Echo lacks, and the ignore rules that matched nothing.

Echo's paths are compared as Echo serves them, with a leading slash ("" is "/" and "users" is "/users"), and put in OpenAPI form by the generator's rule (generator.Route.OpenAPIPath): ":id" becomes "{id}" and a trailing "/*" becomes "/{path}". The generator keeps Echo's parameter names, so a route whose parameter the document names otherwise is reported on both sides.

Only the routes in Echo's route list are compared. The HEAD answer Echo gives a GET route (RouterConfig.AutoHandleHEAD) and its OPTIONS answer are not routes and are not compared, and neither are the not-found routes Group.Use and RouteNotFound add. A HEAD or OPTIONS route the app registers itself is compared like any other; the generator documents HEAD routes but not OPTIONS ones, so ignore those. A route whose method OpenAPI 3.0 and 3.1 cannot express, such as CONNECT, PROPFIND, QUERY, a custom method or an Any route (shown as AnyMethod), is compared too, and so always shows as missing from the document until it is ignored: leaving it out is the app's decision, made where the test shows it.

Ignore and IgnorePrefix leave routes out on purpose, such as health checks, the docs page, the MCP endpoint or static files; Ignore(AnyMethod, path) leaves out every method of path. A rule with an empty path fails the test, and so does a rule that matches no route on either side, so the list cannot outlive the routes it was written for. For a document that is a subset of the app's routes, such as the public document generator.Spec.Public writes beside the full one, ignore the routes it leaves out, by prefix where they share one; a test checking both documents calls Routes once for each, with its own rules.

func Schema

func Schema(t testing.TB, spec []byte, component string, value any)

Schema fails t when value does not validate against the component schema #/components/schemas/<component> of the OpenAPI document spec, with one message naming the component and, for each failure, the JSON pointer of the failing value in the JSON and the reason, at most validate.MaxFields of them.

value is marshalled with encoding/json, the encoder the handlers answer with; a json.RawMessage or a []byte is taken as the JSON it holds, so a test can pass a recorded response body. JSON whose object repeats a key fails, as apitest refuses it.

The value is validated as a response, by JSON Schema 2020-12 with the document's $refs resolved within it, recursive ones included: type, required, properties, additionalProperties, items, enum, const, allOf, oneOf, anyOf, not, the number, string, array and object bounds, pattern, and the formats the JSON Schema library knows (date-time, date, time, uuid, email, ipv4, ipv6, uri and others); readOnly properties are allowed. In an OpenAPI 3.0 document, the schemas of components.schemas are read as 2020-12: nullable: true admits null whatever else the schema says, which is how the generator means it on a reference wrapped in allOf, and a boolean exclusiveMinimum or exclusiveMaximum makes its bound exclusive.

Where the value is reached from the component through properties, items, prefixItems, an additionalProperties schema, allOf, and $refs to whole components (#/components/schemas/<name>), an object whose schema declares properties, itself or through those allOf and $refs, is checked as closed, as encoding/json writes no key its type lacks: a key the schema does not declare, as a property or in required, fails, though the generator writes no additionalProperties. It stays open where its schema states additionalProperties, patternProperties, unevaluatedProperties, propertyNames or dependentRequired, composes by oneOf, anyOf, if, dependentSchemas or $dynamicRef, holds a discriminator, as the base of an allOf hierarchy does, holds in that chain a free-form object (type object with no properties, required, $ref or allOf) or a $ref that is not to a whole component, or declares no properties, as a map or a free-form object does. Where the value is reached that way, open or closed, a writeOnly property, marked on the property or on a schema its allOf or its $ref to a component leads to, must be absent and is not required, unless a component a $ref leads to requires it and does not, itself or through its own allOf and $refs, mark it writeOnly. Everything under oneOf, anyOf, not, if, then, else, contains, propertyNames, patternProperties, dependentSchemas or $defs, and behind a $ref that is not to a whole component, is checked as the document writes it: no key fails for being undeclared, and writeOnly changes nothing.

Not checked: formats the library does not know, such as int32, int64, double, byte, binary or decimal (an integer is still checked as an integer); discriminator, which picks no branch of a oneOf or anyOf and otherwise only leaves its object open; whether the schema is the one the operation's response declares; a writeOnly property reached through anyOf or oneOf, as in the 3.1 nullable form, which stays required where required lists it; and the fields a value leaves at their zero value as other values, which a test covers by passing such values. Read otherwise than OpenAPI 3.0 reads them: every keyword beside a $ref is applied, nullable among them, where 3.0 ignores them; a schema a $ref leads to outside components.schemas, such as one under components.responses, is compiled as written, without the 3.0 reading of nullable and exclusive bounds; and a $ref whose pointer passes through a nullable schema of components.schemas in a 3.0 document cannot be compiled.

Types

type Option

type Option func(*options)

Option changes what Routes compares.

func Ignore

func Ignore(method string, path string) Option

Ignore leaves the route method path out of the comparison, on both sides. path is in OpenAPI form ("/users/{id}") or Echo's ("/users/:id"), which is read as the generator reads it, and a path without a leading slash is read with one, as Echo serves it. method is as Echo registered it, upper case, or AnyMethod, which covers an Any route and every method of path in Echo and in the document.

func IgnorePrefix

func IgnorePrefix(prefix string) Option

IgnorePrefix leaves out every route whose path, in OpenAPI form, starts with prefix, read as Ignore reads a path, whatever its method, on both sides. It is a plain string prefix: "/docs" also matches "/docs-old"; end it with "/" to match whole segments only.

Directories

Path Synopsis
internal
testapp
Package testapp is the application the spectest end-to-end test runs the OpenAPI generator on and serves with Echo, so both helpers are checked against the generator's real output.
Package testapp is the application the spectest end-to-end test runs the OpenAPI generator on and serves with Echo, so both helpers are checked against the generator's real output.
testapp/widgets
Package widgets is the module of the spectest test app: its request types, the functions that answer them and the models they return.
Package widgets is the module of the spectest test app: its request types, the functions that answer them and the models they return.

Jump to

Keyboard shortcuts

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