apitest

package module
v1.0.0-alpha.2 Latest Latest
Warning

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

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

README

This library is on version 0 and we won't guarantee backwards compatible API changes until we go to version 1. The roadmap for version 1 includes mocking external http calls and sequence diagram generation.

api-test

GoDoc Codacy Badge Build Status Coverage Status

Simple behavioural (black box) api testing library.

In black box tests the internal structure of the app is not know by the tests. Data is input to the system and the outputs are expected to meet certain conditions.

This library is dependency free and we intend to keep it that way

Installation

go get -u github.com/steinfletcher/api-test

Examples

Framework and library integration examples
Example Comment
gin popular martini-like web framework
gorilla the gorilla web toolkit
mocks example mocking out external http calls
Companion libraries
Library Comment
JSONPath JSONPath assertion addons
Code snippets
JSON body matcher
func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/user/1234").
		Expect(t).
		Body(`{"id": "1234", "name": "Tate"}`).
		Status(http.StatusCreated).
		End()
}
JSONPath

For asserting on parts of the response body JSONPath may be used. A separate module must be installed which provides these assertions - go get -u github.com/steinfletcher/api-test-jsonpath. This is packaged separately to keep this library dependency free.

Given the response is {"a": 12345, "b": [{"key": "c", "value": "result"}]}

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		Expect(t).
		Assert(jsonpath.Contains(`$.b[? @.key=="c"].value`, "result")).
		End()
}

and jsonpath.Equals checks for value equality

func TestApi(t *testing.T) {
	apitest.New(handler).
		Get("/hello").
		Expect(t).
		Assert(jsonpath.Equal(`$.a`, float64(12345))).
		End()
}
Custom assert functions
func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		Expect(t).
		Assert(func(res *http.Response, req *http.Request) {
			assert.Equal(t, http.StatusOK, res.StatusCode)
		}).
		End()
}
Assert cookies
func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Patch("/hello").
		Expect(t).
		Status(http.StatusOK).
		Cookies(ExpectedCookie"ABC").Value("12345")).
		CookiePresent("Session-Token").
		CookieNotPresent("XXX").
        Cookies(
			ExpectedCookie"ABC").Value("12345"),
			ExpectedCookie"DEF").Value("67890")).
		End()
}
Assert headers
func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		Expect(t).
		Status(http.StatusOK).
		Headers(map[string]string{"ABC": "12345"}).
		End()
}
Mocking external http calls
var getUser = apitest.NewMock().
	Get("/user/12345").
	RespondWith().
	Body(`{"name": "jon", "id": "1234"}`).
	Status(http.StatusOK).
	End()

var getPreferences = apitest.NewMock().
	Get("/preferences/12345").
	RespondWith().
	Body(`{"is_contactable": true}`).
	Status(http.StatusOK).
	End()

func TestApi(t *testing.T) {
	apitest.New().
		Mocks(getUser, getPreferences).
		Handler(handler).
		Get("/hello").
		Expect(t).
		Status(http.StatusOK).
		Body(`{"name": "jon", "id": "1234"}`).
		End()
}
Provide basic auth in the request
func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		BasicAuth("username:password").
		Expect(t).
		Status(http.StatusOK).
		End()
}
Provide cookies in the request
func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		Cookies(ExpectedCookie"ABC").Value("12345")).
		Expect(t).
		Status(http.StatusOK).
		End()
}
Provide headers in the request
func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Delete("/hello").
		Headers(map[string]string{"My-Header": "12345"}).
		Expect(t).
		Status(http.StatusOK).
		End()
}
Provide query parameters in the request

Query can be used in combination with QueryCollection

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		Query(map[string]string{"a": "b"}).
		Expect(t).
		Status(http.StatusOK).
		End()
}
Provide query parameters in collection format in the request

Providing {"a": {"b", "c", "d"} results in parameters encoded as a=b&a=c&a=d. QueryCollection can be used in combination with Query

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Get("/hello").
		QueryCollection(map[string][]string{"a": {"b", "c", "d"}}).
		Expect(t).
		Status(http.StatusOK).
		End()
}
Capture the request and response data
func TestApi(t *testing.T) {
	apitest.New().
		Observe(func(res *http.Response, req *http.Request) {
    	    		// do something with res and req
    		}).
		Handler(handler).
		Get("/hello").
		Expect(t).
		Status(http.StatusOK).
		End()
}

one usage for this might be debug logging to the console. The provided DumpHttp function does this automatically

func TestApi(t *testing.T) {
	apitest.New().
		Observe(apitest.DumpHttp).
		Handler(handler).
		Post("/hello").
		Body(`{"a": 12345}`).
		Headers(map[string]string{"Content-Type": "application/json"}).
		Expect(t).
		Status(http.StatusCreated).
		End()
}
Intercept the request

This is useful for mutating the request before it is sent to the system under test.

