httptesting

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: May 30, 2019 License: MIT Imports: 23 Imported by: 0

README

httptesting

CircleCI

Golang HTTP testing client for human.

Installation

$ go get github.com/dolab/httptesting

Getting Started

package httptesting

import (
	"net/http"
	"testing"

	"github.com/dolab/httptesting"
)

// Testing with httptesting.Request
func Test_Request(t *testing.T) {
	host := "https://example.com"
	client := httptesting.New(host, true)

	request := client.New(t)
	request.Get("/")

	// verify http response status
	if request.AssertOK() {
	    // verify http response header
	    request.AssertExistHeader("Content-Length")

	    // verify http response body
	    request.AssertNotEmpty()
	}
}
Connected with httptest.Server
package httptesting

import (
	"net/http"
	"testing"

	"github.com/dolab/httptesting"
)

type mockServer struct {
	method	string
	path	  string
	assertion func(w http.ResponseWriter, r *http.Request)
}

func (mock *mockServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	mock.assertion(w, r)
}

func Test_Server(t *testing.T) {
	method := "GET"
	uri := "/server/https"
	server := &mockServer{
		method: method,
		path: uri,
		assertion: func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("x-request-method", r.Method)

			w.WriteHeader(http.StatusOK)
			w.Write([]byte("TLS"))
		},
	}

	// return default client connected with httptest.Server
	ts := httptesting.NewServer(server, true)
	defer ts.Close()

	request := ts.New(t)
	request.Get("/server/https")

	// verify http response status
	if request.AssertOK() {
	    // verify http response header
	    request.AssertExistHeader("Content-Length")

	    // verify http response body
	    request.AssertContains("TLS")
	}
}
Advantage Usage
package main

import (
	"testing"
)

func Test_Request(t *testing.T) {
	host := "https://example.com"
	client := httptesting.New(host, true)

	t.Run("GET /api/json", func(t *testing.T) {
		request := client.New(t)
		request.WithHeader("X-Mock-Client", "httptesting")

		// assume server response with following json data:
		// {"user":{"name":"httptesting","age":3},"addresses":[{"name":"china"},{"name":"USA"}]}
		request.GetJSON("/api/json", nil)

		// verify http response status
		if request.AssertOK() {
		    // verify http response header
		    request.AssertHeader("X-Mock-Client", "httptesting")

		    // verify http response body with json format
		    request.AssertContainsJSON("user.name", "httptesting")

		    // for array
		    request.AssertContainsJSON("addresses.1.name", "USA")
		    request.AssertNotContainsJSON("addresses.2.name")

		    // use regexp for custom matcher
		    request.AssertMatch("user.*")
		}
	})

	t.Run("POST /api/json", func(t *testing.T) {
		request := client.New(t)
		request.WithHeader("X-Mock-Client", "httptesting")

		payload := struct {
			Name string `json:"name"`
			Age  int	`json:"age"`
		}{"httptesting", 3}

		// assume server response with following json data:
		// {"data":{"name":"httptesting","age":3},"success":true}
		request.PostJSON("/api/json", payload)

		// verify http response status
		if request.AssertOK() {
		    // verify http response header
		    request.AssertHeader("X-Mock-Client", "httptesting")

		    // verify http response body with json format
		    request.AssertContainsJSON("data.name", "httptesting")
		    request.AssertContainsJSON("data.age", 3)
		    request.AssertContainsJSON("success", true)

		    // use regexp for custom matcher
		    request.AssertNotMatch("user.*")
		}
	})
}

Author

Spring MC

LICENSE

The MIT License (MIT)

Copyright (c) 2016

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client defines request component of httptesting.

NOTE: Client is not safe for concurrency, please use client.New(t) after initialized.

func New

func New(host string, isTLS bool) *Client

New returns an initialized *Client ready for testing

func NewServer

func NewServer(handler http.Handler, isTLS bool) *Client

NewServer returns an initialized *Client along with mocked server for testing NOTE: You MUST call client.Close() for cleanup after testing.

func NewServerWithTLS

