expect

package
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Feb 27, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultHTTPTimeout = 30 * time.Second

DefaultHTTPTimeout is applied to every HTTP request unless overridden on the connection.

Variables

This section is empty.

Functions

This section is empty.

Types

type AfterFunc

type AfterFunc func() error

AfterFunc is a cleanup function run after all steps complete.

type AnyOf

type AnyOf []int

AnyOf asserts the actual HTTP status code is one of the given codes.

func (AnyOf) MatchStatus

func (m AnyOf) MatchStatus(actual int) error

type BeforeFunc

type BeforeFunc func() error

BeforeFunc is a setup function run before steps execute.

type Connection

type Connection interface {
	GetName() string
	Type() string
}

Connection is a named connection to a service under test.

type Contains

type Contains string

Contains asserts the actual string contains the given substring.

func (Contains) Match

func (m Contains) Match(actual any) error

type ExpectBody

type ExpectBody []byte

ExpectBody holds the expected response body and validates it against actual bytes.

func (ExpectBody) Validate

func (e ExpectBody) Validate(actual []byte) error

Validate checks that actual matches the expected body (partial JSON match or exact bytes).

type GRPCConnection

type GRPCConnection struct {
	Name string
	Addr string
	// contains filtered or unexported fields
}

GRPCConnection is a connection to a gRPC service.

func GRPC

func GRPC(name, addr string, opts ...grpc.DialOption) *GRPCConnection

GRPC creates a GRPCConnection. opts are appended after the default insecure credential. Use grpc.WithTransportCredentials(...) in opts to enable TLS.

func (*GRPCConnection) ClientConn

func (c *GRPCConnection) ClientConn() (*grpc.ClientConn, error)

ClientConn returns the raw *grpc.ClientConn, dialling if necessary.

func (*GRPCConnection) Close

func (c *GRPCConnection) Close() error

Close tears down the gRPC connection.

func (*GRPCConnection) Dial

func (c *GRPCConnection) Dial() error

Dial opens the underlying gRPC client connection (lazy — called on first use).

func (*GRPCConnection) GetName

func (c *GRPCConnection) GetName() string

func (*GRPCConnection) Type

func (c *GRPCConnection) Type() string

type GRPCExpect

type GRPCExpect struct {
	// Code is the expected gRPC status code name (e.g. "OK", "NOT_FOUND").
	// If empty, any code is accepted.
	Code string
	// Body is the expected response body for partial JSON matching.
	Body ExpectBody
	// Save extracts fields from the JSON response into variables.
	Save []SaveEntry
}

GRPCExpect validates a gRPC response.

func (*GRPCExpect) Validate

func (e *GRPCExpect) Validate(respBytes []byte, grpcErr error, vars VarStore) error

Validate checks the gRPC response bytes against expectations.

type GRPCRequest

type GRPCRequest struct {
	// FullMethod is the full gRPC method path, e.g. "/mypackage.MyService/MyMethod".
	FullMethod string
	// Body is the JSON-encoded request body.
	Body []byte
	// Header is outgoing metadata to attach to the call.
	Header map[string]string
}

GRPCRequest invokes a unary gRPC method using server reflection to resolve proto descriptors. Body is the JSON-encoded request; an empty body sends {}.

func (*GRPCRequest) Run

func (r *GRPCRequest) Run(conn *GRPCConnection, vars VarStore) ([]byte, error)

Run invokes the gRPC method and returns the raw JSON response bytes.

type Gt

type Gt float64

Gt asserts actual > n.

func (Gt) Match

func (m Gt) Match(actual any) error

type Gte

type Gte float64

Gte asserts actual >= n.

func (Gte) Match

func (m Gte) Match(actual any) error

type HTTPConnection

type HTTPConnection struct {
	Name    string
	URL     string
	Timeout time.Duration // per-request timeout; 0 means use DefaultHTTPTimeout
	Client  *http.Client  // nil means use http.DefaultClient
}

HTTPConnection is a connection to an HTTP/HTTPS service.

func HTTP

func HTTP(name, url string) *HTTPConnection

HTTP is a convenience constructor for an HTTPConnection.

func (*HTTPConnection) GetName

func (c *HTTPConnection) GetName() string

func (*HTTPConnection) Type

func (c *HTTPConnection) Type() string

type HTTPExpect

type HTTPExpect struct {
	Status    int
	StatusAny AnyOf // if set, status must be one of these codes
	Body      ExpectBody
	Header    map[string]string
	Save      []SaveEntry
}

HTTPExpect defines the expected HTTP response and optional variable extractions.

