engine

package
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Overview

Package engine runs request files: it renders each entry, sends the request, and evaluates captures and asserts on the response. It never prints; everything a front end shows comes from events and results.

Example

Run a request file against a local server and inspect the result.

package main

import (
	"context"
	"fmt"
	"io"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"

	"github.com/nhtera/sonde/engine"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		_, _ = io.WriteString(w, `{"status": "ok", "items": [1, 2, 3]}`)
	}))
	defer srv.Close()

	dir, _ := os.MkdirTemp("", "example")
	defer os.RemoveAll(dir) //nolint:errcheck // example cleanup
	src := []byte(`GET {{base}}/health
HTTP 200
[Captures]
count: jsonpath "$.items" count
[Asserts]
jsonpath "$.status" == "ok"
`)
	r := engine.NewRunner(engine.Options{Variables: map[string]any{"base": srv.URL}})
	defer r.Close() //nolint:errcheck // example cleanup
	res, err := r.RunSource(context.Background(), filepath.Join(dir, "health.hurl"), src)
	if err != nil {
		fmt.Println(err)
		return
	}
	entry := res.Entries[0]
	fmt.Println("success:", res.Success)
	fmt.Println("status:", entry.Calls[0].Response.Status)
	fmt.Println("captured:", entry.Captures[0].Name, entry.Captures[0].Value)
}
Output:
success: true
status: 200
captured: count 3

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Assert

type Assert struct {
	Line int
	Err  *Error
}

Assert is the outcome of one assert (implicit or explicit); Err is nil when it holds.

type Call

type Call struct {
	Request  exchange.Request
	Response *exchange.Response
	// Timings are the timings of Response (the same as Response.Timings).
	Timings exchange.Timings
}

Call is one HTTP exchange (redirects produce several).

type Capture

type Capture struct {
	Name  string
	Value Value
}

Capture is a captured variable.

type ContractEvaluated

type ContractEvaluated struct {
	Index      int
	Violations []Violation
}

ContractEvaluated is sent after the response of an entry was checked against the contract. Violations hold raw values.

type Cookie struct {
	Domain           string
	IncludeSubdomain bool
	Path             string
	HTTPS            bool
	// Expires is a Unix time in seconds; 0 for a session cookie, 1 for a
	// cookie the server expired.
	Expires  int64
	Name     string
	Value    string
	HTTPOnly bool
}

Cookie is a cookie of the cookie store (Netscape fields).

func (Cookie) Netscape

func (c Cookie) Netscape() string

Netscape formats the cookie as a line of a Netscape cookie file, without the line terminator.

type CurlEntry

type CurlEntry struct {
	// Index is the entry's 1-based position in the file, exactly as
	// Options.FromEntry/ToEntry address it; RenderCurl never renumbers.
	Index int
	// Command is the curl command line, secrets redacted exactly like a
	// run's --curl FILE. Empty when Err is set.
	Command string
	// Undefined lists, in first-use order, the variable names this entry
	// referenced with no defined value (typically one only a capture of
	// an earlier entry, never run here, would set): each stays a literal
	// {{name}} in Command instead of failing. Scoped to this entry alone
	// — a name undefined here is reported again for every other entry
	// that also references it, never assumed defined from one entry to
	// the next.
	Undefined []string
	// Skipped says why an entry has no Command and no Err: a WebSocket or
	// gRPC entry, which curl can not run. Exactly one of Command, Err and
	// Skipped is set.
	Skipped string
	// Err is set instead of Command when this one entry could not be
	// rendered at all: a value with its own strict syntax (an
	// [Options] repeat/skip/max-redirs/... expecting a number or
	// boolean, not a bare {{name}} it has no source for) or a body file
	// this call's FileRoot cannot supply (missing, unreadable, or not a
	// regular file). It is an *Error for an evaluation error (an invalid
	// option value, an undefined variable where no placeholder fits);
	// other failures, such as a body file that can't be read, are plain
	// errors. Every other entry is still attempted.
	Err error
}

CurlEntry is one entry rendered to its curl command line by RenderCurl, without sending anything.

type EntryFinished

type EntryFinished struct {
	Result *EntryResult
}

EntryFinished is sent after an attempt of an entry.

type EntryResult

