mockhttp

package module
v0.2.4 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2024 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

The go-mockhttp package extend standard net/http client library to provide a familiar HTTP client interface but with mock capabilities for testing. It is a thin wrapper over the standard net/http client library and exposes nearly the same public API. This makes mockhttp very easy to drop into existing programs.

The mock responses that will be returned by mockhttp client library is defined based on mock definitions. Currently only support loading the mock definitions from files.

Basics

How does go-mockhttp wraps the net/http client library ?

As Go http client library use a *http.Client with definition that can be referred here: https://pkg.go.dev/net/http#Client.

Based of the documentation, the Client had 6 main method:

  • (c) CloseIdleConnections()

  • (c) Do(req)

  • (c) Get(url)

  • (c) Head(url)

  • (c) Post(url, contentType, body)

  • (c) PostForm(url, data)

Using this as the base reference, we could easily extend the standard Go http.Client struct into any custom struct that we want. To actually stub the 3rd party dependencies (via HTTP call), we could modify these method:

  • (c) Do(req)

  • (c) Get(url)

  • (c) Head(url)

  • (c) Post(url, contentType, body)

  • (c) PostForm(url, data)

that relates heavily on exchanging actual data to upstream service. Specifically, we apply this approach:

=> Check if req match with loaded (in runtime) Mock Definition
  => Yes? Use response defined in Mock Definition
  => No?  Continue the requests to upstream service

Mock Definitions

A term to describe a specification to determine how to match a request to the mock responses that defined using a file (as a `yaml` file) that includes:

  • Host, endpoint path and HTTP Method of upstream service that we want to mock.

  • Supported http requests format is JSON, XML, Form for POST, PUT, PATCH requests.

  • Description field that is used to describe what's the mock definition is.

  • Multiple (array) responses that can be used as the mock responses that match the `host`, `endpoint path` and `HTTP method` defined in the spec.

Example:

host: marketplace.com
path: /check-price
method: POST
desc: Testing Marketplace Price Endpoint
responses:
  - response_headers:
    Content-Type: application/json
    response_body: "{\"user_name\": \"Mocker\",\r\n \"price\": 1000}"
    status_code: 200
  - response_headers:
    Content-Type: application/json
    response_body: "{\"user_name\": \"William\",\r\n \"price\": 2000}"
    delay: 1000
    status_code: 488
    enable_template: false
    rules:
  - body.name == "William"