func (*HTTPExpect) Validate

func (e *HTTPExpect) Validate(resp *http.Response, vars VarStore) error

Validate checks the response against expectations, saving extracted values into vars.

type HTTPRequest

type HTTPRequest struct {
	Method  string
	Path    string
	Body    []byte
	Header  map[string]string
	Query   map[string]string
	Timeout time.Duration // 0 means use DefaultHTTPTimeout
}

HTTPRequest describes an outbound HTTP request.

func (*HTTPRequest) Run

func (r *HTTPRequest) Run(conn *HTTPConnection, vars VarStore) (*http.Response, error)

Run executes the HTTP request against conn, interpolating variables from vars.

type Length

type Length int

Length asserts the actual array or string has exactly n elements.

func (Length) Match

func (m Length) Match(actual any) error

type Lt

type Lt float64

Lt asserts actual < n.

func (Lt) Match

func (m Lt) Match(actual any) error

type Lte

type Lte float64

Lte asserts actual <= n.

func (Lte) Match

func (m Lte) Match(actual any) error

type Matcher

type Matcher interface {
	Match(actual any) error
}

Matcher is implemented by any value that can assert itself against an actual value. When the JSON body is parsed, field values that implement Matcher are invoked instead of doing a DeepEqual comparison.

type Matches

type Matches string

Matches asserts the actual string matches the given regular expression.

func (Matches) Match

func (m Matches) Match(actual any) error

type NotEmpty

type NotEmpty struct{}

NotEmpty asserts the actual value is non-nil and non-zero.

func (NotEmpty) Match

func (NotEmpty) Match(actual any) error

type SaveEntry

type SaveEntry struct {
	Field string
	As    string
}

SaveEntry defines a field to extract from the response body into a variable. Field uses json path notation (e.g. "id", "user.name", "items.0.id").

type Scenario

type Scenario struct {
	Name string
	// contains filtered or unexported fields
}

Scenario is a named sequence of steps executed against one or more connections.

func NewScenario

func NewScenario(name string) *Scenario

NewScenario creates a new Scenario with the given name.

func (*Scenario) AddStep

func (s *Scenario) AddStep(b *StepBuilder) *Scenario

AddStep appends a step to the scenario.

func (*Scenario) After

func (s *Scenario) After(fn AfterFunc) *Scenario

After registers a cleanup function to always run after the scenario.

func (*Scenario) Before

func (s *Scenario) Before(fn BeforeFunc) *Scenario

Before registers a function to run before the scenario's steps.

func (*Scenario) Run

func (s *Scenario) Run(log *slog.Logger, defaultConn Connection, connections map[string]Connection, vars VarStore) error

Run executes steps sequentially, stopping on the first failure. after-funcs always execute regardless of before or step failures.

type Step

type Step struct {
	Connection string
	Request    any
	Expect     any
}

Step is a single request/response pair within a scenario.

func (*Step) Run

func (s *Step) Run(conn Connection, vars VarStore) error

Run executes the step against the given connection, applying variable interpolation.

type StepBuilder

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

StepBuilder constructs a Step fluently.

func DELETE

func DELETE(path string) *StepBuilder

DELETE creates a step for a DELETE request.

func GET

func GET(path string) *StepBuilder

GET creates a step for a GET request.

func GRPCCall

func GRPCCall(connection, fullMethod string, req proto.Message) *StepBuilder

GRPCCall creates a step that invokes a gRPC method using a proto message as the request. The message is marshaled to JSON via protojson before sending. fullMethod is the full gRPC method path, e.g. "/mypackage.MyService/MyMethod".

func GRPCRawCall

func GRPCRawCall(connection, fullMethod string, body []byte) *StepBuilder

GRPCRawCall creates a step that invokes a gRPC method using raw JSON bytes as the request body.

func HTTPStep

func HTTPStep(method, path string) *StepBuilder

HTTPStep creates a StepBuilder for an HTTP request with any method.

func PATCH

func PATCH(path string) *StepBuilder

PATCH creates a step for a PATCH request.

func POST

func POST(path string) *StepBuilder

POST creates a step for a POST request.

func PUT

func PUT(path string) *StepBuilder

PUT creates a step for a PUT request.

func (*StepBuilder) Build

func (b *StepBuilder) Build() Step

Build returns the completed Step.

func (*StepBuilder) ExpectBody

func (b *StepBuilder) ExpectBody(v any) *StepBuilder

ExpectBody sets the expected response body. v may be:

  • []byte — exact bytes
  • string — exact string
  • any other value — marshalled to JSON for partial matching