type EntryResult struct {
	Index int // 1-based
	// Line is the line of the request method.
	Line     int
	Calls    []Call
	Captures []Capture
	Asserts  []Assert
	// Violations are the contract findings of the final response (see
	// Options.Validator): those that are not warnings also appear in
	// Asserts, located at the status line.
	Violations []Violation
	// Errors are the errors of this attempt; an error whose Assert method
	// reports true is an assert failure.
	Errors           []*Error
	TransferDuration time.Duration
	Compressed       bool
	// Curl is the equivalent curl command line of the request.
	Curl string
	// Retried is set when the attempt failed and the entry was run again;
	// its errors do not count.
	Retried bool
}

EntryResult is one attempt of an entry.

type EntryStarted

type EntryStarted struct {
	Index int
	Retry int
	// Last is the index of the last entry the run executes (the file's
	// entry count, or the --to-entry limit).
	Last int
}

EntryStarted is sent before an entry (or one of its retries) runs.

type Error

type Error struct {
	// contains filtered or unexported fields
}

Error is an error of a run: a parse error (kind ErrorParse) or an error of one entry. It carries the file it belongs to, so Render needs no arguments. Message texts are for people and may change in any version. Errors come from the engine: the zero Error holds nothing and every method returns its zero result.

func (*Error) Actual

func (e *Error) Actual() string

Actual is the actual value of a failed assert or of a value with an unexpected type, as displayed; "" when the error has none.

func (*Error) Assert

func (e *Error) Assert() bool

Assert reports whether the error is an assert failure (the sonde CLI exits with 4) rather than a runtime error (exit 3). It is false for a parse error.

func (*Error) Description

func (e *Error) Description() string

Description is the error's title, e.g. "Assert status code".

func (*Error) Error

func (e *Error) Error() string

Error returns the error on one line: "<description>: <message>" (a parse error starts with "<line>:<col>: ").

func (*Error) Expected

func (e *Error) Expected() string

Expected is the expected value of a failed assert or type, as displayed; "" when the error has none.

func (*Error) Kind

func (e *Error) Kind() ErrorKind

Kind classifies the error.

func (*Error) Message

func (e *Error) Message() string

Message is the explanation shown under the source line.

func (*Error) Render

func (e *Error) Render() string

Render formats the error the way the sonde CLI prints it: the description, the location, the source lines involved and the message.

func (*Error) RenderColor

func (e *Error) RenderColor() string

RenderColor is Render with ANSI colors.

func (*Error) Span

func (e *Error) Span() Span

Span locates the error in its file. A parse error is a position: Start and End are equal.

type ErrorKind

type ErrorKind string

ErrorKind classifies an Error. New kinds may be added in minor versions: switch on it with a default case.

