httpt

package module
v0.0.0-...-5312315 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2017 License: Apache-2.0 Imports: 6 Imported by: 0

README

go-httpt

Build Status Go Report Card

Standard httptest package is great, but there is lot of boilerplate needed to mock your single HTTP response.

httpt is a small library that provides quick request-response mock for your Golang tests!

Usage

httpt provides Server struct. Using that you can specify any round trip scenario (on what request what round trip you want).

For example inside unit-test:

package somepackage

import (
    "net/http"
    "testing"
    
    "github.com/Bplotka/go-httpt"
    "github.com/Bplotka/go-httpt/rt"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
)


func TestSomething(t *testing.T) {
    request, err := http.NewRequest(...)
    // handle err...
            
    s := httpt.NewServer(t)
    s.On(httpt.GET, "/test/path").Push(rt.StringResponseFunc(http.StatusBadRequest, "really_bad_request"))
    s.On(httpt.POST, httpt.AnyPath).Push(rt.JSONResponseFunc(http.StatusOK, []byte(`{"error": "really_bad_request"}`)))

    testClient := s.HTTPClient()
    // Pass testClient to your components for mocked HTTP calls...
}

Having the scenario we can pass mocked HTTP client anywhere. It is common for complex libraries to not use interface but rather enabling custom clients from context.Context e.g standard oauth2 package. In this case, we can just pass our httpt.Server's client:

ctx = context.WithValue(ctx, oauth2.HTTPClient, s.HTTPClient())

// Pass ctx into oauth component...

Using that pattern is really convenient. Imagine now using such libraries (that take custom clients and make lots of HTTP requests internally) within HTTP Handler itself. To properly test your Server with HTTP handlers in your unit test you can use this approach:

package somepackage

import (
    "context"
    "net/http"
    "net/http/httptest"
    "testing"
    
    "github.com/Bplotka/go-httpt"
    "github.com/Bplotka/go-httpt/rt"
    "github.com/stretchr/testify/assert"
    "github.com/stretchr/testify/require"
    "golang.org/x/oauth2"
)


func TestYourServer(t *testing.T) {
    request, err := http.NewRequest(...)
    // handle err...
    
    s := httpt.NewServer(t)
    s.On(httpt.GET, "/test/path").Push(rt.StringResponseFunc(http.StatusBadRequest, "really_bad_request"))
    s.On(httpt.POST, httpt.AnyPath).Push(rt.JSONResponseFunc(http.StatusOK, []byte(`{"error": "really_bad_request"}`)))

    rec := httptest.NewRecorder()
    yourServer.ServeHTTP(
        rec,
        // Pass test HTTP client.
        request.WithContext(
            context.WithValue(context.TODO(), oauth2.HTTPClient, s.HTTPClient()),
        ),
    )
    // ...
}

Documentation

Index

Constants

View Source
const (
	// ANY matches with any HTTP method.
	ANY     = Method("")
	CONNECT = Method("CONNECT")
	DELETE  = Method("DELETE")
	GET     = Method("GET")
	HEAD    = Method("HEAD")
	OPTIONS = Method("OPTIONS")
	PATCH   = Method("PATCH")
	POST    = Method("POST")
	PUT     = Method("PUT")
	TRACE   = Method("TRACE")

	// AnyPath matches will all request paths.
	AnyPath = "!AnyPath!"
)

Variables

This section is empty.

Functions

func FailureFunc

func FailureFunc(err error) func(*http.Request) (*http.Response, error)

FailureFunc is a round trip function that returns error. It can simulate connection error or timeouts.

func NotMockedFunc

func NotMockedFunc(t *testing.T) func(*http.Request) (*http.Response, error)

NotMockedFunc is a round trip function that fails Go test. It is used if accidentally httpt.Server is used but not round trip func was stacked.

Types

type Method

type Method string

Method is an HTTP method.

type RoundTripFunc

type RoundTripFunc func(*http.Request) (*http.Response, error)

RoundTripFunc is a function to mock HTTP request-response round trip. It is loaded into standard http.Client as a mock transport.

type Server

type Server struct {
	DefaultRoundTrip RoundTripFunc
	// contains filtered or unexported fields
}

Server is a test HTTP server that is able to stack multiple round trips for any test case. Example usage:

s := httpt.NewServer(t)
s.Push(StringResponse(http.StatusBadRequest, "really bad request"))
...
// Make sure your component uses mocked http e.g passed in context:
ctx = context.WithValue(ctx, oauth2.HTTPClient, s.HTTTPClient())

// Or used directly:
resp, err := s.HTTPClient().Do(request)

func NewRawServer

func NewRawServer() *Server

NewRawServer constructs Server without any default round trip function. This is used when someone needs to use Server without testing package.

func NewServer

func NewServer(t *testing.T) *Server

NewServer constructs Server with NotMockedFunc as default. Always use that when running within go test.

func (*Server) HTTPClient

func (s *Server) HTTPClient() *http.Client

HTTPClient returns standrard http.Client to feed components the needs to be mocked.

func (*Server) Len

func (s *Server) Len() int

Len returns number of round trip functions (requests) that are mocked. Useful example:

assert.Equal(t, 0, s.Len()) // at the end of your unit test with httpt.Server, to check if all mocked requests were actually used.

func (Server) On

func (t Server) On(method Method, path string) *tripPusher

On specifies particular method and path for mocked round trip function. Example usage:

server.On(httpt.GET, "/path/test").Push(<any round trip function>)

func (*Server) Reset

func (s *Server) Reset()

Reset resets stacked round trip functions. Nothing is mocked after that.

func (*Server) StillExpectedRTs

func (s *Server) StillExpectedRTs() []string

NotDoneRTs returns string slice with concatenated [METHOD]path for Round trips which are still expected. Useful when after test Len != 0.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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