func NewServerWithTLS(handler http.Handler, cert tls.Certificate) *Client

NewServerWithTLS returns an initialized *Client along with mocked server for testing NOTE: You MUST call client.Close() for cleanup after testing.

func NewWithTLS

func NewWithTLS(host string, cert *x509.Certificate) *Client

NewWithTLS returns an initialized *Client with custom certificate.

func (*Client) Close

func (c *Client) Close()

Close tries to

  • close *httptest.Server created by NewServer or NewServerWithTLS

func (*Client) Cookies

func (c *Client) Cookies() ([]*http.Cookie, error)

Cookies returns jar related to the host

func (*Client) Host

func (c *Client) Host() string

Host returns the host and port of the server, e.g. "127.0.0.1:9090"

func (*Client) New

func (c *Client) New(t *testing.T) *Request

New is alias of NewRequest for shortcut.

func (*Client) NewClient added in v1.1.0

func (c *Client) NewClient(filters ...RequestFilter) *http.Client

NewClient creates a http client with cookie and tls for the Client.

func (*Client) NewRequest

func (c *Client) NewRequest(t *testing.T) *Request

New returns a *Request which has more customization!

func (*Client) NewWebsocket

func (c *Client) NewWebsocket(t *testing.T, path string) *websocket.Conn

NewWebsocket creates a websocket connection to the given path and returns the connection

func (*Client) SetCookies

func (c *Client) SetCookies(cookies []*http.Cookie) error

SetCookies sets jar for the host

func (*Client) Url

func (c *Client) Url(urlpath string, params ...url.Values) string

Url returns the abs http/isTLS URL of the resource, e.g. "http://127.0.0.1:9090/status". The scheme is set to isTLS if http.ssl is set to true in the configuration.

func (*Client) WebsocketUrl

func (c *Client) WebsocketUrl(urlpath string, params ...url.Values) string

WebsocketUrl returns the abs websocket URL of the resource, e.g. "ws://127.0.0.1:9090/status"

type FilterTransport added in v1.0.0

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

FilterTransport defines a custom http.Transport with filters and certs.

func NewFilterTransport added in v1.0.0

func NewFilterTransport(filters []RequestFilter, certs ...*x509.CertPool) *FilterTransport

func (*FilterTransport) RoundTrip added in v1.0.0

func (transport *FilterTransport) RoundTrip(r *http.Request) (*http.Response, error)

type Request

type Request struct {
	*Client

	Response     *http.Response
	ResponseBody []byte
	// contains filtered or unexported fields
}

Request defines http client for human usage.

func NewRequest

func NewRequest(t *testing.T, client *Client) *Request

NewRequest returns a new *Request with *Client

func (*Request) AssertContains added in v1.0.0

func (r *Request) AssertContains(s string) bool

AssertContains asserts that the response body contains the string.

func (*Request) AssertContainsJSON added in v1.0.0

func (r *Request) AssertContainsJSON(key string, value interface{}) bool

AssertContainsJSON asserts that the response body contains JSON value of the key.

func (*Request) AssertContentType added in v1.0.0

func (r *Request) AssertContentType(contentType string) bool

AssertContentType asserts that the response includes Content-Type header with value.

func (*Request) AssertEmpty added in v1.0.0

func (r *Request) AssertEmpty() bool

AssertEmpty asserts that the response body is empty.

func (*Request) AssertExistHeader added in v1.0.0

func (r *Request) AssertExistHeader(name string) bool

AssertExistHeader asserts that the response includes named header.

func (*Request) AssertForbidden added in v1.0.0

func (r *Request) AssertForbidden() bool

AssertForbidden asserts that the response status code is 403.

func (*Request) AssertHeader added in v1.0.0

func (r *Request) AssertHeader(name, value string) bool

AssertHeader asserts that the response includes named header with value.

func (*Request) AssertInternalError added in v1.0.0

func (r *Request) AssertInternalError() bool

AssertInternalError asserts that the response status code is 500.

func (*Request) AssertMatch added in v1.0.0

