match

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 25 Imported by: 0

Documentation

Overview

Package match provides request matchers, such as Equal, JSONPath, All and Not. The mock builders of the protocol packages take them to match parts of a request.

How values compare

Every matcher compares values by one rule, the same that mock files and settings read values by. A value has a class: nil, a bool, text (a string or a byte slice), a number (any Go int, uint or float), a list (another slice, or an array), an object (a map with string keys), or another value, such as a struct.

Values of one class compare by value. Bools and text are equal when they are the same. Numbers are equal when their exact values are, whatever their Go types: 10, int64(10) and 10.0 are equal, 1.5 is never 1, and an int64 above 2^53 is never the float64 nearest to it. Lists are equal item by item, in order, and objects member by member. Other values compare with reflect.DeepEqual.

Most of a request is text: its path, query, headers and form values, and a body that isn't JSON. So two readings cross classes, for Equal and the matchers built on it, IsIn, Contain and ItemsMatch:

  • text compared with a number reads as a number when it is written in the JSON number grammar: Equal(10) matches the query value "10" and "1e1", but not "010", "+10" or " 10";
  • anything compared with a bool reads as one the way strconv.ParseBool reads text: Equal(true) matches true, "true", "t", "1" and the number 1.

Nothing else crosses classes: no number equals the character of its value, so Equal(49) doesn't match "1", and text never equals a list. Equal isn't transitive: "1.0" and "1" both equal 1, but not each other. StrictEqual and EqualJSON read no text at all, but still compare numbers by value: StrictEqual(1) matches a JSON 1.0, but not "1". EqualBytes compares the bytes of text, exactly.

The order matchers, such as GreaterThan, compare numbers, and text that reads as one, by their exact values. Truthy and Falsy read bools the way Equal does; nil is neither true nor false. Len counts the bytes of text, the items of a list and the members of an object.

Some matchers read text as a document: EqualJSON and JSONSchema as JSON, and EqualXML and XPath as XML. The date and time matchers, such as Before, read text as a date and time, and compare instants, or wall clocks with LocalTime. Text they can't read doesn't match.

A value of a class a matcher doesn't take, such as a number for HasPrefix or a missing field for GreaterThan, doesn't match. It isn't an error: a matcher returns an error only when user code does, as in Function, since an error stops the search for a mock.

Example
package main

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/caffeine-projects/vlatte/match"
	"github.com/caffeine-projects/vlatte/mockhttp"
)

func main() {
	m := mockhttp.MustNew(mockhttp.Setup().Silent())
	m.MustStart()
	defer m.Close()

	// Each matcher matches a part of the request: a header, a query value, a field of the JSON body.
	m.MustMock(mockhttp.Postf("/orders").
		Header("Authorization", match.HasPrefix("Bearer ")).
		Query("priority", match.IsIn([]string{"low", "high"})).
		Body(match.JSONPath("$.items[0].qty", match.GreaterThan(0))).
		Reply(mockhttp.Created()))

	send := func(query, body string) int {
		req, err := http.NewRequest(http.MethodPost, m.URL("/orders?"+query), strings.NewReader(body))
		if err != nil {
			panic(err)
		}

		req.Header.Set("Authorization", "Bearer token")
		req.Header.Set("Content-Type", "application/json")

		res, err := http.DefaultClient.Do(req)
		if err != nil {
			panic(err)
		}

		res.Body.Close()

		return res.StatusCode
	}

	fmt.Println(send("priority=high", `{"items": [{"qty": 2}]}`))
	fmt.Println(send("priority=urgent", `{"items": [{"qty": 2}]}`))
	fmt.Println(send("priority=low", `{"items": [{"qty": 0}]}`))
}
Output:
201
418
418

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Accept added in v1.2.0

func Accept(mediaType string, offers ...string) vlatte.Matcher

Accept matches the values of an Accept header, a list of them or one string, when mediaType is the one of offers, the media types an operation answers with, that the client prefers: the offer the heaviest range takes, the first of offers on a tie. A range with q=0 refuses its media types. A request without Accept, or with only ranges that don't parse, takes the first offer. Media types ignore case and parameters. Without offers, mediaType is the only one; Accept panics when offers doesn't hold mediaType.

