openapitest

package
v0.0.0-...-38da05c Latest Latest
Warning

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

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

Documentation

Overview

Package openapitest holds the test scaffolding every test package under compilers/openapi would otherwise copy, since test files cannot share unexported helpers.

A helper belongs here only if all of those packages can import it, so imports stop at ir, compilers, diag and third-party libraries: reaching further would make this package unimportable from the internal tests of what it reached. That keeps parseFull and the lowerer fixture with their drivers.

componentID and typeByName stay in test files: the idderivations rule refuses a spelled-out ID in production code, and deriving one through compile would make the lookup a tautology.

Index

Constants

View Source
const EmptySpec = "openapi: 3.1.0\ninfo: {title: T, version: \"1\"}\npaths: {}\n"

EmptySpec is a minimal 3.1 document that declares nothing, for a test that needs a loaded document and reads nothing of it.

View Source
const EveryKindOfReference = `` /* 1239-byte string literal not displayed */

EveryKindOfReference is a document holding a resolvable reference of each kind the library has: one in each position its walk meets one, and a schema's. Each names the component of the same kind, whose name is its section's first letter or, for the security scheme, K.

View Source
const InlineProbeBody = `{type: string, title: SUM, description: DOC, ` +
	`externalDocs: {url: 'https://e.example', description: ED}, deprecated: true, ` +
	`example: abc, x-vendor: V, xml: {name: X}, not: {const: N}, maxLength: 3}`

InlineProbeBody is the body every inline-position case writes: one annotation of each kind the declared-annotation reader takes, one validation-only keyword, and one value constraint — all of them position-scoped, so a position that lowers this to the shared string primitive loses every one. All three documentation keywords are here because a home that keeps only the description passes a probe that writes only a description.

View Source
const MaxTreeDepth = 64

MaxTreeDepth bounds how deep Positions reads the tree a model was built from. The corpus nests far shallower, so a spec reaching it has outgrown the walk, which fails rather than leave the paths below unread.

Variables

This section is empty.

Functions

func AssertHasCode

func AssertHasCode(t TB, diags []ir.Diagnostic, code string, sev ir.Severity)

AssertHasCode requires diags to carry a diagnostic with the given code at the given severity.

func AssertInfoDiagAt

func AssertInfoDiagAt(t TB, diags []ir.Diagnostic, pointer string)

AssertInfoDiagAt requires one info diagnostic stamped at pointer.

func AssertProbeDocsKept

func AssertProbeDocsKept(t TB, d ir.Docs)

AssertProbeDocsKept checks all three documentation keywords InlineProbeBody writes reached d, wherever the position's home turned out to be.

func AssertProbeExample

func AssertProbeExample(t TB, examples []ir.Example)

AssertProbeExample checks the single example InlineProbeBody writes reached the home under test with its value intact.

func BodyTarget

func BodyTarget(t TB, payload *ir.Payload) ir.TypeID

BodyTarget returns the type a single-media-type payload refers to.

The two requires are the reason this is a function rather than the indexing expression it wraps: written inline, a payload that is nil or that grew a second media type panics on a line that says nothing about which of the two happened.

func ClearAnchors

func ClearAnchors(root *yaml.Node)

ClearAnchors empties the anchor name of every node under root, as the load phase does before it hands a tree to the parser library.

func ComponentSpec

func ComponentSpec(schemas string) string

ComponentSpec wraps a components/schemas block in a minimal 3.1 document.

func ComponentSpecVer

func ComponentSpecVer(version, schemas string) string

ComponentSpecVer wraps a components/schemas block in a minimal document of the given OpenAPI version.

func CountDiagsAt

func CountDiagsAt(diags []ir.Diagnostic, code string, sev ir.Severity) int

CountDiagsAt counts the diagnostics in diags matching code and sev exactly. code is an exact match with no wildcard: CountDiagsAt(diags, "", ir.SeverityError) matches only diagnostics whose code is literally empty — it is not a way to spell "every error," and reads dangerously like one, so callers who want that must filter on severity alone instead.

func DiagMessageAt

func DiagMessageAt(t TB, diags []ir.Diagnostic, code string, sev ir.Severity, pointer string) string

DiagMessageAt returns the message of the single diagnostic matching code, severity and provenance pointer. Tests that only compare a diagnostic's code cannot tell two lowerings apart when both report the same code with different reasons, so the reason itself needs an assertable handle.

func DocDeclaring

func DocDeclaring(names ...string) *soa.OpenAPI

DocDeclaring builds a document declaring the named component schemas, with no parser and no fixture — the shape a test wants when what it needs from the document is only which components it declares.

func EmptyEitherSchema

func EmptyEitherSchema() *oas3.JSONSchema[oas3.Referenceable]

EmptyEitherSchema is a JSONSchema whose either-value has neither a Left schema nor a Right bool set: IsSchema() is true (IsLeft defaults true) yet GetSchema() is nil. The parser never produces this, so it drives the nil-schema guards.

func FindOp

func FindOp(t TB, doc *ir.Document, source string) ir.Operation

FindOp returns the operation whose source name matches.

func FirstDegradedWarning

func FirstDegradedWarning(diags []ir.Diagnostic) (ir.Diagnostic, bool)

FirstDegradedWarning returns the first diag.DegradedConstruct warning in diags, and whether one was found — the pointer/message inspection counterpart to HasDiagAt/CountDiagsAt.

func FirstDiag

func FirstDiag(diags []ir.Diagnostic, code string) (ir.Diagnostic, bool)

FirstDiag returns the first diagnostic carrying code, at any severity, so a test can assert on its provenance or its message.

func FirstOp

func FirstOp(t TB, svc ir.Service) ir.Operation