func (r *Request) AssertMatch(re string) bool

AssertMatch asserts that the response body matches the regular expression.

func (*Request) AssertNotContains added in v1.0.0

func (r *Request) AssertNotContains(s string) bool

AssertNotContains asserts that the response body does not contain the string.

func (*Request) AssertNotContainsJSON added in v1.0.0

func (r *Request) AssertNotContainsJSON(key string) bool

AssertNotContainsJSON asserts that the response body dose not contain JSON value of the key.

func (*Request) AssertNotEmpty added in v1.0.0

func (r *Request) AssertNotEmpty() bool

AssertNotEmpty asserts that the response body is not empty.

func (*Request) AssertNotExistHeader added in v1.0.0

func (r *Request) AssertNotExistHeader(name string) bool

AssertNotExistHeader asserts that the response does not include named header.

func (*Request) AssertNotFound added in v1.0.0

func (r *Request) AssertNotFound() bool

AssertNotFound asserts that the response status code is 404.

func (*Request) AssertNotMatch added in v1.0.0

func (r *Request) AssertNotMatch(re string) bool

AssertNotMatch asserts that the response body does not match the regular expression.

func (*Request) AssertOK added in v1.0.0

func (r *Request) AssertOK() bool

AssertOK asserts that the response status code is 200.

func (*Request) AssertStatus added in v1.0.0

func (r *Request) AssertStatus(status int) bool

AssertStatus asserts that the response status code is equal to value.

func (*Request) Build added in v1.0.0

func (r *Request) Build(method, urlpath, contentType string, data ...interface{}) (request *http.Request, err error)

func (*Request) Delete

func (r *Request) Delete(path, contentType string, data ...interface{})

Delete issues a DELETE request to the given path, sending request with specified Content-Type header, and stores the result in Response and ResponseBody if success.

func (*Request) DeleteForm

func (r *Request) DeleteForm(path string, data interface{})

DeleteForm issues a DELETE request to the given path with Content-Type: application/x-www-form-urlencoded header, and stores the result in Response and ResponseBody if success.

func (*Request) DeleteJSON

func (r *Request) DeleteJSON(path string, data interface{})

DeleteJSON issues a DELETE request to the given path with Content-Type: application/json header, and stores the result in Response and ResponseBody if success. NOTE: It will encode data by json.Marshal before making request.

func (*Request) DeleteXML

func (r *Request) DeleteXML(path string, data interface{})

DeleteXML issues a DELETE request to the given path with Content-Type: text/xml header, and stores the result in Response and ResponseBody if success. NOTE: It will encode data by xml.Marshal before making request.

func (*Request) Get

func (r *Request) Get(path string, params ...url.Values)

Get issues a GET request to the given path with Content-Type: text/html header, and stores the result in Response and ResponseBody if success.

func (*Request) GetJSON

func (r *Request) GetJSON(path string, params ...url.Values)

GetJSON issues a GET request to the given path with Content-Type: application/json header, and stores the result in Response and ResponseBody if success.

func (*Request) GetXML

func (r *Request) GetXML(path string, params ...url.Values)

GetXML issues a GET request to the given path with Content-Type: text/xml header, and stores the result in Response and ResponseBody if success.

func (*Request) Head

func (r *Request) Head(path string, params ...url.Values)

Head issues a HEAD request to the given path with Content-Type: text/html header, and stores the result in Response if success.

func (*Request) NewMultipartRequest

func (r *Request) NewMultipartRequest(method, path, filename string, file interface{}, fields ...map[string]string)

NewMultipartRequest issues a multipart request for the method & fields given and read the response. If successful, the caller may examine the Response and ResponseBody properties.

func (*Request) NewRequest

func (r *Request) NewRequest(request *http.Request, filters ...RequestFilter)

NewRequest issues any request and read the response. If successful, the caller may examine the Response and ResponseBody properties. NOTE: You have to manage session / cookie data manually.

func (*Request) NewSessionRequest

func (r *Request) NewSessionRequest(request *http.Request, filters ...RequestFilter)