Give each representation of an operation its own mock with an Accept of the same offers: the client's q-values, not the order of the mocks, decide which one answers. NotAcceptable matches the requests none of them take.

func After

func After(expected time.Time, opts ...DateTimeOption) vlatte.Matcher

After matches a date and time after expected. It reads values as Before does.

func AfterNow

func AfterNow(opts ...DateTimeOption) vlatte.Matcher

AfterNow matches a date and time after the time it is matched at, in UTC, as After matches one after a given time.

func All

func All(matchers ...vlatte.Matcher) vlatte.Matcher

All matches when all the given matchers pass.

Example
package main

import (
	"context"
	"fmt"

	"github.com/caffeine-projects/vlatte"
	"github.com/caffeine-projects/vlatte/match"
)

// matches reports whether m matches v, as a mock server asks it of a part of a request.
func matches(m vlatte.Matcher, v any) bool {
	ok, err := m.Match(vlatte.NewMatcherArg(context.Background(), vlatte.NewExplanation(), v))
	if err != nil {
		panic(err)
	}

	return ok
}

func main() {
	// A version tag: starts with v, has no spaces, and isn't a release candidate.
	tag := match.All(
		match.HasPrefix("v"),
		match.Not(match.Contain(" ")),
		match.Not(match.Contain("-rc")),
	)

	for _, v := range []string{"v1.2.0", "v1.3.0-rc.1", "1.2.0"} {
		fmt.Println(v, matches(tag, v))
	}
}
Output:
v1.2.0 true
v1.3.0-rc.1 false
1.2.0 false

func Any

func Any(matchers ...vlatte.Matcher) vlatte.Matcher

Any matches when any of the given matchers pass.

func Anything

func Anything() vlatte.Matcher

Anything is an empty matcher that always passes.

func Before

func Before(expected time.Time, opts ...DateTimeOption) vlatte.Matcher

Before matches a date and time before expected. The value is a time.Time, or text: a date and time in RFC 3339, in ISO 8601 without a zone, or in one of the formats of HTTP dates, unless ActualFormat gives its layout. Other values, and text in none of those formats, don't match.

A value without a zone is read in time.Local when expected has one; LocalTime compares wall clocks instead. ExpectedOffset, TruncateExpected and TruncateActual shift the dates and times compared. Truncations take the days and hours of expected's UTC offset, at expected: a named zone, such as Europe/Madrid, keeps its offset of that date, the one a description of the matcher writes.

func BeforeNow

func BeforeNow(opts ...DateTimeOption) vlatte.Matcher

BeforeNow matches a date and time before the time it is matched at, in UTC, as Before matches one before a given time: BeforeNow(ExpectedOffset(3, Days)) matches one before 3 days from now.

func Both

func Both(first, second vlatte.Matcher) vlatte.Matcher

Both matches when both filters pass.

func Contain

func Contain(expected any) vlatte.Matcher

Contain matches text holding expected, when expected is text; a list holding an item equal to expected, by Equal's rule; or an object holding a key equal to expected.

func Containf

func Containf(format string, a ...any) vlatte.Matcher

Containf is shorthand to format the expected value.

func Delegate

func Delegate(name string, predicate func(arg vlatte.MatcherArg) (bool, error)) vlatte.Matcher

Delegate creates a Matcher with the given name that calls predicate with the whole vlatte.MatcherArg, and returns its error as is. Unlike Function, predicate reads more than the value.

func EQI

func EQI(expected string) vlatte.Matcher

EQI is an alias to EqualIgnoreCase.

func EQJ

func EQJ(expected any, opts ...EqualJSONOption) vlatte.Matcher

EQJ is an alias for EqualJSON.

func EQS

func EQS(expected any) vlatte.Matcher

EQS is an alias for StrictEqual.

func EQX

func EQX(expected string, opts ...EqualXMLOption) vlatte.Matcher

EQX is an alias for EqualXML.

func Each

func Each(matcher vlatte.Matcher) vlatte.Matcher

Each matches a list whose items, or an object whose members, all match matcher; other values don't match.

func Either

func Either(first, second vlatte.Matcher) vlatte.Matcher

Either matches when either filter passes.

func Empty

func Empty() vlatte.Matcher

