mbgo

package module
v1.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 21, 2023 License: MIT Imports: 14 Imported by: 0

README

mbgo

GoDoc Build Status Go Report Card

A mountebank API client for the Go programming language.

Installation

go get -u github.com/senseyeio/mbgo@latest

Testing

This package includes both unit and integration tests. Use the unit and integration targets in the Makefile to run them, respectively:

make unit
make integration

The integration tests expect Docker to be available on the host, using it to run a local mountebank container at localhost:2525, with the additional ports 8080-8081 exposed for test imposters. Currently tested against a mountebank v2.1.2 instance using the andyrbell/mountebank image on DockerHub.

Contributing

  • Fork the repository.
  • Code your changes.
  • If applicable, add tests and/or documentation.
  • Please ensure all unit and integration tests are passing, and that all code passes make lint.
  • Raise a new pull request with a short description of your changes.
  • Use the following convention for branch naming: <username>/<description-with-dashes>. For instance, smotes/add-smtp-imposters.

Documentation

Overview

Package mbgo implements a mountebank API client with support for the HTTP and TCP protocols.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Behaviors

type Behaviors struct {
	// Wait adds latency to a response by waiting a specified number of milliseconds before sending the response.
	Wait int `json:"wait,omitempty"`
}

Behaviors defines the possible response behaviors for a stub.

See more information on stub behaviours in mountebank at: http://www.mbtest.org/docs/api/behaviors.

type Client

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

Client represents a native client to the mountebank REST API.

func NewClient

func NewClient(cli *http.Client, root *url.URL) *Client

NewClient returns a new instance of *Client given its underlying *http.Client restCli and base *url.URL to the mountebank API root.

If nil, defaults the root *url.URL value to point to http://localhost:2525.

func (*Client) AddStub added in v1.1.0

func (cli *Client) AddStub(ctx context.Context, port, index int, stub Stub) (*Imposter, error)

AddStub adds a new Stub without restarting its Imposter given the imposter's port and the new stub's index, or simply to the end of the array if index < 0.

See more information about this resource at: http://www.mbtest.org/docs/api/overview#add-stub

func (*Client) Config

func (cli *Client) Config(ctx context.Context) (*Config, error)

Config retrieves the configuration information of the mountebank server pointed to by the client.

See more information on this resource at: http://www.mbtest.org/docs/api/overview#get-config.

func (*Client) Create

func (cli *Client) Create(ctx context.Context, imp Imposter) (*Imposter, error)

Create creates a single new Imposter given its creation details imp.

Note that the Imposter.RequestCount field is not used during creation.

See more information on this resource at: http://www.mbtest.org/docs/api/overview#post-imposters.

func (*Client) Delete

func (cli *Client) Delete(ctx context.Context, port int, replay bool) (*Imposter, error)

Delete removes an Imposter configured on the given port and returns the deleted Imposter data, or an empty Imposter struct if one does not exist on the port.

See more information about this resource at: http://www.mbtest.org/docs/api/overview#delete-imposter.

func (*Client) DeleteAll

func (cli *Client) DeleteAll(ctx context.Context, replay bool) ([]Imposter, error)

DeleteAll removes all registered Imposters from mountebank and closes their listening socket. This is the surest way to reset mountebank between test runs.

See more information about this resource at: http://www.mbtest.org/docs/api/overview#delete-imposters.

func (*Client) DeleteRequests

func (cli *Client) DeleteRequests(ctx context.Context, port int) (*Imposter, error)

DeleteRequests removes any recorded requests associated with the Imposter on the given port and returns the Imposter including the deleted requests, or an empty Imposter struct if one does not exist on the port.

See more information about this resource at: http://www.mbtest.org/docs/api/overview#delete-imposter-requests.

func (*Client) Imposter

func (cli *Client) Imposter(ctx context.Context, port int, replay bool) (*Imposter, error)

Imposter retrieves the Imposter data at the given port.

Note that the Imposter.RecordRequests and Imposter.AllowCORS fields are ignored when un-marshalling an Imposter value and should only be used when creating an Imposter.