const (
	// ErrorParse: the file does not parse (UnitResult.ParseError).
	ErrorParse ErrorKind = "parse"

	ErrorAssertFailure                ErrorKind = "assert-failure"
	ErrorAssertStatus                 ErrorKind = "assert-status"
	ErrorAssertVersion                ErrorKind = "assert-version"
	ErrorAssertHeaderValue            ErrorKind = "assert-header-value"
	ErrorAssertBodyValue              ErrorKind = "assert-body-value"
	ErrorAssertBodyDiff               ErrorKind = "assert-body-diff"
	ErrorContractViolation            ErrorKind = "contract-violation"
	ErrorExpressionInvalidType        ErrorKind = "expression-invalid-type"
	ErrorUndefinedVariable            ErrorKind = "undefined-variable"
	ErrorUnrenderable                 ErrorKind = "unrenderable"
	ErrorInvalidOptionValue           ErrorKind = "invalid-option-value"
	ErrorInvalidURL                   ErrorKind = "invalid-url"
	ErrorInvalidJSON                  ErrorKind = "invalid-json"
	ErrorInvalidRegex                 ErrorKind = "invalid-regex"
	ErrorInvalidXPathEval             ErrorKind = "invalid-xpath-eval"
	ErrorQueryInvalidJSON             ErrorKind = "query-invalid-json"
	ErrorQueryInvalidJSONPath         ErrorKind = "query-invalid-jsonpath"
	ErrorQueryInvalidXML              ErrorKind = "query-invalid-xml"
	ErrorQueryHeaderNotFound          ErrorKind = "query-header-not-found"
	ErrorNoQueryResult                ErrorKind = "no-query-result"
	ErrorNoFilterResult               ErrorKind = "no-filter-result"
	ErrorFilterDecode                 ErrorKind = "filter-decode"
	ErrorFilterDateParsing            ErrorKind = "filter-date-parsing"
	ErrorFilterInvalidEncoding        ErrorKind = "filter-invalid-encoding"
	ErrorFilterInvalidInputValue      ErrorKind = "filter-invalid-input-value"
	ErrorFilterInvalidInputType       ErrorKind = "filter-invalid-input-type"
	ErrorFilterInvalidFormatSpecifier ErrorKind = "filter-invalid-format-specifier"
	ErrorFilterMissingInput           ErrorKind = "filter-missing-input"
	// ErrorHTTP: a transport failure or a body that can't be decoded.
	ErrorHTTP                   ErrorKind = "http"
	ErrorFileReadAccess         ErrorKind = "file-read-access"
	ErrorFileWriteAccess        ErrorKind = "file-write-access"
	ErrorUnauthorizedFileAccess ErrorKind = "unauthorized-file-access"
	ErrorBinaryOutput           ErrorKind = "binary-output"
	ErrorPossibleLoggedSecret   ErrorKind = "possible-logged-secret"
	ErrorUnsupportedSecretType  ErrorKind = "unsupported-secret-type"
	// ErrorStream: a WebSocket step that failed, or a sondeStream field
	// that does not apply to the entry's protocol.
	ErrorStream ErrorKind = "stream"
	// ErrorGRPC: a gRPC call that failed: a status other than OK that the
	// entry does not check, descriptors that could not be loaded, or a
	// message that does not match its type.
	ErrorGRPC ErrorKind = "grpc"
)

Error kinds.

type Event

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

Event is something a front end may show while a unit runs. Events are delivered serially. Log texts are redacted; results carried by events (and returned by the runner) hold raw values, to be passed through UnitResult.Redact (or Runner.Redact, for a run without data rows) before they are shown.

type Field

type Field struct {
	Key   string
	Value Value
}

Field is a member of an object Value.

type HTTPOptions

type HTTPOptions struct {
	AWSSigV4          string
	CACert            string
	ClientCert        string
	ClientKey         string
	Compressed        bool
	ConnectTimeout    time.Duration
	ConnectTo         []string
	Digest            bool
	FollowLocation    bool
	LocationTrusted   bool
	Headers           []string // "Name: value"
	HTTPVersion       HTTPVersion
	Insecure          bool
	IPResolve         IPResolve
	MaxFilesize       int64
	LimitRate         int64
	MaxRedirects      int // -1: unlimited; 0 here means the default (50)
	Negotiate         bool
	Netrc             bool
	NetrcFile         string
	NetrcOptional     bool
	NetrcAllowReroute bool
	NoProxy           string
	NTLM              bool
	PathAsIs          bool
	PinnedPublicKey   string
	Proxy             string
	Resolve           []string
	Timeout           time.Duration
	UnixSocket        string
	User              string
	UserAgent         string
}

HTTPOptions are the transport options.

type HTTPVersion

type HTTPVersion int

HTTPVersion is the requested protocol.

const (
	HTTPDefault HTTPVersion = iota
	HTTP10
	HTTP11
	HTTP2
	HTTP3
)

Protocol versions.

type IPResolve

type IPResolve int

IPResolve restricts name resolution to one IP family.

const (
	IPAny IPResolve = iota
	IPv4
	IPv6
)

IP families.

type Job

type Job struct {
	Name   string
	Source []byte
	// Variables and Secrets apply to this job only (for example from a
	// project file); the runner's Options take precedence over them.
	Variables map[string]any
	Secrets   map[string]string
	// Row, when set, runs the job with a data row.
	Row *Row
	// Validator, when set, replaces Options.Validator for this job.
	Validator ResponseValidator
}

Job is a file to run: its Source, or the file Name read when Source is nil.

func (Job) Label

func (j Job) Label() string

Label names the job like its result's Label.

type Log