Empty matches nil, and text, a list or an object of no items; other values don't match.

func Eq

func Eq(expected any) vlatte.Matcher

Eq is an alias to Equal.

func Equal

func Equal(expected any) vlatte.Matcher

Equal matches a value equal to expected, by the rule in the package doc: numbers by their exact value whatever their Go types, text read as a number or a bool when compared with one, lists item by item. So Equal(10) matches 10.0, an int64 10 and the query value "10", but not "010".

Example
package main

import (
	"context"
	"fmt"

	"github.com/caffeine-projects/vlatte"
	"github.com/caffeine-projects/vlatte/match"
)

// matches reports whether m matches v, as a mock server asks it of a part of a request.
func matches(m vlatte.Matcher, v any) bool {
	ok, err := m.Match(vlatte.NewMatcherArg(context.Background(), vlatte.NewExplanation(), v))
	if err != nil {
		panic(err)
	}

	return ok
}

func main() {
	// Text read as a number equals the number, whatever the Go type of either.
	fmt.Println(matches(match.Equal(10), "10"))
	fmt.Println(matches(match.Equal(10), 10.0))
	fmt.Println(matches(match.Equal(10), "010")) // not the JSON number grammar

	// Text read as a bool equals the bool.
	fmt.Println(matches(match.Equal(true), "1"))

	// StrictEqual reads no text.
	fmt.Println(matches(match.StrictEqual(10), "10"))
}
Output:
true
true
false
true
false

func EqualBytes

func EqualBytes(expected []byte) vlatte.Matcher

EqualBytes matches text, a string or a byte slice, whose bytes are expected, exactly: unlike Equal, it reads no text as a number or a bool. It matches a body that isn't UTF-8 text, such as an image, and describes the bytes in standard base64, as mock files write them: [equalbytes, "//4A"].

func EqualDateTime

func EqualDateTime(expected time.Time, opts ...DateTimeOption) vlatte.Matcher

EqualDateTime matches a date and time equal to expected: the same instant, whatever its zone. It reads values as Before does.

func EqualDateTimeNow

func EqualDateTimeNow(opts ...DateTimeOption) vlatte.Matcher

EqualDateTimeNow matches a date and time equal to the time it is matched at, in UTC. It is of use with truncations: EqualDateTimeNow(TruncateExpected(FirstHourOfDay), TruncateActual(FirstHourOfDay)) matches any time of today, in UTC.

func EqualIgnoreCase

func EqualIgnoreCase(expected string) vlatte.Matcher

EqualIgnoreCase compares the expected value with the incoming request value ignoring the case.

func EqualIgnoreCasef

func EqualIgnoreCasef(format string, a ...any) vlatte.Matcher

EqualIgnoreCasef is short-hand to format the expected value.

func EqualJSON

func EqualJSON(expected any, opts ...EqualJSONOption) vlatte.Matcher

EqualJSON matches a value whose JSON equals expected, by StrictEqual's rule. expected is JSON text, or a value of any type, written as JSON. A value that is text, such as a request body, is read as JSON; any other value is written as JSON. It panics when expected isn't JSON, or can't be written as JSON.

By default the JSON must be equal in full: lists in the same order, and objects with the same members. Options loosen it: IgnoreArrayOrder and IgnoreExtraElements.

Example
package main

import (
	"context"
	"fmt"

	"github.com/caffeine-projects/vlatte"
	"github.com/caffeine-projects/vlatte/match"
)

// matches reports whether m matches v, as a mock server asks it of a part of a request.
func matches(m vlatte.Matcher, v any) bool {
	ok, err := m.Match(vlatte.NewMatcherArg(context.Background(), vlatte.NewExplanation(), v))
	if err != nil {
		panic(err)
	}

	return ok
}

func main() {
	// The order of the members doesn't matter, nor, with IgnoreArrayOrder, that of the items.
	expected := match.EqualJSON(`{"id": 1, "tags": ["a", "b"]}`, match.IgnoreArrayOrder())

	fmt.Println(matches(expected, `{"tags": ["b", "a"], "id": 1}`))
	fmt.Println(matches(expected, `{"tags": ["b", "a"], "id": 1, "extra": true}`))
}
Output:
true
false

func EqualXML