FirstOp returns the operation at svc.Groups[0].Operations[0], requiring both to be non-empty first rather than letting a malformed fixture fail with a bare index-out-of-range panic.

func HasDiag

func HasDiag(diags []ir.Diagnostic, code string) bool

HasDiag reports whether diags contains a diagnostic with the exact code, at any severity. It is the existential half of the vocabulary: use it where a test only needs to know a diagnostic fired, not how many or at what severity.

func HasDiagAt

func HasDiagAt(diags []ir.Diagnostic, code string, sev ir.Severity) bool

HasDiagAt reports whether diags contains a diagnostic with the exact code at the exact severity.

func HasDiagCodeAt

func HasDiagCodeAt(diags []ir.Diagnostic, code, pointer string) bool

HasDiagCodeAt reports whether diags carries code at exactly pointer.

func HolderSpec

func HolderSpec(version, p, rest string) string

HolderSpec is a document of the version declaring Holder, whose property p is written as p, beside the schemas Plain and Pet and those in rest.

func IndexBy

func IndexBy[T any, K comparable](items []T, key func(T) K) map[K]T

IndexBy builds a lookup keyed by key(item), the shape behind every hand-rolled "m := map[K]T{}; for _, x := range xs { m[key(x)] = x }" loop these suites used to repeat per test.

func NestedMerges

func NestedMerges(levels int, body string) string

NestedMerges writes body, a flow mapping, merged in through levels `<<` keys each naming the next in place: `{<<: {<<: body}}` for two. One level past nodeview.MergeDepthLimit is a mapping the parser reads whole and the compiler's view reads short of body.

func NodeConstraints

func NodeConstraints(t TB, td ir.TypeDef) *ir.Constraints

NodeConstraints returns the constraints on a Scalar, list, map or tuple, and fails on any other node.

func ParamBySource

func ParamBySource(op ir.Operation, name string) (ir.Parameter, bool)

ParamBySource returns the operation's logical parameter with the given source name.

func PathKeyFragments

func PathKeyFragments() map[string]int

PathKeyFragments maps Paths Object keys to where the fragment each carries begins, the index of its "#", or -1 where it carries none. The lowering and the rule table each split a key there (docs/compilers/openapi.md#path-keys), so both are held to this one table: a key split apart would lower to a template whose expressions its path parameters are not checked against.

func PathsSpec

func PathsSpec(paths string) string

PathsSpec wraps a paths block in a minimal 3.1 document with no components.

func PathsSpecVer

func PathsSpecVer(version, paths string) string

PathsSpecVer wraps a paths block in a minimal document of the given OpenAPI version, with no components.

func PointersOf

func PointersOf(diags []ir.Diagnostic, code string) []jsontext.Pointer

PointersOf returns the pointers diags report code at, sorted.

func Positions

func Positions(ctx context.Context, t TB, doc *soa.OpenAPI) []jsontext.Pointer

Positions returns the pointers a differential over doc asks about: each place the model's walk reaches, each path through the tree the model was built from, each path below an internal $ref's target read through the $ref, and each of those with a token appended that names nothing, an index, the empty key, an escape or a schema keyword. A read that answers otherwise than the library's at any of them shows.

func PreservationClaims

func PreservationClaims(diags []ir.Diagnostic) []string

PreservationClaims returns the messages announcing that something was kept under Unmodeled. The unpreservable report is excluded by code rather than by wording: it says a construct "could not be kept verbatim under Unmodeled", which contains the phrase and is the opposite of a claim.

func PropsByWire

func PropsByWire(props []ir.Property) map[string]ir.Property

PropsByWire indexes a model's properties by wire name.

func RequireNoErrorDiags

func RequireNoErrorDiags(t TB, diags []ir.Diagnostic)

RequireNoErrorDiags fails the test if any diagnostic has error severity, reporting the first offending diagnostic.

func RootMergeChain

func RootMergeChain(levels int, leaf, own string) []byte

RootMergeChain writes a document whose root merges a chain of levels anchored mappings, the innermost holding leaf, and writes own after the merge.

func ScalarNode

func ScalarNode(tag, val string) *yaml.Node

ScalarNode builds a bare scalar yaml.Node with the given tag and value.

func SchemaFromYAML

func SchemaFromYAML(ctx context.Context, t TB, body string) *oas3.JSONSchema[oas3.Referenceable]

SchemaFromYAML unmarshals body as a JSONSchema, keeping the reference and boolean forms a bare *oas3.Schema cannot represent.

func SourceOf

func SourceOf(src string) compilers.Source

SourceOf wraps a spec string as a compilers.Source.

func SpecFiles

func SpecFiles(t TB, root string) []string

SpecFiles returns every spec under root, in filepath.WalkDir's lexical order: a .yaml, .yml or .json file that is no .golden.json IR snapshot, the filter internal/harness sweeps a directory with.

func StrNode

func StrNode(val string) *yaml.Node

StrNode builds a bare string-scalar yaml.Node.

func YAMLDocument

func YAMLDocument(t TB, src string) *yaml.Node

YAMLDocument parses src as a document tree and returns its document node, the node a loader indexes and hands on.

func YAMLNode

func YAMLNode(t TB, src string) *yaml.Node

YAMLNode parses a YAML snippet and returns its root value node (the document node's single content child), matching what schema fields expose.

Types

type TB

type TB interface {
	Helper()
	Errorf(format string, args ...any)
	FailNow()
	Fatalf(format string, args ...any)
}

TB is the subset of *testing.T these helpers need.

It is an interface rather than *testing.T so this package's own tests can drive the failure branches with a recording stub, the way ir/irtest does: a helper that aborts a real test cannot have its abort path covered.

Jump to

Keyboard shortcuts

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