There are 3 ways on how the library will try to match the endpoint path:

  1. Exact Match: /v1/api/mock/1

  2. With Path Param: /v1/api/mock/:id

  3. Wildcard: /v1/api/*

What happen when the request have no matching Mock Definition?

There are 2 conditions that might happen:

  1. Request don't match host, path, and method => http client will immediately call actual upstream service

  2. Request match host, path, and method, but didn't satisfy the rules in responses => will try to use default response (response with no rules). If no default response defined, will simply call actual upstream service.

Example Usage

Here are the example on how to use the library:

resolver, err := mockhttp.NewFileResolverAdapter(definitionDirPath)
if err != nil {
  panic(err)
}

err = resolver.LoadDefinition(context.Background())
if err != nil {
  panic(err)
}

mockClient := mockhttp.NewClient(resolver)
resp, err := .Get("/foo")
if err != nil {
  panic(err)
}

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrDefinitionLoaded       = fmt.Errorf("mock definition had been loaded")
	ErrClientMissing          = fmt.Errorf("client missing")
	ErrNoMockResponse         = fmt.Errorf("no mock response prepared")
	ErrUnsupportedContentType = fmt.Errorf("unsupported content type")
	ErrCommon                 = fmt.Errorf("common error")
	ErrNoContentType          = fmt.Errorf("unable to find content type")
)

Functions

func ReusableReader

func ReusableReader(r io.Reader) io.Reader

ReusableReader creates and returns a new reusableReader based on the provided io.Reader. The reusableReader allows for multiple reads of the same data efficiently.

Types

type Client

type Client struct {
	HTTPClient *http.Client // Internal HTTP client.
	Logger     interface{}  // Customer logger instance. Can be either Logger or LeveledLogger

	// RequestLogHook allows a user-supplied function to be called
	// before each httprequest  call.
	RequestLogHook RequestLogHook

	// ResponseLogHook allows a user-supplied function to be called
	// with the response from each HTTP request executed.
	ResponseLogHook ResponseLogHook

	// Resolver represents the mock definition resolver.
	// The built-in library provides file-based datastore, but it can be easily extended to use any other datastore.
	Resolver ResolverAdapter
	// contains filtered or unexported fields
}

Client is used to make HTTP requests. It adds additional functionality for testing purposes to mock certain http requests based on mock definition.

func NewClient

func NewClient(resolver ResolverAdapter) *Client

NewClient creates a new mockhttp Client with default settings.

func (*Client) Do

func (c *Client) Do(req *Request) (*http.Response, error)

Do wraps calling an HTTP method to also check if the request should be mock or not, based on mock definition loaded during client initialization.

func (*Client) Get

func (c *Client) Get(url string) (*http.Response, error)

Get is a convenience helper for doing simple GET requests.

func (*Client) Head

func (c *Client) Head(url string) (*http.Response, error)

Head is a convenience method for doing simple HEAD requests.

func (*Client) Post

func (c *Client) Post(url, contentType string, body interface{}) (*http.Response, error)

Post is a convenience method for doing simple POST requests.

func (*Client) PostForm

func (c *Client) PostForm(url string, data url.Values) (*http.Response, error)

PostForm is a convenience method for doing simple POST operations using pre-filled url.Values form data.

func (*Client) StandardClient

func (c *Client) StandardClient() *http.Client

StandardClient returns a stdlib *http.Client with a custom Transport, which shims in a *mockhttp.Client for added retries.

type LenReader

type LenReader interface {
	Len() int
}

LenReader is an interface implemented by many in-memory io.Reader's. Used for automatically sending the right Content-Length header when possible.

type LeveledLogger

type LeveledLogger interface {
	Error(msg string, keysAndValues ...interface{})
	Info(msg string, keysAndValues ...interface{})
	Debug(msg string, keysAndValues ...interface{})
	Warn(msg string, keysAndValues ...interface{})
}

LeveledLogger is an interface that can be implemented by any logger or a logger wrapper to provide leveled logging. The methods accept a message string and a variadic number of key-value pairs. For log.Printf style formatting where message string contains a format specifier, use Logger interface.

type Logger

type Logger interface {
	Printf(string, ...interface{})
}

Logger interface allows to use other loggers than standard log.Logger.

type ReaderFunc

type ReaderFunc func() (io.Reader, error)

ReaderFunc is the type of function that can be given natively to NewRequest

type Request

type Request struct {

	// Embed an HTTP request directly. This makes a *Request act exactly
	// like an *http.Request so that all meta methods are supported.
	*http.Request
	// contains filtered or unexported fields
}

Request wraps the metadata needed to create HTTP requests.

func FromRequest

func FromRequest(r *http.Request) (*Request, error)

FromRequest wraps an http.Request in a retryablehttp.Request

func NewRequest

func NewRequest(method, url string, rawBody interface{}) (*Request, error)

NewRequest creates a new wrapped request.

func NewRequestWithContext

func NewRequestWithContext(ctx context.Context, method, url string, rawBody interface{}) (*Request, error)

NewRequestWithContext creates a new wrapped request with the provided context.

The context controls the entire lifetime of a request and its response: obtaining a connection, sending the request, and reading the response headers and body.

func (*Request) BodyBytes

func (r *Request) BodyBytes() ([]byte, error)

BodyBytes allows accessing the request body. It is an analogue to http.Request's Body variable, but it returns a copy of the underlying data rather than consuming it.

This function is not thread-safe; do not call it at the same time as another call, or at the same time this request is being used with Client.Do.

func (*Request) SetBody

func (r *Request) SetBody(rawBody interface{}) error

SetBody allows setting the request body.

It is useful if a new body needs to be set without constructing a new Request.

func (*Request) SetResponseHandler

func (r *Request) SetResponseHandler(fn ResponseHandlerFunc)

SetResponseHandler allows setting the response handler.

func (*Request) WithContext

func (r *Request) WithContext(ctx context.Context) *Request

WithContext returns wrapped Request with a shallow copy of underlying *http.Request with its context changed to ctx. The provided ctx must be non-nil.

func (*Request) WriteTo

func (r *Request) WriteTo(w io.Writer) (int64, error)

WriteTo allows copying the request body into a writer.

It writes data to w until there's no more data to write or when an error occurs. The return int64 value is the number of bytes written. Any error encountered during the write is also returned. The signature matches io.WriterTo interface.

type RequestLogHook

type RequestLogHook func(Logger, *http.Request)

RequestLogHook allows a function to run before http call executed. The HTTP request which will be made.

type ResolverAdapter

type ResolverAdapter interface {
	LoadDefinition(ctx context.Context) error
	Resolve(ctx context.Context, req *Request) (*http.Response, error)
}

Resolver Adapter Contract: 1. LoadDefinition : load mock definition spec from different datastore (file, database, etc...) 2. Resolve : check request and return mock response if exist

used to build any datastore adapter, as long as it able to resolve mock definition properties from http request

func NewFileResolverAdapter

func NewFileResolverAdapter(dir string) (ResolverAdapter, error)

NewFileResolverAdapter returns new ResolverAdapter for Mock client, with file based mock definition.

param: dir (string) -> directory path where all the mock definition specs located.

type ResponseHandlerFunc

type ResponseHandlerFunc func(*http.Response) error

ResponseHandlerFunc is a type of function that takes in a Response, and does something with it. The ResponseHandlerFunc is called when the HTTP client successfully receives a response and the The response body is not automatically closed. It must be closed either by the ResponseHandlerFunc or by the caller out-of-band. Failure to do so will result in a memory leak.

Main purposes: to enable delay for mocking http calls

type ResponseLogHook

type ResponseLogHook func(Logger, *http.Response)

ResponseLogHook is like RequestLogHook, but allows running a function on each HTTP response. This function will be invoked at the end of every HTTP request executed, regardless of whether a subsequent retry needs to be performed or not. If the response body is read or closed from this method, this will affect the response returned from Do().

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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