func EqualXML(expected string, opts ...EqualXMLOption) vlatte.Matcher

EqualXML matches text, such as a request body, that is an XML document equal to expected. Documents are equal when their elements are, as XML means them rather than as written:

  • comments, processing instructions and the doctype don't count;
  • text is trimmed, and text that is only white space, such as indentation between elements, doesn't count;
  • attributes are equal in any order, and namespace declarations aren't attributes;
  • names are equal by namespace URI and local name, whatever their prefixes;
  • child elements and text are equal in order.

IgnoreChildOrder and XMLNamespaces change the last two. A value that isn't text, or isn't XML, doesn't match. EqualXML panics when expected isn't an XML document.

func Equalf

func Equalf(format string, a ...any) vlatte.Matcher

Equalf returns true if the matcher value is equal to the given parameter value.

func Falsy

func Falsy() vlatte.Matcher

Falsy matches a value that reads as false the way strconv.ParseBool reads text: false, "false", "f", "0" or 0. Nil, and values that don't read as a bool, don't match.

func Field

func Field(path string, matcher vlatte.Matcher) vlatte.Matcher

Field is an alias for JSONPath. It panics if path is not a valid JSONPath expression.

func Function

func Function(fn func(v any) (bool, error)) vlatte.Matcher

Function creates an anonymous Matcher using the given function.

func GT

func GT[N Number](expected N) vlatte.Matcher

GT is an alias for GreaterThan.

func GTE

func GTE[N Number](expected N) vlatte.Matcher

GTE is an alias for GreaterThanOrEqual.

func GlobMatch

func GlobMatch(pattern string) vlatte.Matcher

GlobMatch matches the value against a glob pattern.

func GreaterThan

func GreaterThan[N Number](expected N) vlatte.Matcher

GreaterThan matches a number, or text that reads as one, greater than expected. Numbers compare by their exact value, whatever their Go types; other values don't match.

func GreaterThanOrEqual

func GreaterThanOrEqual[N Number](expected N) vlatte.Matcher

GreaterThanOrEqual matches a number, or text that reads as one, greater than or equal to expected. Numbers compare by their exact value, whatever their Go types; other values don't match.

func HasKey

func HasKey(path string) vlatte.Matcher

HasKey matches when the value (map or struct) has the given key/path. It panics if path is not a valid JSONPath expression.

func HasPrefix

func HasPrefix(prefix string) vlatte.Matcher

HasPrefix matches when the value has the given prefix.

func HasSuffix

func HasSuffix(suffix string) vlatte.Matcher

HasSuffix matches when the value has the given suffix.

func IsIn

func IsIn[T any](items []T) vlatte.Matcher

IsIn matches a value equal to one of items, by Equal's rule, so IsIn([]int{1, 2}) matches the query value "2".

func Item

func Item(index int, matcher vlatte.Matcher) vlatte.Matcher

Item applies matcher to the item of a list at index. A value that isn't a list, or is too short, doesn't match. It panics when index is negative.

func ItemsMatch

func ItemsMatch[T any](items []T) vlatte.Matcher

ItemsMatch matches a list holding items in any order, and nothing else: each item of the list pairs with its own item of items. An item of items that is a vlatte.Matcher pairs with the list items it matches, such as ItemsMatch([]vlatte.Matcher{Equal(1), HasPrefix("a")}); any other item pairs with the list items equal to it, by Equal's rule.

func JSONPath

func JSONPath(path string, matcher vlatte.Matcher) vlatte.Matcher

JSONPath applies the provided matcher to the JSON field value in the given path. It panics if path is not a valid JSONPath expression.

Example
package main

import (
	"context"
	"fmt"

	"github.com/caffeine-projects/vlatte"
	"github.com/caffeine-projects/vlatte/match"
)

// matches reports whether m matches v, as a mock server asks it of a part of a request.
func matches(m vlatte.Matcher, v any) bool {
	ok, err := m.Match(vlatte.NewMatcherArg(context.Background(), vlatte.NewExplanation(), v))
	if err != nil {
		panic(err)
	}

	return ok
}