NewSessionRequest issues any request with session / cookie and read the response. If successful, the caller may examine the Response and ResponseBody properties. NOTE: Session data will be added to the request jar for requested host.

func (*Request) Options

func (r *Request) Options(path string, params ...url.Values)

Options issues an OPTIONS request to the given path Content-Type: text/html header, and stores the result in Response if success.

func (*Request) Patch

func (r *Request) Patch(path, contentType string, data ...interface{})

Patch issues a PATCH request to the given path with specified Content-Type header, and stores the result in Response and ResponseBody if success.

func (*Request) PatchForm

func (r *Request) PatchForm(path string, data interface{})

PatchForm issues a PATCH request to the given path with Content-Type: application/x-www-form-urlencoded header, and stores the result in Response and ResponseBody if success.

func (*Request) PatchJSON

func (r *Request) PatchJSON(path string, data interface{})

PatchJSON issues a PATCH request to the given path with with Content-Type: application/json header, and stores the result in Response and ResponseBody if success. It will encode data by json.Marshal before making request.

func (*Request) PatchXML

func (r *Request) PatchXML(path string, data interface{})

PatchXML issues a PATCH request to the given path with Content-Type: text/xml header, and stores the result in Response and ResponseBody if success. NOTE: It will encode data by xml.Marshal before making request.

func (*Request) Post

func (r *Request) Post(path, contentType string, data ...interface{})

Post issues a POST request to the given path with specified Content-Type header, and stores the result in Response and ResponseBody if success.

func (*Request) PostForm

func (r *Request) PostForm(path string, data interface{})

PostForm issues a POST request to the given path with Content-Type: application/x-www-form-urlencoded header, and stores the result in Response and ResponseBody if success.

func (*Request) PostJSON

func (r *Request) PostJSON(path string, data interface{})

PostJSON issues a POST request to the given path with Content-Type: application/json header, and stores the result in Response and ResponseBody if success. NOTE: It will encode data by json.Marshal before making request.

func (*Request) PostXML

func (r *Request) PostXML(path string, data interface{})

PostXML issues a POST request to the given path with Content-Type: text/xml header, and stores the result in Response and ResponseBody if success. NOTE: It will encode data by xml.Marshal before making request.

func (*Request) Put

func (r *Request) Put(path, contentType string, data ...interface{})

Put issues a PUT request to the given path with specified Content-Type header, and stores the result in Response and ResponseBody if success.

func (*Request) PutForm

func (r *Request) PutForm(path string, data interface{})

PutForm issues a PUT request to the given path with Content-Type: application/x-www-form-urlencoded header, and stores the result in Response and ResponseBody if success.

func (*Request) PutJSON

func (r *Request) PutJSON(path string, data interface{})

PutJSON issues a PUT request to the given path with Content-Type: application/json header, and stores the result in Response and ResponseBody if success. NOTE: It will encode data by json.Marshal before making request.

func (*Request) PutXML

func (r *Request) PutXML(path string, data interface{})

PutXML issues a PUT request to the given path with Content-Type: text/xml header, and stores the result in Response and ResponseBody if success. NOTE: It will encode data by xml.Marshal before making request.

func (*Request) Send

func (r *Request) Send(method, path, contentType string, data ...interface{})

Send issues a HTTP request to the given path with specified method and content type header, and stores the result in Response and ResponseBody if success. NOTE: It will encode data with json.Marshal for unsupported types and reset content type to application/json for the request.

func (*Request) WithCookies added in v1.0.0

func (r *Request) WithCookies(cookies []*http.Cookie) *Request

WithCookie sets jar for client by replace for the request

func (*Request) WithHeader

func (r *Request) WithHeader(key, value string) *Request

WithHeader sets http header by replace for the request

func (*Request) WithHttpHeader

func (r *Request) WithHttpHeader(header http.Header) *Request

WithHttpHeader adds http header for the request

type RequestFilter added in v1.0.0

type RequestFilter func(r *http.Request) error

RequestFilter is a callback for http request injection.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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