See more information about this resource at: http://www.mbtest.org/docs/api/overview#get-imposter.

func (*Client) Imposters

func (cli *Client) Imposters(ctx context.Context, replay bool) ([]Imposter, error)

Imposters retrieves a list of all Imposters registered in mountebank.

See more information about this resource at: http://www.mbtest.org/docs/api/overview#get-imposters.

func (*Client) Logs

func (cli *Client) Logs(ctx context.Context, start, end int) ([]Log, error)

Logs retrieves the Log values across all registered Imposters between the provided start and end indices, with either index filter being excluded if less than zero. Set start < 0 and end < 0 to include all Log values.

See more information on this resource at: http://www.mbtest.org/docs/api/overview#get-logs.

func (*Client) Overwrite

func (cli *Client) Overwrite(ctx context.Context, imps []Imposter) ([]Imposter, error)

Overwrite is used to overwrite all registered Imposters with a new set of Imposters. This call is destructive, removing all previous Imposters even if the new set of Imposters do not conflict with previously registered protocols/ports.

See more information about this resource at: http://www.mbtest.org/docs/api/overview#put-imposters.

func (*Client) OverwriteAllStubs added in v1.1.0

func (cli *Client) OverwriteAllStubs(ctx context.Context, port int, stubs []Stub) (*Imposter, error)

OverwriteAllStubs overwrites all existing Stubs without restarting their Imposter.

See more information about this resource at: http://www.mbtest.org/docs/api/overview#change-stubs

func (*Client) OverwriteStub added in v1.1.0

func (cli *Client) OverwriteStub(ctx context.Context, port, index int, stub Stub) (*Imposter, error)

OverwriteStub overwrites an existing Stub without restarting its Imposter, where the stub index denotes the stub to be changed.

See more information about this resouce at: http://www.mbtest.org/docs/api/overview#change-stub

func (*Client) RemoveStub added in v1.1.0

func (cli *Client) RemoveStub(ctx context.Context, port, index int) (*Imposter, error)

RemoveStub removes a Stub without restarting its Imposter.

See more information about this resource at: http://www.mbtest.org/docs/api/overview#delete-stub

type Config

type Config struct {
	// Version represents the mountebank version in semantic M.m.p format.
	Version string `json:"version"`

	// Options represent runtime options of the mountebank server process.
	Options struct {
		Help           bool     `json:"help"`
		NoParse        bool     `json:"noParse"`
		NoLogFile      bool     `json:"nologfile"`
		AllowInjection bool     `json:"allowInjection"`
		LocalOnly      bool     `json:"localOnly"`
		Mock           bool     `json:"mock"`
		Debug          bool     `json:"debug"`
		Port           int      `json:"port"`
		PIDFile        string   `json:"pidfile"`
		LogFile        string   `json:"logfile"`
		LogLevel       string   `json:"loglevel"`
		IPWhitelist    []string `json:"ipWhitelist"`
	} `json:"options"`

	// Process represents information about the mountebank server NodeJS runtime.
	Process struct {
		NodeVersion  string  `json:"nodeVersion"`
		Architecture string  `json:"architecture"`
		Platform     string  `json:"platform"`
		RSS          int64   `json:"rss"`
		HeapTotal    int64   `json:"heapTotal"`
		HeapUsed     int64   `json:"heapUsed"`
		Uptime       float64 `json:"uptime"`
		CWD          string  `json:"cwd"`
	} `json:"process"`
}

Config represents information about the configuration of the mountebank server runtime, including its version, options and runtime information.

See more information about its full structure at: http://www.mbtest.org/docs/api/contracts?type=config.

type HTTPRequest

type HTTPRequest struct {
	// RequestFrom is the originating address of the incoming request.
	RequestFrom net.IP

	// Method is the HTTP request method.
	Method string

	// Path is the path of the request, without the query parameters.
	Path string

	// Query contains the URL query parameters of the request.
	Query url.Values

	// Headers contains the HTTP headers of the request.
	Headers http.Header

	// Body is the body of the request.
	Body interface{}

	// Timestamp is the timestamp of the request.
	Timestamp string
}