func main() {
	body := `{"user": {"name": "Ada", "roles": ["admin", "dev"]}}`

	fmt.Println(matches(match.JSONPath("$.user.name", match.Equal("Ada")), body))
	fmt.Println(matches(match.JSONPath("$.user.roles", match.Contain("admin")), body))
	fmt.Println(matches(match.JSONPath("$.user.email", match.Present()), body))
}
Output:
true
true
false

func JSONSchema

func JSONSchema(schema string, opts ...JSONSchemaOption) vlatte.Matcher

JSONSchema matches a value whose JSON conforms to schema, a JSON Schema written as JSON text. A value that is text, such as a request body, is read as JSON; any other value is written as JSON. Formats, such as "email", are checked.

The schema is of the draft its $schema names, or else of 2020-12, unless SchemaDraft says otherwise. It loads nothing else: a $ref to anything outside the schema fails, so a mock file can't make the server read files or the network. JSONSchema panics when schema isn't a JSON Schema.

func JWT

func JWT(matcher vlatte.Matcher) vlatte.Matcher

JWT matches a JWT without verifying it: it checks neither the signature, so a token anyone could have signed matches, nor the exp and nbf claims. To match only tokens signed by keys you trust and within their lifetime, use SignedJWT.

JWT decodes the token, a compact JWS whose payload is a JSON object, and matches matcher against {"header": {...}, "claims": {...}}, so other matchers read it: JWT(JSONPath("$.claims.sub", Equal("ana"))). The value is the token, or an Authorization header value with it, such as "Bearer <token>": a scheme before the token is skipped, whatever it is.

Example
package main

import (
	"context"
	"fmt"

	"github.com/caffeine-projects/vlatte"
	"github.com/caffeine-projects/vlatte/match"
)

// matches reports whether m matches v, as a mock server asks it of a part of a request.
func matches(m vlatte.Matcher, v any) bool {
	ok, err := m.Match(vlatte.NewMatcherArg(context.Background(), vlatte.NewExplanation(), v))
	if err != nil {
		panic(err)
	}

	return ok
}

func main() {
	// The Authorization header of a request: a JWT whose claims are {"sub": "ana", "scope": "read"}. JWT reads the
	// claims without checking who signed them; SignedJWT checks that too.
	header := "Bearer eyJhbGciOiJub25lIn0.eyJzdWIiOiJhbmEiLCJzY29wZSI6InJlYWQifQ."

	fmt.Println(matches(match.JWT(match.JSONPath("$.claims.sub", match.Equal("ana"))), header))
	fmt.Println(matches(match.JWT(match.JSONPath("$.claims.scope", match.Equal("write"))), header))
}
Output:
true
false

func LTE

func LTE[N Number](expected N) vlatte.Matcher

LTE is an alias for LessThanOrEqual.

func Len

func Len(length int) vlatte.Matcher

Len matches text of length bytes, or a list or an object of length items; other values don't match. It panics when length is negative.

func LessThan

func LessThan[N Number](expected N) vlatte.Matcher

LessThan matches a number, or text that reads as one, less than expected. Numbers compare by their exact value, whatever their Go types; other values don't match.

func LessThanOrEqual

func LessThanOrEqual[N Number](expected N) vlatte.Matcher

LessThanOrEqual matches a number, or text that reads as one, less than or equal to expected. Numbers compare by their exact value, whatever their Go types; other values don't match.

func Nil

func Nil() vlatte.Matcher

Nil matches when the value is nil.

func Not

func Not(matcher vlatte.Matcher) vlatte.Matcher

Not inverts the result of the given matcher.

func NotAcceptable added in v1.2.0

func NotAcceptable(offers ...string) vlatte.Matcher

NotAcceptable matches the values of an Accept header, as Accept reads them, that take none of offers: every range that matches an offer has q=0, or none does. A request without Accept, or with only ranges that don't parse, takes any offer, so it doesn't match. Without offers, NotAcceptable matches every Accept that parses.

func Peek

func Peek(matcher vlatte.Matcher, action func(v any) error) vlatte.Matcher

Peek runs an action on the value then matches with the inner matcher.

func Predicate

func Predicate(predicate func(v any) bool) vlatte.Matcher

Predicate creates a Matcher function using the given predicate.

func Present

func Present() vlatte.Matcher

Present matches when the value is present (non-zero).

func RegExpr