type Log struct {
	Level LogLevel
	Text  string
	// Color is Text with ANSI colors, set for LogError and LogDebugError.
	Color string
}

Log is a line (or rendered error) of diagnostic output.

type LogLevel

type LogLevel int

LogLevel tells how a log line is presented.

const (
	// LogDebug is verbose detail ("* " prefix).
	LogDebug LogLevel = iota
	// LogDebugImportant is a verbose heading ("* " prefix, emphasized).
	LogDebugImportant
	// LogRequest is a request header as sent, "Name: value" ("> "
	// prefix); an empty text ends the headers.
	LogRequest
	// LogResponse is a response header as received, "Name: value" ("< "
	// prefix); an empty text ends the headers.
	LogResponse
	// LogDebugError is a rendered error of a retried attempt, shown in
	// verbose mode only.
	LogDebugError
	// LogWarning is a warning ("warning: " prefix).
	LogWarning
	// LogError is a rendered error ("error: " prefix, followed by a blank
	// line).
	LogError
	// LogRequestLine is the request line as sent ("> " prefix).
	LogRequestLine
	// LogResponseLine is the status line as received ("< " prefix).
	LogResponseLine
	// LogCapture is a captured variable, "name: value" ("* " prefix).
	LogCapture
)

Log levels.

type MessageReceived added in v1.2.0

type MessageReceived struct {
	Index   int // the entry
	Message exchange.Message
}

MessageReceived is sent when a streamed entry receives a Server-Sent Event or a WebSocket message. Like results, it holds raw values.

type MessageSent added in v1.2.0

type MessageSent struct {
	Index   int // the entry
	Message exchange.Message
}

MessageSent is sent when a streamed entry sends a WebSocket message. Like results, it holds raw values: redact before showing them.

type Options

type Options struct {
	// Variables are typed: nil, bool, int, int64, float64, string, Value,
	// []any or map[string]any of those (a map becomes an object with its
	// keys sorted).
	Variables map[string]any
	// Secrets are string variables whose values are redacted everywhere.
	Secrets map[string]string
	// FileRoot confines the files a request file reads or writes; empty
	// means the directory of the file (or the working directory).
	FileRoot string
	HTTP     HTTPOptions
	// CookieFile is read before the first request (Netscape format).
	CookieFile    string
	NoCookieStore bool

	// Retry is the number of retries of a failing entry (-1: unlimited).
	Retry         int
	RetryInterval time.Duration // zero: 1s
	// Delay is the pause before each entry (not before retries).
	Delay           time.Duration
	FromEntry       int // 1-based, 0: first
	ToEntry         int // 1-based, 0: last
	NoAssert        bool
	ContinueOnError bool
	Verbosity       Verbosity
	// BufferedLogs tells that log events are held until their unit ends
	// and then redacted with Runner.Redact, which allows `redact` captures
	// in verbose mode.
	BufferedLogs bool

	// Stdout receives responses written with `output: -`. Nil: discarded.
	Stdout io.Writer
	// DefaultUserAgent replaces `sonde/<version>` (the version of this
	// module) as the User-Agent sent when neither the entry nor the
	// options set one.
	DefaultUserAgent string
	// Validator checks every final response against a contract, after
	// the explicit asserts (skipped with NoAssert). Nil: no contract.
	// Job.Validator replaces it for one job.
	Validator ResponseValidator
	// OnEvent receives events serially, in order. Nil: discarded.
	OnEvent func(Event)

	// Now and UUID replace the clock and UUID source of the template
	// functions (tests). Nil: system clock, random UUIDs.
	Now  func() time.Time
	UUID func() string
}

Options configure a run. Command line options map to these fields; an entry's Options section overrides them for that entry.

type Pos

type Pos struct {
	Offset int
	Line   int
	Col    int
}

Pos is a position in a request file. Offset is a byte offset, counted after a leading byte order mark if the file has one; Line and Col are 1-based, Col counted in runes.

type Redirect

type Redirect struct {
	Status      int
	Location    string
	HasLocation bool
}

Redirect is one hop of a `redirects` query: the status of the response and its Location header, if any.

type ResponseValidator

type ResponseValidator interface {
	// ValidateResponse returns the violations of resp, the response to
	// req (the final one, after redirects); none when it conforms.
	ValidateResponse(ctx context.Context, req *exchange.Request, resp *exchange.Response) []Violation
}

