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 ¶
- type Assert
- type Call
- type Capture
- type ContractEvaluated
- type Cookie
- type CurlEntry
- type EntryFinished
- type EntryResult
- type EntryStarted
- type Error
- func (e *Error) Actual() string
- func (e *Error) Assert() bool
- func (e *Error) Description() string
- func (e *Error) Error() string
- func (e *Error) Expected() string
- func (e *Error) Kind() ErrorKind
- func (e *Error) Message() string
- func (e *Error) Render() string
- func (e *Error) RenderColor() string
- func (e *Error) Span() Span
- type ErrorKind
- type Event
- type Field
- type HTTPOptions
- type HTTPVersion
- type IPResolve
- type Job
- type Log
- type LogLevel
- type MessageReceived
- type MessageSent
- type Options
- type Pos
- type Redirect
- type ResponseValidator
- type Row
- type RunAllOptions
- type Runner
- func (r *Runner) Close() error
- func (r *Runner) HasSecrets() bool
- func (r *Runner) Redact(s string) string
- func (r *Runner) RenderCurl(ctx context.Context, name string, src []byte) ([]CurlEntry, error)
- func (r *Runner) RunAll(ctx context.Context, jobs iter.Seq[Job], opt RunAllOptions)
- func (r *Runner) RunFile(ctx context.Context, path string) (*UnitResult, error)
- func (r *Runner) RunSource(ctx context.Context, name string, src []byte) (*UnitResult, error)
- type Span
- type UnitResult
- type Value
- func (v Value) Bool() (b, ok bool)
- func (v Value) Bytes() ([]byte, bool)
- func (v Value) Fields() []Field
- func (v Value) Float() (float64, bool)
- func (v Value) Get(key string) (Value, bool)
- func (v Value) Int() (int64, bool)
- func (v Value) Kind() ValueKind
- func (v Value) Len() int
- func (v Value) List() []Value
- func (v Value) Redirect() (Redirect, bool)
- func (v Value) Regex() (string, bool)
- func (v Value) String() string
- func (v Value) Text() (string, bool)
- func (v Value) Time() (time.Time, bool)
- type ValueKind
- type Verbosity
- type Violation
- type ViolationKind
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
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 ContractEvaluated ¶
ContractEvaluated is sent after the response of an entry was checked against the contract. Violations hold raw values.
type Cookie ¶
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).
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 ¶
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 ¶
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 ¶
Description is the error's title, e.g. "Assert status code".
func (*Error) Error ¶
Error returns the error on one line: "<description>: <message>" (a parse error starts with "<line>:<col>: ").
func (*Error) Expected ¶
Expected is the expected value of a failed assert or type, as displayed; "" when the error has none.
func (*Error) Render ¶
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 ¶
RenderColor is Render with ANSI colors.
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" 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 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
// NoHeaders are the names of headers not sent: the entry's, the
// --header ones and the defaults (Accept, User-Agent, …).
NoHeaders []string
NoProxy string
NTLM bool
PathAsIs bool
PinnedPublicKey string
Proxy string
// ProxyHeaders ("Name: value") are sent to an HTTP proxy only: in the
// CONNECT request of an https:// URL, with the request of an http://
// one. Without an HTTP proxy (none, or SOCKS) they are not sent.
ProxyHeaders []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 // HTTP2PriorKnowledge sends HTTP/2 without an upgrade to an http:// // URL (h2c); an https:// URL negotiates HTTP/2 as HTTP2 does. HTTP2PriorKnowledge )
Protocol versions.
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.
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
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
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
// FailWithBody writes the response body of an entry that fails (after
// its last retry) to its `output`, or Stdout, before its errors are
// reported.
FailWithBody bool
// NoJSONPathCoercion keeps the result of a jsonpath query or filter
// the list of its matches: no match is an empty list rather than no
// value, and a single match stays in a list.
NoJSONPathCoercion 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
// StdoutBody, when set, renders a response body written with
// `output: -` before it goes to Stdout (for example pretty-printing
// for a terminal). Nil: the body is written as received. It may be
// called concurrently (RunAll); it must not modify resp or body, nor
// keep either after it returns. Experimental: see docs/stability.md.
StdoutBody func(resp *exchange.Response, body []byte) []byte
// 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 ¶
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 ¶
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 (*Runner) HasSecrets ¶
HasSecrets reports whether the runner knows any secret.
func (*Runner) RenderCurl ¶
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 ¶
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
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) Decisive ¶ added in v1.5.0
func (u *UnitResult) Decisive(i int) bool
Decisive reports whether the errors of Entries[i] decide the outcome, as the reference decides it: unless the next result is of the same entry (a retry, or another repeat of it), and always for the last.
func (*UnitResult) Errors ¶
func (u *UnitResult) Errors() []*Error
Errors returns the errors that decided the outcome: those of every decisive result (see Decisive). 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) Fields ¶
Fields returns the members of an object value in their order; nil for other kinds.
func (Value) Int ¶
Int returns an integer value. It is false for an integer beyond 64 bits, whose digits String returns.
func (Value) Len ¶
Len returns the number of elements of a list, members of an object or nodes of a nodeset; 0 for other kinds.
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.
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.