func RegExpr(expression string) vlatte.Matcher

RegExpr matches text the regular expression matches; other values don't match. It panics when expression isn't a regular expression.

func RequestURI

func RequestURI(expected string) vlatte.Matcher

RequestURI matches a URL whose path and query are those of expected, such as "/items?page=2": the same path, and the same query parameters, each with the same values in the same order, though the parameters can come in any order. Paths compare segment by segment once decoded, so "%41" is "A", but an escaped "%2F" is not a "/". A fragment counts only when expected has one. The scheme and the host don't count. The value is a URL, or text that parses as one: one without a path, such as the target of a CONNECT or mailto:x, doesn't match. It panics when expected isn't a URL.

func SignedJWT

func SignedJWT(keys string, matcher vlatte.Matcher) vlatte.Matcher

SignedJWT is JWT for tokens signed by one of keys: a JWK Set, a single JWK, or PEM public keys or certificates, such as a provider publishes or an app registers. A token passes only when its signature verifies with a key of keys, and fails otherwise:

  • when its alg is "none" or an HMAC one, such as HS256;
  • when its kid names no key, unless keys has keys without a kid, such as PEM ones, which are tried in turn;
  • when a JWK names an alg other than the token's, so a token can't choose how its key is read;
  • when its exp claim is now or past, or its nbf claim future.

The algorithms are RS256, RS384, RS512, PS256, PS384, PS512, ES256, ES384, ES512 and EdDSA. Keys of a JWK Set it can't use, such as encryption keys or keys on other curves, are skipped. SignedJWT panics when keys holds no public key it can use, holds a malformed one, or holds a private one: a mock is no place for it.

func Some

func Some(matcher vlatte.Matcher) vlatte.Matcher

Some matches a list with an item that matches matcher; other values don't match.

func Split

func Split(separator string, matcher vlatte.Matcher) vlatte.Matcher

Split splits the value by separator and matches with the inner matcher.

func StrictEqual

func StrictEqual(expected any) vlatte.Matcher

StrictEqual matches a value equal to expected without reading text, as Equal does otherwise: text never equals a number or a bool. Numbers still compare by their exact value, and lists by their items.

func StrictEqualf

func StrictEqualf(format string, a ...any) vlatte.Matcher

StrictEqualf is short-hand to format the expected value.

func ToLower

func ToLower(matcher vlatte.Matcher) vlatte.Matcher

ToLower lowers the incoming request value case before submitting it to the provided matcher.

func ToUpper

func ToUpper(matcher vlatte.Matcher) vlatte.Matcher

ToUpper uppercases the value and matches with the inner matcher.

func Trim

func Trim(matcher vlatte.Matcher) vlatte.Matcher

Trim trims spaces and matches with the inner matcher.

func Truthy

func Truthy() vlatte.Matcher

Truthy matches a value that reads as true the way strconv.ParseBool reads text: true, "true", "t", "1" or 1. Nil, and values that don't read as a bool, don't match.

func URLPath

func URLPath(expected string) vlatte.Matcher

URLPath compares the URL path with the expected value (glob match).

func URLPathMatch

func URLPathMatch(matcher vlatte.Matcher) vlatte.Matcher

URLPathMatch applies the provided matcher to the URL path.

func URLPathf

func URLPathf(format string, a ...any) vlatte.Matcher

URLPathf compares the URL path with the formatted expected value.

func XOR

func XOR(first, second vlatte.Matcher) vlatte.Matcher

XOR matches when exactly one of the two filters passes.

func XPath

func XPath(expr string, matcher vlatte.Matcher, opts ...XPathOption) vlatte.Matcher

XPath applies matcher to what expr, an XPath 1.0 expression, selects in an XML document: text, such as a request body. matcher gets nil when expr selects nothing, the one result when it selects one, and a list of them when it selects more, as JSONPath does: Some(m) matches when any of them matches. An element is given as its XML, with the namespace declarations its ancestors make, so EqualXML can compare it: its text as written, line breaks included, CDATA as escaped text, and an end tag even when empty, as in <a></a>; an attribute or a text node, as its text; a number, a string or a bool that expr computes, as it is.