func TestApi(t *testing.T) {
	apitest.New().
		Handler(handler).
		Intercept(func(req *http.Request) {
			req.URL.RawQuery = "a[]=xxx&a[]=yyy"
		}).
		Get("/hello").
		Expect(t).
		Status(http.StatusOK).
		End()
}

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrFailedToMatch = "failed to match any of the defined mocks"
)

Functions

This section is empty.

Types

type APITest

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

APITest is the top level struct holding the test spec

func New

func New(name ...string) *APITest

New creates a new api test. The name is optional and will appear in test reports

func (*APITest) BuildRequest

func (a *APITest) BuildRequest() *http.Request

func (*APITest) Handler

func (a *APITest) Handler(handler http.Handler) *Request

Handler defines the http handler that is invoked when the test is run

func (*APITest) HttpClient

func (a *APITest) HttpClient(cli *http.Client) *APITest

HttpClient allows the developer to provide a custom http client when using mocks

func (*APITest) Mocks

func (a *APITest) Mocks(mocks ...*Mock) *APITest

Mocks is a builder method for setting the mocks

func (*APITest) Observe added in v0.0.2

func (a *APITest) Observe(observer Observe) *APITest

Observe is a builder method for setting the observer

func (*APITest) Request

func (a *APITest) Request() *Request

Request returns the request spec

func (*APITest) Response

func (a *APITest) Response() *Response

Response returns the expected response

type Assert

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

Assert is a user defined custom assertion function

var IsClientError Assert = func(response *http.Response, request *http.Request) error {
	if response.StatusCode >= 400 && response.StatusCode < 500 {
		return nil
	}
	return errors.New("not a client error. Status code=" + strconv.Itoa(response.StatusCode))
}

IsClientError is a convenience function to assert on a range of client error status codes

var IsServerError Assert = func(response *http.Response, request *http.Request) error {
	if response.StatusCode >= 500 {
		return nil
	}
	return errors.New("not a server error. Status code=" + strconv.Itoa(response.StatusCode))
}

IsServerError is a convenience function to assert on a range of server error status codes

var IsSuccess Assert = func(response *http.Response, request *http.Request) error {
	if response.StatusCode >= 200 && response.StatusCode < 400 {
		return nil
	}
	return errors.New("not a client error. Status code=" + strconv.Itoa(response.StatusCode))
}

IsSuccess is a convenience function to assert on a range of happy path status codes

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

func NewCookie

func NewCookie(name string) *Cookie

func (*Cookie) Domain

func (cookie *Cookie) Domain(domain string) *Cookie

func (*Cookie) Expires

func (cookie *Cookie) Expires(expires time.Time) *Cookie

func (*Cookie) HttpOnly

func (cookie *Cookie) HttpOnly(httpOnly bool) *Cookie

func (*Cookie) MaxAge

func (cookie *Cookie) MaxAge(maxAge int) *Cookie

func (*Cookie) Path

func (cookie *Cookie) Path(path string) *Cookie

func (*Cookie) Secure

func (cookie *Cookie) Secure(secure bool) *Cookie

func (*Cookie) ToHttpCookie

func (cookie *Cookie) ToHttpCookie() *http.Cookie

func (*Cookie) Value

func (cookie *Cookie) Value(value string) *Cookie

type Intercept

type Intercept func(*http.Request)

Intercept will be called before the request is made. Updates to the request will be reflected in the test

type Matcher

type Matcher func(*http.Request, *MockRequest) bool

type Mock

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

func NewMock

func NewMock() *Mock

func (*Mock) Delete

func (m *Mock) Delete(u string) *MockRequest

func (*Mock) Get

func (m *Mock) Get(u string) *MockRequest

func (*Mock) Method

func (m *Mock) Method(method string) *MockRequest

func (*Mock) Patch

func (m *Mock) Patch(u string) *MockRequest

func (*Mock) Post

func (m *Mock) Post(u string) *MockRequest

func (*Mock) Put

func (m *Mock) Put(u string) *MockRequest

type MockRequest

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

func (*MockRequest) Body

func (r *MockRequest) Body(b string) *MockRequest

func (*MockRequest) Header

func (r *MockRequest) Header(key, value string) *MockRequest

func (*MockRequest) Headers

func (r *MockRequest) Headers(headers map[string]string) *MockRequest

func (*MockRequest) Query

func (r *MockRequest) Query(key, value string) *MockRequest

func (*MockRequest) QueryParams

func (r *MockRequest) QueryParams(queryParams map[string]string) *MockRequest

func (*MockRequest) QueryPresent

func (r *MockRequest) QueryPresent(key string) *MockRequest

func (*MockRequest) RespondWith

func (r *MockRequest) RespondWith() *MockResponse

type MockResponse

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

func (*MockResponse) Body

func (r *MockResponse) Body(body string) *MockResponse

