unplugged

package module
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Jan 6, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

README

Go Reference coverage Go Version License

Unplugged - The Specification-Native Go Testing Library

The only Go-native library that turns your Postman collections and OpenAPI specs into test servers - no Node.js, no Java, no external processes.

Unlike transport mocking libraries (httpmock, gock), Unplugged lets you test against real API specifications without modifying your code. Unlike heavyweight tools (WireMock, Mockoon), it's a zero-dependency Go library that runs in-process. Perfect for contract testing, legacy code testing, and microservices integration.

Test your APIs unplugged from external dependencies - no more flaky tests due to external API downtime or rate limits.

🎯 Perfect For

  • API Testing & HTTP Mock Server creation in Go
  • Postman Collection Testing - Convert collections to test servers
  • OpenAPI Testing - Generate mock servers from OpenAPI 3.0 specs (JSON/YAML)
  • Microservices Testing - Isolated testing without external dependencies
  • Legacy Code Testing - Add API tests without refactoring existing Go code
  • Integration Testing - Test API client libraries against realistic responses
  • Contract Testing - Validate API contracts using real specification files

✨ Key Features

🔌 Multiple Collection Sources
  • Postman Collections - Import .json collections with variables and authentication
  • OpenAPI 3.0 Specs - Support for .json, .yaml, and .yml files with schema-based response generation
  • Programmatic Stubs - Create custom routes with full control over request/response matching
  • Custom Collection Providers - Implement the unplugged.Collection interface for any API format
🚀 Easy Integration & Testing
  • Zero Refactoring - Add API tests to legacy Go projects without code changes
  • Drop-in Replacement - Simply replace your http.Client with server.Client()
  • Realistic Responses - Test against actual API responses from your collections
  • Fast & Reliable - No external network calls, no flaky tests, instant test execution
  • In-Process Performance - Zero network overhead (runs in same process as tests)
🔐 Authentication & Advanced Features
  • Built-in Auth Support - API keys (header/query), Bearer tokens, Basic authentication
  • Request/Response Logging - Optional detailed logging with TestingLogger for debugging
  • Host & Header Matching - Flexible routing with custom matching rules
  • Egress Control - Block or whitelist external requests during testing (unique feature!)
  • Variable Substitution - Support for Postman-style {{variable}} templating
  • Thread-Safe - Safe for go test -race and parallel test execution

🤔 Why Choose Unplugged for Go API Testing?

Common API Testing Problems Solved

Before Unplugged:

  • Flaky tests due to external API dependencies
  • Time-consuming manual mock creation
  • Difficulty testing legacy code without refactoring
  • Complex setup for different API authentication methods
  • Inconsistent test data across team members

With Unplugged:

  • Reliable Tests - No external dependencies, consistent results
  • Faster Development - Import existing Postman collections or OpenAPI specs instantly
  • Zero Refactoring - Test legacy Go applications without code changes
  • Real Data Testing - Use actual API responses from your existing documentation
  • Team Consistency - Share collections for identical test environments
Perfect for These Scenarios

🏢 Enterprise API Testing - Test microservices integration without external service dependencies 🔧 Legacy Application Testing - Add comprehensive API tests to existing Go codebases ⚡ TDD & CI/CD - Fast, reliable tests that run in any environment 🔄 API Client Development - Test your Go HTTP clients against realistic responses 📋 Contract Testing - Validate API implementations against OpenAPI specifications


🔍 Comparison: When to Use Unplugged vs. Alternatives

✅ Use Unplugged When:
  • ✓ You have Postman collections or OpenAPI specs you want to reuse in tests
  • ✓ You're writing Go code and want a native library (no external runtimes)
  • ✓ You need contract testing between microservices
  • ✓ You want to test legacy code without refactoring
  • ✓ You need egress control to prevent accidental external API calls
  • ✓ You value zero dependencies and in-process performance
💡 Migration Paths

From httpmock/gock to Unplugged:

// Before (httpmock)
httpmock.RegisterResponder("GET", "https://api.example.com/users/1",
    httpmock.NewStringResponder(200, `{"id": 1, "name": "John"}`))

// After (Unplugged) - Reuse existing Postman collection
collection, _ := postman.New("./api.postman_collection.json")
server := unplugged.NewServer(collection)
// All routes from collection now available!

Why migrate?

  • Reuse existing API documentation (Postman/OpenAPI)
  • Better for complex APIs (100+ endpoints)
  • Contract testing against specs
  • Easier team collaboration (share collections)