A name in expr selects elements whose name is written the same, prefix included, unless XPathNamespace binds its prefix to a namespace URI: then it selects by namespace and local name, whatever prefix the document gives them. local-name() selects by local name alone: /*[local-name()='order']. The document's nodes are XPath 1.0's: its elements, their attributes, its text, white space included, and its comments; processing instructions aren't selected. A value that isn't well-formed XML, with one root element and each prefix bound, doesn't match. XPath panics when expr isn't an XPath expression.

Types

type DateTimeOption

type DateTimeOption interface {
	// contains filtered or unexported methods
}

DateTimeOption configures the date and time matchers, such as Before.

func ActualFormat

func ActualFormat(layout string) DateTimeOption

ActualFormat reads text values in layout, a Go time layout, such as "02/01/2006", rather than in the formats read by default. A value read with a layout that writes no zone has none. Prefer a numeric offset, such as -0700, to a zone abbreviation, MST: Go reads an abbreviation it doesn't know as UTC.

func ExpectedOffset

func ExpectedOffset(n int, unit DateTimeUnit) DateTimeOption

ExpectedOffset moves the expected date and time by n units, back when n is negative, as "now +3 days" does. A month or a year later is the same day of the month, or the last day of a shorter month: January 31 and 1 month is February 28, or 29. A later ExpectedOffset replaces an earlier one.

func LocalTime

func LocalTime() DateTimeOption

LocalTime makes the expected date and time a local one, without a zone: its wall clock is compared with the wall clock of the value, in the value's own zone.

func TruncateActual

func TruncateActual(t Truncation) DateTimeOption

TruncateActual truncates the date and time matched, in the zone of the expected one: with EqualDateTime(march, TruncateActual(FirstDayOfMonth)), any time in March matches, march being March 1, 00:00, and March being the month in march's zone.

func TruncateExpected

func TruncateExpected(t Truncation) DateTimeOption

TruncateExpected truncates the expected date and time, before ExpectedOffset moves it unless TruncateLast is given: AfterNow(ExpectedOffset(15, Days), TruncateExpected(FirstDayOfMonth)) matches after the 16th of this month begins.

func TruncateLast

func TruncateLast() DateTimeOption

TruncateLast makes TruncateExpected apply after ExpectedOffset: EqualDateTimeNow(ExpectedOffset(1, Months), TruncateExpected(LastDayOfMonth), TruncateLast()) is the last day of next month.

type DateTimeUnit

type DateTimeUnit int

DateTimeUnit is a unit of ExpectedOffset.

const (
	Seconds DateTimeUnit = iota + 1
	Minutes
	Hours
	Days
	Weeks
	Months
	Years
)

The units of ExpectedOffset.

func (DateTimeUnit) String

func (u DateTimeUnit) String() string

String returns the name of the unit as mock files write it, such as days.

type EqualJSONOption

type EqualJSONOption interface {
	// contains filtered or unexported methods
}

EqualJSONOption configures EqualJSON.

func IgnoreArrayOrder

func IgnoreArrayOrder() EqualJSONOption

IgnoreArrayOrder makes EqualJSON match lists whose items pair up in any order: each expected item with an item of its own.

func IgnoreExtraElements

func IgnoreExtraElements() EqualJSONOption

IgnoreExtraElements makes EqualJSON ignore what the value has beyond what is expected: object members it doesn't expect, and list items. The expected items of a list must still be there, in order, unless IgnoreArrayOrder is given too: {"a": [1, 3]} matches {"a": [1, 2, 3], "b": 4}, but not {"a": [3, 1]}.

type EqualXMLOption

type EqualXMLOption interface {
	// contains filtered or unexported methods
}

EqualXMLOption configures EqualXML.

func IgnoreChildOrder

func IgnoreChildOrder() EqualXMLOption

IgnoreChildOrder makes EqualXML match elements whose child elements and text pair up in any order: <a><b>1</b><b>2</b></a> matches <a><b>2</b><b>1</b></a>.

func XMLNamespaces

func XMLNamespaces(mode XMLNamespaceMode) EqualXMLOption

XMLNamespaces sets how EqualXML compares the names of elements and attributes.

type JSONSchemaDraft

type JSONSchemaDraft int

JSONSchemaDraft is a version of the JSON Schema specification.

const (
	JSONSchemaDraft4    JSONSchemaDraft = iota + 1 // draft-04
	JSONSchemaDraft6                               // draft-06
	JSONSchemaDraft7                               // draft-07
	JSONSchemaDraft2019                            // 2019-09
	JSONSchemaDraft2020                            // 2020-12
)

The versions of JSON Schema that SchemaDraft takes.

func (JSONSchemaDraft) String

func (d JSONSchemaDraft) String() string

String returns the name of the draft as mock files write it: 4, 6, 7, 2019-09 or 2020-12.

type JSONSchemaOption

type JSONSchemaOption interface {
	// contains filtered or unexported methods
}

JSONSchemaOption configures JSONSchema.

func SchemaDraft

func SchemaDraft(d JSONSchemaDraft) JSONSchemaOption

SchemaDraft sets the draft of a schema of JSONSchema without $schema.

type Number

type Number interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr | ~float32 | ~float64
}

Number is any Go integer or floating-point type: the type of the bound of an order matcher, such as GreaterThan.

type Truncation

type Truncation int

Truncation moves a date and time to the start of a period of the calendar, in its own zone, for TruncateExpected and TruncateActual.

const (
	FirstMinuteOfHour Truncation = iota + 1
	FirstHourOfDay
	FirstDayOfMonth
	FirstDayOfNextMonth
	LastDayOfMonth
	FirstDayOfYear
	FirstDayOfNextYear
	LastDayOfYear
)

The truncations.

func (Truncation) String

func (t Truncation) String() string

String returns the name of the truncation as mock files write it, such as first day of month.

type XMLNamespaceMode

type XMLNamespaceMode int

XMLNamespaceMode is how EqualXML compares the names of elements and attributes.

const (
	// XMLNamespacesByURI compares names by namespace URI and local name, whatever their prefixes: the default.
	XMLNamespacesByURI XMLNamespaceMode = iota
	// XMLNamespacesStrict compares the prefixes of names too.
	XMLNamespacesStrict
	// XMLNamespacesIgnored reads no namespaces: a name is compared as written, prefix included, a prefix needs no
	// declaration, and namespace declarations are attributes like any other.
	XMLNamespacesIgnored
)

The ways EqualXML reads namespaces.

func (XMLNamespaceMode) String

func (m XMLNamespaceMode) String() string

String returns the name of the mode as mock files write it: uri, strict or none.

type XPathOption

type XPathOption interface {
	// contains filtered or unexported methods
}

XPathOption configures XPath.

func XPathNamespace

func XPathNamespace(prefix, uri string) XPathOption

XPathNamespace binds prefix, in the expression of XPath, to the namespace uri.

Directories

Path Synopsis
internal
timetext
Package timetext reads dates and times as the date and time matchers write them.
Package timetext reads dates and times as the date and time matchers write them.
Package matchbuild builds matchers from the matcher specs of mock files: a list whose first item names the matcher and whose other items are its arguments, such as ["contains", "x"] or ["jsonpath", "$.a", ["gt", 1]].
Package matchbuild builds matchers from the matcher specs of mock files: a list whose first item names the matcher and whose other items are its arguments, such as ["contains", "x"] or ["jsonpath", "$.a", ["gt", 1]].
Package matchopenapi holds the openapi matcher of mock files, [openapi, {spec, operation, check}], which matches a request that keeps the contract an OpenAPI 3 spec gives one of its operations.
Package matchopenapi holds the openapi matcher of mock files, [openapi, {spec, operation, check}], which matches a request that keeps the contract an OpenAPI 3 spec gives one of its operations.
Package matchrepeat limits how many times a mock is served: Repeat matches until a mock has been served the given number of times.
Package matchrepeat limits how many times a mock is served: Repeat matches until a mock has been served the given number of times.
Package matchscenario serves mocks in turn, as a scenario moves from state to state.
Package matchscenario serves mocks in turn, as a scenario moves from state to state.
scenariotest
Package scenariotest checks that a mock server serves scenarios as github.com/caffeine-projects/vlatte/match/matchscenario defines them.
Package scenariotest checks that a mock server serves scenarios as github.com/caffeine-projects/vlatte/match/matchscenario defines them.

Jump to

Keyboard shortcuts

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