ResponseValidator checks a response against a contract (an OpenAPI description). One validator serves every unit of a run: it must be safe for concurrent use.

func NoContract

func NoContract() ResponseValidator

NoContract returns a ResponseValidator checking nothing: as Job.Validator, it turns the run's contract off for one job.

type Row

type Row struct {
	// Index is the 1-based position of the row; results are labeled
	// "<file>#row-<Index>".
	Index     int
	Variables map[string]any
	// Secrets, and the secrets the job finds while running (`redact`
	// captures, credentials), are redacted from the job's events and by
	// UnitResult.Redact, not by Runner.Redact: rows never grow the run's
	// secrets.
	Secrets map[string]string
}

Row is a data row a job runs with. Its variables and secrets take precedence over the runner's Options.Variables; a caller wanting some options to win over rows (the CLI's --variable) leaves those names out of the row.

type RunAllOptions

type RunAllOptions struct {
	// Parallel is the number of jobs run at a time; < 1 runs one at a
	// time.
	Parallel int
	// Stop, when closed, schedules no more jobs and ends running jobs at
	// their next entry boundary (their results are Interrupted).
	// Canceling the context of RunAll also aborts requests in flight.
	Stop <-chan struct{}
	// Started is called when a job starts, seq being its 0-based position
	// in the sequence of jobs; it returns where the job sends its events
	// and its standard output (nil: nowhere).
	Started func(seq int, job Job) (onEvent func(Event), stdout io.Writer)
	// Finished receives the result of a job, in completion order, or the
	// error that prevented it from running (an unreadable file, a setup
	// failure). It returns false to schedule no more jobs.
	Finished func(seq int, job Job, res *UnitResult, err error) bool
}

RunAllOptions configure RunAll. Calls to the hooks and to the event handlers they return are never concurrent.

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner runs files with shared options. Secrets known to a runner (options and `redact` captures of every file it ran) are redacted from the log events it sends and by Redact. RunFile and RunSource run one file; RunAll runs several in parallel.

func NewRunner

func NewRunner(opt Options) *Runner

NewRunner returns a runner.

func (*Runner) Close

func (r *Runner) Close() error

Close releases the runner's resources.

func (*Runner) HasSecrets

func (r *Runner) HasSecrets() bool

HasSecrets reports whether the runner knows any secret.

func (*Runner) Redact

func (r *Runner) Redact(s string) string

Redact masks every secret known to the runner in s.

func (*Runner) RenderCurl

func (r *Runner) RenderCurl(ctx context.Context, name string, src []byte) ([]CurlEntry, error)

RenderCurl renders the entries of the file named name, with content src, to their curl command lines without sending anything: those selected by Options.FromEntry/ToEntry (1-based, as in a run; both zero select every entry). ctx may cancel the call between entries. A file that does not parse is returned as an *Error of kind ErrorParse.

Variables, secrets and every HTTP option come from the runner's options exactly as a run would use them; its run-only fields (Retry, Delay, ...) are never read. Options.FileRoot confines file bodies and multipart files exactly like a run (empty: the directory of name). Secrets found while rendering (credentials) are added to the runner's.

Every entry is isolated: an invalid FromEntry/ToEntry range is the only other error RenderCurl itself returns; a problem specific to one entry (an undefined variable in a value with its own strict syntax, a body file RenderCurl can't supply) is reported in that entry's own Err, and every other entry is still rendered. A body file that exists but is not a regular one (a FIFO, a device, a directory) is never opened at all — only Stat, which cannot block, checks it — so it reports the same error a missing file would rather than hanging forever, since a caller has no way to cancel a blocking read once it has started.

A variable no source defines is not an error by itself: it stays a literal {{name}} in the rendered command (Undefined names it), evaluated once per entry — never written back to the shared variables, so one entry's undefined name is never mistaken for defined by another. The literal placeholder works in any plain-text value (a header, the URL, a JSON or form-urlencoded body, ...); it does not work where the file syntax requires a real number or boolean (Options repeat/skip/max-redirs/limit-rate/...), which is reported through that entry's Err instead.

func (*Runner) RunAll

func (r *Runner) RunAll(ctx context.Context, jobs iter.Seq[Job], opt RunAllOptions)

RunAll runs jobs, opt.Parallel at a time. Jobs are isolated: a failing job does not affect the others. Jobs send their events and output where opt.Started says, never to Options.OnEvent or Options.Stdout. A Finished hook returning false only stops the scheduling: running jobs complete.

Example

Run several files, two at a time, and count the successes.

package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"slices"

	"github.com/nhtera/sonde/engine"
)