🚀 Quick Start Guide

Installation
go get gitlab.com/xtechiz/unplugged@latest
30-Second Example
// 1. Import and create server from Postman collection
collection, _ := postman.New("./api.postman_collection.json")
server := unplugged.NewServer(collection)
defer server.Close()

// 2. Use in your existing Go HTTP client code
client := yourapi.NewClient(server.Client()) // <- Only change needed!

// 3. Test your API calls with realistic responses
result, err := client.GetUser("123") // Uses real Postman response data
Choose Your API Testing Approach
Collection Type Best For File Format
Postman Collections Existing API documentation .json
OpenAPI 3.0 Specs API-first development .json, .yaml, .yml
Programmatic Stubs Custom test scenarios Go code

📚 Complete Examples

🟠 Postman Collection Testing
package pokemonapi_test 

import (
    "context"
    "testing"

    "pokemonapi"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

    "gitlab.com/xtechiz/unplugged"
    "gitlab.com/xtechiz/unplugged/collections/postman"
)

func TestGetData(t *testing.T) {
    collection, err := postman.New("./testdata/pokemonapi_collection.json")
    require.NoError(t, err)

    // Start testing server
    server := unplugged.NewServer(collection)
    defer server.Close()

    // Create pokemonapi instance using server's Client
    clt := pokemonapi.NewClient(server.Client())

    // Run the actual code to check that everything is working as expected
    stat, err := clt.Stat(context.Background(), "2")
    require.NoError(t, err)

    assert.Equal(t, "attack", stat.Name)
    assert.False(t, stat.IsBattleOnly)
}
🔷 OpenAPI 3.0 Specification Testing
package api_test

import (
    "testing"

    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"

    "gitlab.com/xtechiz/unplugged"
    "gitlab.com/xtechiz/unplugged/collections/openapi"
)

func TestOpenAPIEndpoints(t *testing.T) {
    // Load OpenAPI specification (supports .json, .yaml, .yml)
    collection, err := openapi.New("./api-spec.yaml")
    require.NoError(t, err)

    // Create server with logging for debugging
    logger := unplugged.NewTestingLogger(t)
    server := unplugged.NewServer(collection, unplugged.WithLogger(logger))
    defer server.Close()

    // Test API endpoints defined in your OpenAPI spec
    // Responses are generated from examples or schemas automatically
    response, err := server.Client().Get("https://api.example.com/users")
    require.NoError(t, err)
    defer response.Body.Close()

    assert.Equal(t, 200, response.StatusCode)
    assert.Equal(t, "application/json", response.Header.Get("Content-Type"))
}
⚙️ Programmatic Stub Testing
package api_test

import (
    "net/http"
    "testing"

    "github.com/stretchr/testify/require"

    "gitlab.com/xtechiz/unplugged"
    "gitlab.com/xtechiz/unplugged/collections/stub"
)

func TestCustomStubs(t *testing.T) {
    // Create custom stub collection
    collection := stub.StubCollection{
        Stubs: []unplugged.Route{
            {
                Name: "health-check",
                Request: unplugged.Request{
                    Method: "GET",
                    Host:   "api.example.com",
                    Path:   "/health",
                },
                Response: unplugged.Response{
                    StatusCode: 200,
                    Body:       []byte(`{"status": "ok"}`),
                    Header: http.Header{
                        "Content-Type": {"application/json"},
                    },
                },
            },
        },
    }

    server := unplugged.NewServer(collection)
    defer server.Close()

    response, err := server.Client().Get("http://api.example.com/health")
    require.NoError(t, err)
    defer response.Body.Close()
}

🔧 Advanced Configuration

Logging Support

Enable detailed request/response logging for debugging:

// Use TestingLogger for test output
logger := unplugged.NewTestingLogger(t)
server := unplugged.NewServer(collection, unplugged.WithLogger(logger))

// Or implement custom Logger interface
type CustomLogger struct{}
func (l CustomLogger) LogRequest(req *http.Request) { /* custom logic */ }
func (l CustomLogger) LogResponse(req *http.Request, res *http.Response, route string) { /* custom logic */ }
func (l CustomLogger) LogRouteNotFound(req *http.Request) { /* custom logic */ }

server := unplugged.NewServer(collection, unplugged.WithLogger(CustomLogger{}))
Authentication Support

Built-in support for common authentication methods:

// API Key authentication
auth := unplugged.NewHeaderApikey("X-API-Key", "your-api-key")
// or
auth := unplugged.NewQueryApikey("api_key", "your-api-key")

// Bearer token authentication
auth := unplugged.NewBearerAuth("your-bearer-token")

// Basic authentication
auth := unplugged.NewBasicAuth("username", "password")
Server Configuration Options
server := unplugged.NewServer(collection,
    unplugged.WithLogger(logger),                    // Enable logging
    unplugged.WithHeaderMatch("X-Custom-Header"),    // Match specific headers
    unplugged.WithoutHost(),                         // Disable host matching
    unplugged.AllowEgress(),                         // Allow outbound requests
    unplugged.WithEgressWhitelist("api.example.com"), // Whitelist specific hosts
)

⚡ Performance & Architecture

Why In-Process Matters

Unplugged runs in the same process as your tests - no separate servers, no network sockets:

// Unplugged: Direct function call (nanoseconds)
response, _ := server.Client().Get("https://api.example.com/users")
// ↑ Resolved by gorilla/mux router in same process

// Prism/WireMock: HTTP over network (milliseconds)
response, _ := http.Get("http://localhost:4010/users")
// ↑ TCP handshake + HTTP parsing + IPC overhead

Benefits:

  • ⚡ Faster tests - No network latency (0ms overhead)
  • 🔒 More reliable - No port conflicts, no "address already in use" errors
  • 🚀 Easier CI/CD - No Docker containers or separate processes to manage
  • 🧪 Parallel testing - Each test gets its own server instance, no port conflicts
Test Coverage & Quality
  • 94.6% test coverage - Thoroughly tested, production-ready
  • Thread-safe - Unlike gock, safe for go test -race
  • Zero dependencies - Only Go standard library + gorilla/mux

Go Libraries

httpmock (2.2k ⭐)

  • Best for: Simple, manual mock setup (5-10 endpoints)
  • Pros: Very simple API, minimal learning curve
  • Cons: Manual mock creation, no spec support
  • Use if: You need quick mocks without existing specs

gock (2.1k ⭐)

  • Best for: Pattern-based HTTP traffic interception
  • Pros: Fluent API, powerful matching
  • Cons: Not thread-safe, no spec support
  • Use if: You need regexp-based request matching
Cross-Platform Tools

Prism (4.3k ⭐, Node.js)

  • Best for: Multi-language teams, CLI workflows
  • Pros: Full OpenAPI 2.0/3.0 validation, dynamic response generation
  • Cons: Requires Node.js runtime, separate process overhead
  • Use if: You need language-agnostic tool or dynamic data generation

Mockoon (6.4k ⭐, Desktop App)

  • Best for: Non-developers, visual API design
  • Pros: Beautiful GUI, easy to use, no coding required
  • Cons: Desktop app (not a library), Electron overhead
  • Use if: You want visual interface for mock creation

WireMock (6.3k ⭐, Java)

  • Best for: Java/Spring Boot applications
  • Pros: Mature, feature-rich, excellent Java integration
  • Cons: Requires JVM, complex setup
  • Use if: You're in Java ecosystem

Postman Mock Server (Cloud)

  • Best for: Teams already using Postman cloud
  • Pros: Integrated with Postman ecosystem, shareable URLs
  • Cons: Requires internet, cloud-based (privacy concerns)
  • Use if: You want hosted solution with team collaboration
Why Choose Unplugged?

Unique advantages:

  1. Only Go-native library with both Postman + OpenAPI support
  2. Egress control - prevents accidental external API calls (unique feature)
  3. In-process performance - zero network overhead
  4. Specification + Code hybrid - combine specs with programmatic stubs
  5. Zero dependencies - no Node.js, Java, or external runtimes

Perfect for: Go developers who want to reuse existing API specifications in tests without external dependencies.

🗺️ Roadmap & Current Limitations

✅ Recently Added (2025)
  • Thread-safe body decoder registration
  • Improved error handling in body matching
  • Path parameter support for OpenAPI (/users/{id})
  • Code formatting standardization
🚧 Planned Features (See IMPROVEMENTS.md)

High Priority:

  • OpenAPI $ref schema references support
  • Dynamic response generation ({{$randomInt}}, {{$guid}}, etc.)
  • Request validation against OpenAPI schemas
  • HTTP traffic recording mode

Medium Priority:

  • Chaos engineering features (latency, failures, timeouts)
  • Performance benchmarks vs. competitors
  • Enhanced OpenAPI request body matching
