Documentation
¶
Overview ¶
Package openapi writes mock files from an OpenAPI description. It reads a Document, a model that is the same for every version of OpenAPI, which the version packages fill: openapiv3 from OpenAPI 3.0, 3.1 and 3.2. It imports none of them, nor any OpenAPI library.
Generate turns each operation of a document into mocks in priority bands, above the priority 0 of mocks written by hand, so those always win:
- 100 + 1000s: the responses nothing in a request predicts, such as 403 or 503, written disabled. Enabled through the admin API, one answers before the others.
- 200 + 1000s: a 401 for a request without a credential the operation's security asks.
- 300 + 1000s: a 415 for a body in a media type the operation doesn't take.
- 400 + 1000s: a 400 for parameters or a body that don't fit their schemas, or the 422 the operation declares instead.
- 500 + 1000s: a mock for each example of the path parameters, on the concrete path, when the path's own mocks take it: no value is empty, or holds a / inside a segment.
- 600 + 1000s: the main success response, one mock for each media type it offers.
- 700 + 1000s: a 406 for a request whose Accept takes none of those media types.
- 800 + 1000s: a 404, when the spec declares one and the path parameters have examples, one mock for each media type it offers. A client whose Accept takes none of them gets the first.
- 900 + 1000s: a 405 for a method none of the path's operations has.
s is the number of templated segments of the path: every mock of /pets/mine answers before those of /pets/{id}, as OpenAPI matches a literal path first. The 401, 415 and 400 refuse a request that the openapi matcher, under not, finds breaks the copy of the spec Generate writes beside the mocks. Each answers the operation's response of its status, or a problem body, RFC 9457's, which for a 400 or 422 lists what the request breaks.
A body is the media type's first example, or a fake value of its schema. In JSON, it is written as JSON. In any other media type, it is written as text, or as bytes when its schema says the string is base64, but for a serialized example, the body as sent: an object or a list there, which has no text, leaves its mock disabled and without a body.
A rerun on the same document writes the same bytes: the operations are sorted, and fake values are seeded by the mock they belong to.
Index ¶
- Constants
- Variables
- func Detect(data []byte) (string, error)
- func IsJSON(mediaType string) bool
- func Location(in string) (*url.URL, error)
- func Read(ctx context.Context, client *http.Client, u *url.URL) ([]byte, error)
- func RequestRoots(defs map[string]any, schemas []any) []map[string]any
- func RouteFirst(m *Mock) string
- type Content
- type Document
- type Example
- type File
- type Header
- type Layout
- type Mock
- type Namer
- type Operation
- type Parameter
- type Reply
- type Report
- type Request
- type Response
Constants ¶
const DefsPrefix = "#/$defs/"
DefsPrefix starts a $ref to a schema of Document.Defs: DefsPrefix + name.
const MaxSpecSize = 32 << 20
MaxSpecSize bounds a spec, and each file it refers to, in bytes.
Variables ¶
var ( // ErrNotOpenAPI is the error of a document that names no version of OpenAPI or Swagger. ErrNotOpenAPI = errors.New("openapi: not an OpenAPI or Swagger document") // ErrInvalid is the error of a spec its version package finds invalid: mocks of it would mislead. ErrInvalid = errors.New("openapi: invalid spec") // ErrTooLarge is the error of a spec, or a file it refers to, larger than [MaxSpecSize]. ErrTooLarge = errors.New("openapi: the spec is too large") // ErrNotGenerated is the error of a file [Write] would overwrite that it didn't write from the same spec. ErrNotGenerated = errors.New("openapi: a file to write is not one generated from this spec") )
var SchemaMapKeywords = []string{"properties", "patternProperties", "$defs", "dependentSchemas"}
SchemaMapKeywords are the keywords of a schema that hold schemas by name: their keys are names, not keywords.
var ValueKeywords = []string{"const", "default", "enum", "example", "examples"}
ValueKeywords are the keywords of a schema that hold values, not schemas: what they hold is data, whatever its keys.
Functions ¶
func Detect ¶
Detect returns the version a spec in JSON or YAML declares: its openapi field, such as 3.1.0, or its swagger field, such as 2.0. It fails with ErrNotOpenAPI when it declares neither.
func IsJSON ¶
IsJSON reports whether mediaType, with or without parameters, is JSON: application/json or a type ending in +json, such as application/vnd.api+json.
func Location ¶
Location returns the URL of in, a file path or an http(s) URL, which the relative references of the spec it names resolve against.
func Read ¶
Read returns the content of the file or the http(s) URL u, which client gets, up to MaxSpecSize bytes. A URL that doesn't answer 200 fails, as does one past MaxSpecSize, with ErrTooLarge.
func RequestRoots ¶
RequestRoots returns each of schemas, schemas of a document whose shared schemas are defs, as a request sees it: a property a schema marks readOnly is no longer required, as a request needn't send it, but stays declared, as it may. Each is a root, with the shared schemas its $ref values name under $defs.
func RouteFirst ¶
RouteFirst names a mock route first, so a folder lists the mocks of a route together: <route>[-<method>]-<status>[-<media>][-<variant>], such as pets-_id-get-200-json, or pets-_id-405 for a mock of any method. The segments of the route are joined by '-', a parameter {id} is written _id, and a dot inside a part is written '-'. The route / is root.
Types ¶
type Content ¶
type Content struct {
// MediaType is the media type, such as application/json.
MediaType string
// Schema is the schema of the body, or nil for none.
Schema any
// Examples are bodies the spec gives for the media type.
Examples []Example
}
Content is the body of a response in a media type.
type Document ¶
type Document struct {
// Title is the title of the API. Generated files name it, so a rerun knows them.
Title string
// Operations are the operations of the API, in any order.
Operations []Operation
// Defs are the schemas the others share, by name.
Defs map[string]any
// Spec is the spec as data, in one document, which the mocks that refuse a request that breaks it check the
// request against: its operations answer where their mocks do, under servers of their base path only.
Spec any
}
Document is an OpenAPI description, in the terms every version shares. Its schemas are JSON Schema 2020-12 documents, maps or booleans, whose $ref values point into Defs as DefsPrefix + name.
type Example ¶
type Example struct {
// Name is the name the spec gives the example, or "" for an unnamed one.
Name string
// Value is the example's value.
Value any
// Serialized tells whether Value is the spec's serializedValue of OpenAPI 3.2, the body as sent, encoding
// included: a body takes it as is, though its schema says base64.
Serialized bool
}
Example is a value a spec gives as an example.
type File ¶
type File struct {
// Name is the name of the file, which ends in .mock.yaml, or .openapi.yaml for the copy of the spec.
Name string
// Mocks are the mocks of the file, one YAML document each.
Mocks []Mock
// Data is the content of a file without mocks, the copy of the spec, as data.
Data any
}
File is a mock file: its name, in the folder it is written to, and its mocks, in order. It is the copy of the spec instead when it has no mocks.
func Generate ¶
Generate makes the mock files of doc: mocks named by RouteFirst, each in a file of its own, as PerMock lays them out. It logs on log, at warn level, each thing it could not honor, naming its mock, and zerolog.Nop silences it: a body no value fits, by its examples or its schema, leaves its mock without one and disabled. It fails only when ctx is done.
type Header ¶
type Header struct {
// Name is the name of the header.
Name string
// MediaType is the media type its value is written in, such as application/json, or "" for OpenAPI's simple
// style, in which a list is its items joined by commas.
MediaType string
// Explode tells, for an object in simple style, whether each of its keys is written with its value as key=value,
// rather than both as items.
Explode bool
// Schema is the schema of its value, or nil for none.
Schema any
// Examples are values the spec gives for it.
Examples []Example
}
Header is a header of a response.
type Mock ¶
type Mock struct {
// ID is the mock's ID, which its file is named after. [Generate] sets it with [RouteFirst].
ID string
// Route is the path the mock answers, under the document's base path, as the spec writes it.
Route string
// Method is the HTTP method, in upper case, or "" for a 405, which answers the methods its route lacks.
Method string
// Status is the key of the response the mock answers with, such as 200, 4XX or default.
Status string
// MediaType is the media type of the response body, or "" for none.
MediaType string
// Variant tells mocks of one response apart: the name of an example, or "example" for an unnamed one. It is ""
// for the response's main mock.
Variant string
// Name describes the mock.
Name string
// Priority orders the mock among the others: lower first.
Priority int
// Enabled is false for a mock that nothing in a request predicts, which the admin API can enable.
Enabled bool
// Request is what the mock matches.
Request Request
// Reply is what the mock answers.
Reply Reply
}
Mock is a generated mock: the route and response it answers, and the request it matches.
type Namer ¶
Namer returns the ID of a mock, which its file is named after: letters, digits, '_', '~' and '-', so the only dots of the file name are those of .mock.yaml, and never a name Windows keeps for a device, such as con. Generate makes IDs unique, ignoring case, and short enough for a file name.
type Operation ¶
type Operation struct {
// Method is the HTTP method, in upper case, such as GET or QUERY.
Method string
// Path is the path, as the spec writes it, such as /pets/{id}.
Path string
// BasePath is the path Path is under, such as /v1, or "" for none: that of the operation's servers, else of its
// path's, else of the document's.
BasePath string
// ID is the operationId of the operation, or "" for none.
ID string
// Summary describes the operation in a line. It may be empty.
Summary string
// Secured tells whether the operation refuses a request without credentials: its security requirements, else
// the document's, ask for some, and none of them is empty.
Secured bool
// Challenges are the challenges of the schemes the operation's security requirements name, as a
// WWW-Authenticate header gives them, such as Bearer, each once. A scheme without one, such as an API key, adds
// none.
Challenges []string
// Consumes are the media types the operation's request body takes, or nil for none.
Consumes []string
// HasInput tells whether the operation has parameters or a request body: what a request can break.
HasInput bool
// PathParams are the parameters of Path.
PathParams []Parameter
// Responses are the responses the operation declares.
Responses []Response
}
Operation is an HTTP method on a path.
type Parameter ¶
type Parameter struct {
// Name is the name the path gives it, between braces.
Name string
// Style is how a client writes its value in the path: simple, label or matrix.
Style string
// Explode tells, for a list or an object, whether each item is written apart, as Style does it.
Explode bool
// MediaType is the media type its value is written in, such as application/json, in place of Style, or "" for
// none.
MediaType string
// Examples are values of the parameter, the parameter's own examples first, then its schema's.
Examples []Example
}
Parameter is a parameter of a path.
type Reply ¶
type Reply struct {
// Status is the status code.
Status int
// Header holds the headers, by name.
Header map[string]string
// Body is the body, as a mock file's body key takes it: text as is, anything else as JSON. nil is no body.
Body any
// BodyBase64 is the body as bytes, in standard base64, in place of Body. "" is none.
BodyBase64 string
// Template tells whether Body is a template, which the server renders for each request.
Template bool
}
Reply is what a generated mock answers.
type Report ¶
type Report struct {
// Written are the names of the files it wrote.
Written []string
// Stale are the names of the files generated from the same spec before that it no longer writes: mocks, which
// still load, as the spec may have dropped their operation, and the copies of the spec they check requests
// against.
Stale []string
}
Report is what Write did.
func Write ¶
Write writes files to dir, which it creates if missing. Each file's first line says it was generated from the spec titled title, so a rerun overwrites the files it wrote, and lists those it no longer writes as stale, deleting none. When a file to write exists and wasn't generated from that spec, such as a mock written by hand or generated from another spec, it writes nothing, and fails with ErrNotGenerated naming each one.
type Request ¶
type Request struct {
// Method is what the method matches, as a mock file's method key takes it: a method, or a matcher list.
Method any
// Path is what the path matches, as a mock file's path key takes it: an equal matcher list, for a route without
// parameters or an example of one; or a regex matcher list, for a route with a parameter inside a segment. It is
// nil for a PathTemplate.
Path any
// PathTemplate is the path template to match, for a route whose parameters are whole segments.
PathTemplate string
// Accept is the matcher spec of the Accept header, or nil for none.
Accept []any
// Custom are the matcher specs of the whole request, as a mock file's custom key takes them, or nil for none.
Custom []any
}
Request is what a generated mock matches.
type Response ¶
type Response struct {
// Status is the key of the response: a status such as 200, a range such as 4XX, or default.
Status string
// Headers are the headers of the response, but Content-Type.
Headers []Header
// Content holds the body of the response for each media type it offers, in order of preference.
Content []Content
}
Response is a response an operation declares.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package pathtemplate reads the paths of an OpenAPI document, whose segments may hold parameters, such as {id}.
|
Package pathtemplate reads the paths of an OpenAPI document, whose segments may hold parameters, such as {id}. |