func (*StepBuilder) ExpectGRPCBody

func (b *StepBuilder) ExpectGRPCBody(v any) *StepBuilder

ExpectGRPCBody sets the expected gRPC response body for partial JSON matching.

func (*StepBuilder) ExpectGRPCCode

func (b *StepBuilder) ExpectGRPCCode(code string) *StepBuilder

ExpectGRPCCode sets the expected gRPC status code name (e.g. "OK", "NOT_FOUND").

func (*StepBuilder) ExpectHeader

func (b *StepBuilder) ExpectHeader(key, value string) *StepBuilder

ExpectHeader adds an expected response header assertion.

func (*StepBuilder) ExpectStatus

func (b *StepBuilder) ExpectStatus(code int) *StepBuilder

ExpectStatus sets the expected HTTP status code.

func (*StepBuilder) Save

func (b *StepBuilder) Save(field, as string) *StepBuilder

Save extracts a field from the JSON response body into a variable for later steps.

func (*StepBuilder) SaveGRPC

func (b *StepBuilder) SaveGRPC(field, as string) *StepBuilder

SaveGRPC extracts a field from the JSON gRPC response into a variable for later steps.

func (*StepBuilder) WithBody

func (b *StepBuilder) WithBody(body []byte) *StepBuilder

WithBody sets the raw request body.

func (*StepBuilder) WithConnection

func (b *StepBuilder) WithConnection(name string) *StepBuilder

WithConnection sets which named connection this step uses.

func (*StepBuilder) WithHeader

func (b *StepBuilder) WithHeader(key, value string) *StepBuilder

WithHeader adds a request header (works for both HTTP and gRPC steps).

func (*StepBuilder) WithJSON

func (b *StepBuilder) WithJSON(v any) *StepBuilder

WithJSON marshals v to JSON and sets it as the request body, also setting Content-Type: application/json.

func (*StepBuilder) WithQuery

func (b *StepBuilder) WithQuery(key, value string) *StepBuilder

WithQuery adds a query parameter.

type Suite

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

Suite holds a collection of scenarios to run.

func LoadDir

func LoadDir(dir string) (*Suite, error)

LoadDir loads all *.yaml, *.yml, and *.json files in dir from the OS filesystem.

func LoadFS

func LoadFS(fsys fs.FS) (*Suite, error)

LoadFS loads all *.yaml, *.yml, and *.json files from fsys and returns a Suite ready to run. Useful with //go:embed directories. Use fs.Sub to scope to a subdirectory if needed.

func LoadFile

func LoadFile(fpath string) (*Suite, error)

LoadFile parses a YAML or JSON file from the OS filesystem, detected by extension.

func LoadJSON

func LoadJSON(data []byte) (*Suite, error)

LoadJSON parses JSON bytes and returns a Suite ready to run.

func LoadYAML

func LoadYAML(data []byte) (*Suite, error)

LoadYAML parses YAML bytes and returns a Suite ready to run.

func NewSuite

func NewSuite() *Suite

NewSuite creates an empty Suite.

func (*Suite) Run

func (s *Suite) Run() error

Run executes all scenarios. Each scenario gets its own fresh VarStore.

func (*Suite) WithConnections

func (s *Suite) WithConnections(conns ...Connection) *Suite

WithConnections registers one or more named connections. The first connection registered becomes the default for steps with no explicit connection.

func (*Suite) WithLogger

func (s *Suite) WithLogger(log *slog.Logger) *Suite

WithLogger overrides the logger used when running scenarios.

func (*Suite) WithScenarios

func (s *Suite) WithScenarios(scenarios ...*Scenario) *Suite

WithScenarios appends scenarios to the suite.

type TestSuite

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

TestSuite wraps Suite for use with Go's testing package.

func NewTestSuite

func NewTestSuite(suite *Suite) *TestSuite

NewTestSuite creates a TestSuite backed by the given Suite.

func (*TestSuite) Run

func (s *TestSuite) Run(t *testing.T)

Run executes all scenarios, routing log output through t and reporting failures via t.Errorf so all scenarios always run (non-fatal).

type VarStore

type VarStore map[string]any

VarStore holds variables that can be set by one step and consumed by later steps.

func (VarStore) Interpolate

func (v VarStore) Interpolate(s string) string

Interpolate replaces all {key} placeholders in s with values from the store. Unknown keys are left as-is.

func (VarStore) InterpolateBytes

func (v VarStore) InterpolateBytes(b []byte) []byte

InterpolateBytes replaces {key} placeholders in a byte slice.

Jump to

Keyboard shortcuts

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