⚠️ Current Limitations

OpenAPI:

  • No support for $ref components yet (coming soon)
  • No request body validation
  • OpenAPI 2.0 (Swagger) not supported (3.0 only)

General:

  • No dynamic fake data generation (use Prism if needed)
  • No GUI/visual interface (use Mockoon if needed)
  • HTTP/REST only (no gRPC, WebSocket, GraphQL yet)

Transparency: We're honest about what we don't support yet. Check IMPROVEMENTS.md for detailed roadmap.


📖 Documentation & Support

🤝 Contributing to Unplugged

We welcome contributions! Whether you're fixing bugs, adding features, or improving documentation:

  1. 🍴 Fork the repository
  2. 🌿 Create a feature branch (git checkout -b feature/amazing-feature)
  3. 💾 Commit your changes (git commit -m 'Add amazing feature')
  4. 📤 Push to the branch (git push origin feature/amazing-feature)
  5. 🔄 Open a Merge Request

📄 License

This project is licensed under the Apache 2.0 License - see the LICENSE file for details.


Made with ❤️ for the Go community | Star ⭐ this repo if it helped you!

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

View Source
const StatusRouteNotFound = 499

Variables

View Source
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 FormDataBodyDecoder added in v0.1.0

func FormDataBodyDecoder(req *http.Request) (any, error)

func GetContentType added in v0.1.0

func GetContentType(header http.Header) string

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 JsonBodyDecoder added in v0.1.0

func JsonBodyDecoder(req *http.Request) (any, error)

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 MultipartFormDataBodyDecoder(req *http.Request) (any, error)

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

func RegisterGenerator(name string, fn func() string)

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

func RenderTemplate(content []byte) []byte

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.

func UnmarshalBody added in v0.1.0

func UnmarshalBody(req *http.Request) (any, error)

func UpdateClientTransport

func UpdateClientTransport(clt *http.Client, destination string, knownHosts []string, options ...Option)

Types

type Authentication added in v0.0.3

type Authentication interface {
	Authenticate(request *Request) error
	Matcher(*http.Request) bool
}

type BasicAuth added in v0.0.3

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

func NewBasicAuth added in v0.0.3

func NewBasicAuth(user, password string) BasicAuth

func (BasicAuth) Authenticate added in v0.0.3

func (auth BasicAuth) Authenticate(request *Request) error

func (BasicAuth) Matcher added in v0.0.3

func (auth BasicAuth) Matcher(r *http.Request) bool

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

func (BearerAuth) Matcher added in v0.0.3

func (auth BearerAuth) Matcher(r *http.Request) bool

type BodyDecoder added in v0.1.0

type BodyDecoder func(*http.Request) (any, 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

func (HeaderApikey) Matcher added in v0.0.3

func (auth HeaderApikey) Matcher(r *http.Request) bool

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) LogResponse(req *http.Request, res *http.Response, route string)

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

func WithEgressWhitelist(whitelist ...string) Option

WithEgressWhitelist returns an Option that sets the egress whitelist to the given list of hosts.

func WithHeaderMatch

func WithHeaderMatch(headers ...string) Option

WithHeaderMatch returns an Option that adds header matches.

func WithLogger added in v0.2.0

func WithLogger(logger Logger) Option

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.

func (*Options) Apply

func (opts *Options) Apply(options []Option)

Apply applies the given options to the Options struct.

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

func (QueryApikey) Matcher added in v0.0.3

func (auth QueryApikey) Matcher(r *http.Request) bool

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

func (r Request) ToHTTPRequest() *http.Request

func (Request) ToQueries

func (r Request) ToQueries() []string

ToQueries converts the request queries to a slice of strings. Returns a slice of strings with the query key and value to be used in mux conditions.

type Response

type Response struct {
	Header     http.Header
	Body       []byte
	StatusCode int
}

Response represents an HTTP response with headers, body, and status code.

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

type Server struct {
	*httptest.Server
	// contains filtered or unexported fields
}

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.

func (*Server) Report added in v0.3.2

func (s *Server) Report(t *testing.T)

Report prints the route coverage report to the testing log.

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 (l *TestingLogger) LogResponse(req *http.Request, res *http.Response, route string)

func (*TestingLogger) LogRouteNotFound added in v0.2.0

func (l *TestingLogger) LogRouteNotFound(req *http.Request)

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.

Jump to

Keyboard shortcuts

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