func main() {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path == "/missing" {
			w.WriteHeader(http.StatusNotFound)
		}
	}))
	defer srv.Close()

	jobs := []engine.Job{
		{Name: "a.hurl", Source: []byte("GET " + srv.URL + "/a\nHTTP 200\n")},
		{Name: "b.hurl", Source: []byte("GET " + srv.URL + "/missing\nHTTP 200\n")},
		{Name: "c.hurl", Source: []byte("GET " + srv.URL + "/c\nHTTP 200\n")},
	}
	r := engine.NewRunner(engine.Options{})
	defer r.Close() //nolint:errcheck // example cleanup
	failed := map[string]bool{}
	r.RunAll(context.Background(), slices.Values(jobs), engine.RunAllOptions{
		Parallel: 2,
		Finished: func(_ int, job engine.Job, res *engine.UnitResult, err error) bool {
			failed[job.Name] = err != nil || !res.Success
			return true
		},
	})
	fmt.Println(failed["a.hurl"], failed["b.hurl"], failed["c.hurl"])
}
Output:
false true false

func (*Runner) RunFile

func (r *Runner) RunFile(ctx context.Context, path string) (*UnitResult, error)

RunFile reads and runs a file; the error reports a file that cannot be read or a setup failure (e.g. an unreadable cookie file).

func (*Runner) RunSource

func (r *Runner) RunSource(ctx context.Context, name string, src []byte) (*UnitResult, error)

RunSource runs the content of a file named name (used for messages and to locate the default file root).

type Span

type Span struct {
	Start Pos
	End   Pos
}

Span is a half-open source range [Start, End).

type UnitResult

type UnitResult struct {
	File   string
	Source []byte
	// ParseError is set when the file does not parse; nothing ran. Its
	// kind is ErrorParse.
	ParseError *Error
	// Entries has one result per attempt: a retried entry appears once per
	// attempt, repeated entries once per repetition.
	Entries []*EntryResult
	// Interrupted is set when the run was stopped or canceled before its
	// last entry; an interrupted run is not a success.
	Interrupted bool
	Success     bool
	Duration    time.Duration
	// Cookies is the cookie store at the end of the run.
	Cookies []Cookie
	// Timestamp is the start of the run.
	Timestamp time.Time
	// Row is the 1-based index of the data row the file ran with (0:
	// none).
	Row int
	// contains filtered or unexported fields
}

UnitResult is the result of running one file.

func (*UnitResult) Errors

func (u *UnitResult) Errors() []*Error

Errors returns the errors that decided the outcome: those of every attempt that was not retried. It does not include ParseError.

func (*UnitResult) HasSecrets

func (u *UnitResult) HasSecrets() bool

HasSecrets reports whether Redact knows any secret.

func (*UnitResult) Label

func (u *UnitResult) Label() string

Label names the run in output and reports: the file, and its data row as "#row-N".

func (*UnitResult) Redact

func (u *UnitResult) Redact(s string) string

Redact masks in s every secret known for this result, in one pass: the runner's (as of the call: sinks written after the run get the final union) and those of its data row (Row.Secrets, and the `redact` captures and credentials of the row's run), which Runner.Redact does not know. Sinks showing a result redact with it. Row secrets exist only in a run with data rows; a UnitResult not produced by a Runner redacts nothing.

type Value

type Value struct {
	// contains filtered or unexported fields
}

Value is a typed value, such as a captured one. The zero Value has no kind. Values are also accepted as variables (Options.Variables). Values are not comparable with ==: compare their kinds and contents.

func (Value) Bool

func (v Value) Bool() (b, ok bool)

Bool returns a boolean value.

func (Value) Bytes

func (v Value) Bytes() ([]byte, bool)

Bytes returns a copy of a bytes value.