HTTPRequest describes an incoming HTTP request received by an Imposter of the "http" protocol.

See more information about HTTP requests in mountebank at: http://www.mbtest.org/docs/protocols/http.

func (HTTPRequest) MarshalJSON added in v1.2.0

func (r HTTPRequest) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (*HTTPRequest) UnmarshalJSON added in v1.2.0

func (r *HTTPRequest) UnmarshalJSON(b []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface.

type HTTPResponse

type HTTPResponse struct {
	// StatusCode is the HTTP status code of the response.
	StatusCode int

	// Headers are the HTTP headers in the response.
	Headers http.Header

	// Body is the body of the response. It will be JSON encoded before sending to mountebank
	Body interface{}

	// Mode is the mode of the response; either "text" or "binary".
	// Defaults to "text" if excluded.
	Mode string
}

HTTPResponse is a Response.Value used to respond to a matched HTTPRequest.

See more information about HTTP responses in mountebank at: http://www.mbtest.org/docs/protocols/http.

func (HTTPResponse) MarshalJSON added in v1.2.0

func (r HTTPResponse) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (*HTTPResponse) UnmarshalJSON added in v1.2.0

func (r *HTTPResponse) UnmarshalJSON(b []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface.

type Imposter

type Imposter struct {
	// Port is the listening port of the Imposter; required.
	Port int

	// Proto is the listening protocol of the Imposter; required.
	Proto string

	// Name is the name of the Imposter.
	Name string

	// RecordRequests adds mock verification support to the Imposter
	// by having it remember any requests made to it, which can later
	// be retrieved and examined by the testing environment.
	RecordRequests bool

	// Requests are the list of recorded requests, or nil if RecordRequests == false.
	// Note that the underlying type will be HTTPRequest or TCPRequest depending on
	// the protocol of the Imposter.
	Requests []interface{}

	// RequestCount is the number of matched requests received by the Imposter.
	// Note that this value is only used/set when receiving Imposter data
	// from the mountebank server.
	RequestCount int

	// AllowCORS will allow all CORS pre-flight requests on the Imposter.
	AllowCORS bool

	// DefaultResponse is the default response to send if no predicate matches.
	// Only used by HTTP and TCP Imposters; should be one of HTTPResponse or TCPResponse.
	DefaultResponse interface{}

	// Stubs contains zero or more valid Stubs associated with the Imposter.
	Stubs []Stub
}

Imposter is the primary mountebank resource, representing a server/service that listens for networked traffic of a specified protocol and port, with the ability to match incoming requests and respond to them based on the behaviour of any attached Stub values.

See one of the following links below for details on Imposter creation parameters, which varies by protocol:

http://www.mbtest.org/docs/protocols/http

http://www.mbtest.org/docs/protocols/tcp

func (Imposter) MarshalJSON

func (imp Imposter) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (*Imposter) UnmarshalJSON

func (imp *Imposter) UnmarshalJSON(b []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface.

type JSONPath

type JSONPath struct {
	// Selector is the JSON path of the value tested against the predicate.
	Selector string `json:"selector"`
}

JSONPath is a predicate parameter used to narrow the scope of a tested value to one found at the specified path in the response JSON.

See more information about the JSONPath parameter at: http://www.mbtest.org/docs/api/jsonpath.

type Log

type Log struct {
	Level     string    `json:"level"`
	Timestamp time.Time `json:"timestamp"`
	Message   string    `json:"message"`
}

Log represents a log entry value in mountebank.

See more information about its full structure at: http://www.mbtest.org/docs/api/contracts?type=logs.

type Predicate

type Predicate struct {
	// Operator is the conditional or logical operator of the Predicate.
	Operator string

	// Request is the request value challenged against the Operator;
	// either of type HTTPRequest or TCPRequest.
	Request interface{}

	// JSONPath is the predicate parameter for narrowing the scope of JSON
	// comparison; leave nil to disable functionality.
	JSONPath *JSONPath

	// CaseSensitive determines if the match is case sensitive or not.
	CaseSensitive bool
}

Predicate represents conditional behaviour attached to a Stub in order for it to match or not match an incoming request.

The supported operations for a Predicate are listed at: http://www.mbtest.org/docs/api/predicates.

func (Predicate) MarshalJSON added in v1.2.0

func (p Predicate) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (*Predicate) UnmarshalJSON added in v1.2.0

func (p *Predicate) UnmarshalJSON(b []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface.

type Response

type Response struct {
	// Type is the type of the Response; one of "is", "proxy" or "inject".
	Type string

	// Value is the value of the Response; either of type HTTPResponse or TCPResponse.
	Value interface{}

	// Behaviors is an optional field allowing the user to define response behavior.
	Behaviors *Behaviors
}

Response defines a networked response sent by a Stub whenever an incoming Request matches one of its Predicates. Each Response is has a Type field that defines its behaviour. Its currently supported values are:

is - Merges the specified Response fields with the defaults.
proxy - Proxies the request to the specified destination and returns the response.
inject - Creates the Response object based on the injected Javascript.

See more information on stub responses in mountebank at: http://www.mbtest.org/docs/api/stubs.

func (Response) MarshalJSON added in v1.2.0

func (r Response) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (*Response) UnmarshalJSON added in v1.2.0

func (r *Response) UnmarshalJSON(b []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface.

type Stub

type Stub struct {
	// Predicates are the list of Predicates associated with the Stub,
	// which are logically AND'd together if more than one exists.
	Predicates []Predicate

	// Responses are the circular queue of Responses used to respond to
	// incoming matched requests.
	Responses []Response
}

Stub adds behaviour to Imposters where one or more registered Responses will be returned if an incoming request matches all of the registered Predicates. Any Stub value without Predicates always matches and returns its next Response. Note that the Responses slice acts as a circular-queue type structure, where every time the Stub matches an incoming request, the first Response is moved to the end of the slice. This allows for test cases to define and handle a sequence of Responses.

See more information about stubs in mountebank at: http://www.mbtest.org/docs/api/stubs.

func (Stub) MarshalJSON added in v1.1.0

func (s Stub) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (*Stub) UnmarshalJSON added in v1.2.0

func (s *Stub) UnmarshalJSON(b []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface.

type TCPRequest

type TCPRequest struct {
	// RequestFrom is the originating address of the incoming request.
	RequestFrom net.IP

	// Data is the data in the request as plaintext.
	Data string
}

TCPRequest describes incoming TCP data received by an Imposter of the "tcp" protocol.

See more information about TCP requests in mountebank at: http://www.mbtest.org/docs/protocols/tcp.

func (TCPRequest) MarshalJSON added in v1.2.0

func (r TCPRequest) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (*TCPRequest) UnmarshalJSON added in v1.2.0

func (r *TCPRequest) UnmarshalJSON(b []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface.

type TCPResponse

type TCPResponse struct {
	// Data is the data in the data contained in the response.
	// An empty string does not respond with data, but does send
	// the FIN bit.
	Data string
}

TCPResponse is a Response.Value to a matched incoming TCPRequest.

See more information about TCP responses in mountebank at: http://www.mbtest.org/docs/protocols/tcp.

func (TCPResponse) MarshalJSON added in v1.2.0

func (r TCPResponse) MarshalJSON() ([]byte, error)

MarshalJSON satisfies the json.Marshaler interface.

func (*TCPResponse) UnmarshalJSON added in v1.2.0

func (r *TCPResponse) UnmarshalJSON(b []byte) error

UnmarshalJSON satisfies the json.Unmarshaler interface.

Directories

Path Synopsis
internal
assert
Package assert is used internally by tests to make basic assertions.
Package assert is used internally by tests to make basic assertions.
rest
Package rest is used internally by the client to interact with the mountebank API.
Package rest is used internally by the client to interact with the mountebank API.

Jump to

Keyboard shortcuts

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