func (*MockResponse) Cookie

func (r *MockResponse) Cookie(name, value string) *MockResponse

func (*MockResponse) Cookies

func (r *MockResponse) Cookies(cookie ...*Cookie) *MockResponse

func (*MockResponse) End

func (r *MockResponse) End() *Mock

func (*MockResponse) Header

func (r *MockResponse) Header(name string, value string) *MockResponse

func (*MockResponse) Headers

func (r *MockResponse) Headers(headers map[string]string) *MockResponse

func (*MockResponse) Status

func (r *MockResponse) Status(statusCode int) *MockResponse

func (*MockResponse) Times

func (r *MockResponse) Times(times int) *MockResponse

type Observe

type Observe func(*http.Response, *http.Request)

Observe will be called by with the request and response on completion

var DumpHttp Observe = func(res *http.Response, req *http.Request) {
	requestDump, err := httputil.DumpRequest(req, true)
	if err == nil {
		fmt.Println("--> http request dump\n\n" + string(requestDump))
	}

	responseDump, err := httputil.DumpResponse(res, true)
	if err == nil {
		fmt.Println("<-- http response dump:\n\n" + string(responseDump))
	}
}

DumpHttp logs the http wire representation of the request and response

type Request

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

Request is the user defined request that will be invoked on the handler under test

func (*Request) BasicAuth

func (r *Request) BasicAuth(auth string) *Request

BasicAuth is a builder method to sets basic auth on the request. The credentials should be provided delimited by a colon, e.g. "username:password"

func (*Request) Body

func (r *Request) Body(b string) *Request

Body is a builder method to set the request body

func (*Request) Cookies

func (r *Request) Cookies(c ...*Cookie) *Request

Cookies is a builder method to set the request cookies

func (*Request) Delete

func (r *Request) Delete(url string) *Request

Delete is a convenience method for setting the request as http.MethodDelete

func (*Request) Expect

func (r *Request) Expect(t *testing.T) *Response

Expect marks the request spec as complete and following code will define the expected response

func (*Request) Get

func (r *Request) Get(url string) *Request

Get is a convenience method for setting the request as http.MethodGet

func (*Request) Headers

func (r *Request) Headers(h map[string]string) *Request

Headers is a builder method to set the request headers

func (*Request) Intercept

func (r *Request) Intercept(interceptor Intercept) *Request

Intercept is a builder method for setting the request interceptor

func (*Request) Method

func (r *Request) Method(method string) *Request

Method is a builder method for setting the http method of the request

func (*Request) Patch

func (r *Request) Patch(url string) *Request

Patch is a convenience method for setting the request as http.MethodPatch

func (*Request) Post

func (r *Request) Post(url string) *Request

Post is a convenience method for setting the request as http.MethodPost

func (*Request) Put

func (r *Request) Put(url string) *Request

Put is a convenience method for setting the request as http.MethodPut

func (*Request) Query

func (r *Request) Query(q map[string]string) *Request

Query is a builder method to set the request query parameters. This can be used in combination with request.QueryCollection

func (*Request) QueryCollection

func (r *Request) QueryCollection(q map[string][]string) *Request

QueryCollection is a builder method to set the request query parameters This can be used in combination with request.Query

func (*Request) URL

func (r *Request) URL(url string) *Request

URL is a builder method for setting the url of the request

type Response

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

Response is the user defined expected response from the application under test

func (*Response) Assert

func (r *Response) Assert(fn func(*http.Response, *http.Request) error) *Response

Assert allows the consumer to provide a user defined function containing their own custom assertions

func (*Response) Body

func (r *Response) Body(b string) *Response

Body is the expected response body

func (*Response) CookieNotPresent

func (r *Response) CookieNotPresent(cookieName string) *Response

CookieNotPresent is used to assert that a cookie is not present in the response

func (*Response) CookiePresent

func (r *Response) CookiePresent(cookieName string) *Response

CookiePresent is used to assert that a cookie is present in the response, regardless of its value

func (*Response) Cookies

func (r *Response) Cookies(cookies ...*Cookie) *Response

Cookies is the expected response cookies

func (*Response) End

func (r *Response) End()

End runs the test and all defined assertions

func (*Response) Headers

func (r *Response) Headers(headers map[string]string) *Response

Headers is the expected response headers

func (*Response) Status

func (r *Response) Status(s int) *Response

Status is the expected response http status code

type Transport

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

func NewTransport

func NewTransport(mocks []*Mock, httpClient *http.Client) *Transport

func (*Transport) Hijack

func (r *Transport) Hijack()

func (*Transport) Reset

func (r *Transport) Reset()

func (*Transport) RoundTrip

func (r *Transport) RoundTrip(req *http.Request) (*http.Response, error)

Directories

Path Synopsis
examples module

Jump to

Keyboard shortcuts

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