func (Value) Fields

func (v Value) Fields() []Field

Fields returns the members of an object value in their order; nil for other kinds.

func (Value) Float

func (v Value) Float() (float64, bool)

Float returns a float value (not an integer one).

func (Value) Get

func (v Value) Get(key string) (Value, bool)

Get returns the member key of an object value.

func (Value) Int

func (v Value) Int() (int64, bool)

Int returns an integer value. It is false for an integer beyond 64 bits, whose digits String returns.

func (Value) Kind

func (v Value) Kind() ValueKind

Kind returns the type of v; "" for the zero Value.

func (Value) Len

func (v Value) Len() int

Len returns the number of elements of a list, members of an object or nodes of a nodeset; 0 for other kinds.

func (Value) List

func (v Value) List() []Value

List returns the elements of a list value; nil for other kinds.

func (Value) Redirect

func (v Value) Redirect() (Redirect, bool)

Redirect returns a redirect value.

func (Value) Regex

func (v Value) Regex() (string, bool)

Regex returns the pattern of a regex value.

func (Value) String

func (v Value) String() string

String returns v as displayed in messages: a string's own text, an integer's digits, bytes in hexadecimal, a date like "2006-01-02 15:04:05.123 UTC" (fraction only when non-zero); "none" for the zero Value.

func (Value) Text

func (v Value) Text() (string, bool)

Text returns a string value.

func (Value) Time

func (v Value) Time() (time.Time, bool)

Time returns a date value, in UTC.

type ValueKind

type ValueKind string

ValueKind is the type of a Value. New kinds may be added in minor versions: switch on it with a default case.

const (
	ValueNull    ValueKind = "null"
	ValueBool    ValueKind = "boolean"
	ValueInteger ValueKind = "integer" // including integers beyond 64 bits
	ValueFloat   ValueKind = "float"
	ValueString  ValueKind = "string"
	ValueBytes   ValueKind = "bytes"
	ValueList    ValueKind = "list"
	ValueObject  ValueKind = "object"
	ValueDate    ValueKind = "date"
	// ValueNodeset is an XPath result; only its size is kept.
	ValueNodeset ValueKind = "nodeset"
	// ValueUnit is the result of a query that matched without data (e.g.
	// a cookie attribute flag).
	ValueUnit ValueKind = "unit"
	// ValueRegex is a regular expression; no capture produces one today.
	ValueRegex ValueKind = "regex"
	// ValueRedirect is one hop of a `redirects` query.
	ValueRedirect ValueKind = "redirect"
)

Value kinds.

type Verbosity

type Verbosity int

Verbosity is the level of debug information emitted as log events.

const (
	Quiet Verbosity = iota
	Brief
	Verbose
	VeryVerbose
)

Verbosity levels.

type Violation

type Violation struct {
	Kind ViolationKind
	// Operation is the matched operation, "GET /pets/{petId}"; empty when
	// no operation matched.
	Operation string
	// SpecPointer locates the broken rule in the contract, as a JSON
	// pointer fragment ("#/paths/~1pets/get/responses/200").
	SpecPointer string
	// InstancePath locates the offending part of the response: a JSON
	// pointer into the body ("/0/name"), or "header <Name>"; empty for the
	// response as a whole.
	InstancePath string
	Message      string
	// Warning marks a finding that does not fail the entry, such as a
	// request no operation matches outside of strict mode.
	Warning bool
}

Violation is a response not conforming to the contract.

type ViolationKind

type ViolationKind string

ViolationKind classifies a violation.

const (
	// ViolationUnmatched: no operation of the contract matches the
	// request (a warning outside strict mode).
	ViolationUnmatched ViolationKind = "unmatched"
	// ViolationStatus: the status is not documented.
	ViolationStatus ViolationKind = "status"
	// ViolationHeader: a documented header is missing or invalid.
	ViolationHeader ViolationKind = "header"
	// ViolationContentType: the content type is not documented.
	ViolationContentType ViolationKind = "content-type"
	// ViolationBody: the body does not match its schema.
	ViolationBody ViolationKind = "body"
	// ViolationError: the response could not be checked.
	ViolationError ViolationKind = "error"
)

Violation kinds.

Jump to

Keyboard shortcuts

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