Documentation
¶
Overview ¶
Package unplugged provides API testing utilities by creating HTTP test servers from various collection formats including Postman collections, OpenAPI specifications, and programmatic stubs.
Unplugged simplifies testing by allowing you to test against realistic API responses without external dependencies or complex mocking setups. It's particularly useful for:
- Adding tests to legacy projects without refactoring
- Contract testing between microservices
- Development environments with realistic API responses
- CI/CD pipelines without flaky external dependencies
Basic usage:
// From Postman collection
collection, _ := postman.New("./api.postman_collection.json")
server := unplugged.NewServer(collection)
defer server.Close()
// From OpenAPI specification
collection, _ := openapi.New("./api-spec.yaml")
server := unplugged.NewServer(collection)
// Your HTTP client can now use server.Client()
response, _ := server.Client().Get("https://api.example.com/users")
The library uses a Collection interface that can be implemented for custom data sources, and supports comprehensive configuration through functional options.
Index ¶
- Constants
- Variables
- func BodyMatching(req Request) mux.MatcherFunc
- func FormDataBodyDecoder(req *http.Request) (any, error)
- func GetContentType(header http.Header) string
- func HeaderMatching(req Request, headers []string) mux.MatcherFunc
- func JsonBodyDecoder(req *http.Request) (any, error)
- func MatcherWrapper(matcher func(r *http.Request) bool) mux.MatcherFunc
- func MultipartFormDataBodyDecoder(req *http.Request) (any, error)
- func NewRouter(collection Collection, options ...Option) (http.Handler, []string)
- func RegisterBodyDecoder(contentType string, fn BodyDecoder)
- func RegisterGenerator(name string, fn func() string)
- func RenderTemplate(content []byte) []byte
- func StaticHandler(response Response, routeName string, logger Logger, serverChaos ChaosConfig, ...) func(http.ResponseWriter, *http.Request)
- func UnmarshalBody(req *http.Request) (any, error)
- func UpdateClientTransport(clt *http.Client, destination string, knownHosts []string, options ...Option)
- type Authentication
- type BasicAuth
- type BearerAuth
- type BodyDecoder
- type ChaosConfig
- type Collection
- type ErrorConfig
- type HeaderApikey
- type LatencyConfig
- type Logger
- type NoopLogger
- type Option
- type Options
- type QueryApikey
- type Request
- type Response
- type Route
- type RouteTracker
- type Server
- type TestingLogger
Constants ¶
const StatusRouteNotFound = 499
Variables ¶
var ErrUnsupportedContentType = errors.New("unsupported content type for body matching")
Functions ¶
func BodyMatching ¶ added in v0.1.0
func BodyMatching(req Request) mux.MatcherFunc
func GetContentType ¶ added in v0.1.0
func HeaderMatching ¶
func HeaderMatching(req Request, headers []string) mux.MatcherFunc
HeaderMatching returns a mux.MatcherFunc that matches headers based on the given request and headers. req: the ingress request to be matched // headers: the list of headers to match
func MatcherWrapper ¶ added in v0.0.3
func MatcherWrapper(matcher func(r *http.Request) bool) mux.MatcherFunc
MatcherWrapper return a mux.MatcherFunc from a SDK agnostic matcher
func MultipartFormDataBodyDecoder ¶ added in v0.1.0
func NewRouter ¶
func NewRouter(collection Collection, options ...Option) (http.Handler, []string)
NewRouter creates a new HTTP router with the given collection and options. collection: the collection of routes to be added to the router. options: additional options to configure the router.
func RegisterBodyDecoder ¶ added in v0.1.0
func RegisterBodyDecoder(contentType string, fn BodyDecoder)
RegisterBodyDecoder allows you to add support to custom content-typeif if the one you are looking for is not supported natively
func RegisterGenerator ¶ added in v0.3.1
RegisterGenerator allows adding custom dynamic variable generators. The name must start with '$' (e.g., "$customVar").
Example:
unplugged.RegisterGenerator("$myToken", func() string {
return "token-" + uuid.New().String()
})
func RenderTemplate ¶ added in v0.3.1
RenderTemplate processes the content and replaces dynamic variables like {{$guid}} with their generated values.
Supported built-in variables:
- {{$guid}} or {{$randomUUID}}: Generates a random UUID v4.
- {{$timestamp}}: Generates current Unix timestamp.
- {{$isoTimestamp}}: Generates current time in ISO 8601 format.
- {{$randomInt}}: Generates a random integer between 0 and 1000.
- {{$randomBoolean}}: Generates "true" or "false".
- {{$randomEmail}}: Generates a random email address.
- {{$randomIPv4}}: Generates a random IPv4 address.
Variables that are not found in the registry are left unchanged.
func StaticHandler ¶
func StaticHandler(response Response, routeName string, logger Logger, serverChaos ChaosConfig, routeChaos ChaosConfig, tracker *RouteTracker) func(http.ResponseWriter, *http.Request)
StaticHandler returns an HTTP handler that serves a static response. response: the response to be served by the handler. routeName: the name of the route for logging purposes. logger: the logger to use for logging requests and responses. serverChaos: the chaos engineering configuration from the server. routeChaos: the chaos engineering configuration from the route. tracker: the route tracker to record hits.
Types ¶
type Authentication ¶ added in v0.0.3
type BasicAuth ¶ added in v0.0.3
type BasicAuth struct {
// contains filtered or unexported fields
}
func NewBasicAuth ¶ added in v0.0.3
func (BasicAuth) Authenticate ¶ added in v0.0.3
type BearerAuth ¶ added in v0.0.3
type BearerAuth struct {
// contains filtered or unexported fields
}
func NewBearerAuth ¶ added in v0.0.3
func NewBearerAuth(token string) BearerAuth
func (BearerAuth) Authenticate ¶ added in v0.0.3
func (auth BearerAuth) Authenticate(request *Request) error
type ChaosConfig ¶ added in v0.3.1
type ChaosConfig struct {
Latency LatencyConfig
Errors ErrorConfig
}
ChaosConfig defines the configuration for chaos engineering features. It allows simulating unreliable network conditions and API failures.
Example usage:
config := unplugged.ChaosConfig{
Latency: unplugged.LatencyConfig{
Fixed: 100 * time.Millisecond,
Random: 50 * time.Millisecond,
},
Errors: unplugged.ErrorConfig{
Rate: 0.1, // 10% failure rate
StatusCode: 503,
},
}
type Collection ¶
type Collection interface {
Routes() []Route
}
Collection is an interface that provides routes.
func MultiCollections ¶
func MultiCollections(collections ...Collection) Collection
MultiCollections returns a collection that combines multiple collections. collections: the collections to be combined.
type ErrorConfig ¶ added in v0.3.1
type ErrorConfig struct {
// Rate is the probability of an error occurring (0.0 to 1.0).
// For example, 0.1 means 10% of requests will fail.
Rate float64
// StatusCode is the HTTP status code to return when an error occurs.
// If 0, it defaults to 500 (Internal Server Error).
StatusCode int
}
ErrorConfig defines error injection settings for chaos engineering simulation. Use this to simulate API failures (e.g., 500 Internal Server Error).
type HeaderApikey ¶ added in v0.0.3
type HeaderApikey struct {
// contains filtered or unexported fields
}
func NewHeaderApikey ¶ added in v0.0.3
func NewHeaderApikey(key, value string) HeaderApikey
func (HeaderApikey) Authenticate ¶ added in v0.0.3
func (auth HeaderApikey) Authenticate(request *Request) error
type LatencyConfig ¶ added in v0.3.1
type LatencyConfig struct {
// Fixed is the constant delay added to every request.
Fixed time.Duration
// Random is the maximum random jitter added to the delay.
// The actual random delay will be between 0 and Random.
Random time.Duration
}
LatencyConfig defines latency settings for chaos engineering simulation. Use this to simulate network delays or slow APIs.
type Logger ¶ added in v0.2.0
type Logger interface {
LogRequest(req *http.Request)
LogResponse(req *http.Request, res *http.Response, route string)
LogRouteNotFound(req *http.Request)
}
Logger is an interface for logging HTTP requests and responses.
type NoopLogger ¶ added in v0.2.0
type NoopLogger struct{}
NoopLogger is a logger that does nothing.
func (NoopLogger) LogRequest ¶ added in v0.2.0
func (NoopLogger) LogRequest(req *http.Request)
func (NoopLogger) LogResponse ¶ added in v0.2.0
func (NoopLogger) LogRouteNotFound ¶ added in v0.2.0
func (NoopLogger) LogRouteNotFound(req *http.Request)
type Option ¶
type Option func(*Options)
Option is a function that configures Options.
func AllowEgress ¶
func AllowEgress() Option
WithEgress returns an Option that allows egress traffic. It is disabled by default
func WithChaos ¶ added in v0.3.1
func WithChaos(config ChaosConfig) Option
WithChaos returns an Option that enables chaos engineering features for the server. This sets the global chaos configuration applied to all routes unless overridden by per-route chaos settings.
Example:
server := unplugged.NewServer(collection, unplugged.WithChaos(unplugged.ChaosConfig{
Latency: unplugged.LatencyConfig{Fixed: 200 * time.Millisecond},
}))
func WithEgressWhitelist ¶
WithEgressWhitelist returns an Option that sets the egress whitelist to the given list of hosts.
func WithHeaderMatch ¶
WithHeaderMatch returns an Option that adds header matches.
func WithLogger ¶ added in v0.2.0
WithLogger returns an Option that sets the logger for the server.
func WithoutHost ¶
func WithoutHost() Option
WithoutHost returns an Option that disables host matching.
type Options ¶
type Options struct {
// contains filtered or unexported fields
}
Options represents options for configuring the router.
type QueryApikey ¶ added in v0.0.3
type QueryApikey struct {
// contains filtered or unexported fields
}
func NewQueryApikey ¶ added in v0.0.3
func NewQueryApikey(key, value string) QueryApikey
func (QueryApikey) Authenticate ¶ added in v0.0.3
func (auth QueryApikey) Authenticate(request *Request) error
type Request ¶
type Request struct {
Method string
Scheme string
Host string
Path string
Queries url.Values
Header http.Header
Auth Authentication
Body []byte
}
Request represents an HTTP request with method, scheme, host, path, queries, and headers.
func (Request) ToHTTPRequest ¶ added in v0.1.0
type Route ¶
type Route struct {
Name string
Request Request
Response Response
// Chaos defines per-route chaos engineering settings.
// These settings are additive to any server-level chaos configuration.
Chaos ChaosConfig
}
Route represents a route with a name, request, and response.
type RouteTracker ¶ added in v0.3.2
type RouteTracker struct {
// contains filtered or unexported fields
}
RouteTracker tracks which routes have been triggered during execution.
func NewRouteTracker ¶ added in v0.3.2
func NewRouteTracker() *RouteTracker
NewRouteTracker creates a new RouteTracker.
func (*RouteTracker) RegisterRoute ¶ added in v0.3.2
func (rt *RouteTracker) RegisterRoute(route Route)
RegisterRoute registers a route definition.
func (*RouteTracker) Report ¶ added in v0.3.2
func (rt *RouteTracker) Report(t *testing.T)
Report prints a coverage report to the testing log.
func (*RouteTracker) Track ¶ added in v0.3.2
func (rt *RouteTracker) Track(routeName string)
Track records a hit for a specific route.
type Server ¶ added in v0.3.2
Server is a wrapper around httptest.Server that adds tracking capabilities.
func NewServer ¶
func NewServer(collection Collection, options ...Option) *Server
NewServer creates a new HTTP test server with the given collection and options. collection: the collection of routes to be added to the server. options: additional options to configure the server.
func NewTLSServer ¶
func NewTLSServer(collection Collection, options ...Option) *Server
NewTLSServer creates a new HTTPS test server with the given collection and options. by default the client will use the server's certificate so you won't have any SSL errors. collection: the collection of routes to be added to the server. options: additional options to configure the server.
type TestingLogger ¶ added in v0.2.0
type TestingLogger struct {
// contains filtered or unexported fields
}
TestingLogger is a logger that logs to *testing.T for debugging tests.
func NewTestingLogger ¶ added in v0.2.0
func NewTestingLogger(t *testing.T) *TestingLogger
NewTestingLogger creates a new TestingLogger with the given *testing.T.
func (*TestingLogger) LogRequest ¶ added in v0.2.0
func (l *TestingLogger) LogRequest(req *http.Request)
func (*TestingLogger) LogResponse ¶ added in v0.2.0
func (*TestingLogger) LogRouteNotFound ¶ added in v0.2.0
func (l *TestingLogger) LogRouteNotFound(req *http.Request)
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
collections
|
|
|
openapi
Package openapi provides support for loading OpenAPI 3.0 specifications and automatically generating test routes with realistic example responses.
|
Package openapi provides support for loading OpenAPI 3.0 specifications and automatically generating test routes with realistic example responses. |
|
postman
Package postman provides support for loading Postman collection files and converting them into unplugged routes for testing.
|
Package postman provides support for loading Postman collection files and converting them into unplugged routes for testing. |
|
stub
Package stub provides programmatic route creation for custom test scenarios where you need full control over request/response definitions.
|
Package stub provides programmatic route creation for custom test scenarios where you need full control over request/response definitions. |
|
Package transport provides HTTP transport middleware for routing and controlling network traffic in unplugged test servers.
|
Package transport provides HTTP transport middleware for routing and controlling network traffic in unplugged test servers. |