gophers

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

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

Go to latest
Published: Jan 17, 2017 License: MIT Imports: 17 Imported by: 5

README

Gophers GoDoc Build Status

Gophers is a tool for API testing. It covers:

  • unit testing of individual endpoints;
  • functional testing of broader scenarios;
  • generation of up-to-date examples for documentation from scenarios.

Note: For now it's focused on HTTP APIs. Support for other protocols is planned.

Gophers allows you to write test scenarios in full-power programming languages, not by using limited pesky UI. Those languages are Go and (in the future) Lua.

Go package contains a lot of helpers tailored just for that task. In particular, sometimes they sacrifice idiomatic approach for brevity and simplicity of usage in test scenarios. For example, many methods explicitly fail test or panic instead of returning error which should be checked in test manually.

For example this code can be used to create repository on Github via API and check result:

// Client contains base URL with host, path prefix, default headers and query parameters
// t is *testing.T or compatible interface

// create new request with JSON body
req := Client.NewRequest(t, "POST", "/user/repos", jsons.Parse(`{"name": %q}`, repo))

// enable recording of request and response for documentation
req.EnableRecording("repo_create.apib")

// make request and check response status code
j := Client.Do(t, req, 201).JSON(t)

// check create repository
assert.Equal(t, jsons.Parse(`{"name": %q, "full_name": %q}`, repo, Login+"/"+repo),
	j.KeepFields("name", "full_name"))

// check repository is owned by authenticated user
assert.Equal(t, jsons.Parse(`{"login": %q}`, Login), j.Get("/owner").KeepFields("login"))

// check repository exists via other API
j := Client.Get(t, "/repos/"+Login+"/"+repo, 200).JSON(t)
assert.Equal(t, jsons.Parse(`{"login": %q}`, Login), j.Get("/owner").KeepFields("login"))

Running this scenario with go test and combining recorded request and response with API Blueprint template will produce documentation with accurate and up-to-date examples.

Lua bindings would allow making tests even simpler while using the whole power and speed of Go networking stack. They are work-in-progress.

Usage

Get the package as usual with Go 1.6+:

go get -u github.com/go-gophers/gophers

Then use it for writing your tests, see examples directory.

Future work

First version was hacked during Gopher Gala 2016. Now development happens at https://github.com/go-gophers/gophers. Our plans include:

  • allow to remove extra headers from requests and responses for documentation (Github, why you send so much of them?)
  • better ideomatic Lua bindings (already drafted)
  • fuzz testing (?)
  • support for other protocols and API types
  • mruby bindings (?)

License

Code is licensed under MIT-style license.

Gopher artwork is taken from gophericons. Created by Olga Shalakhina, based on original work by Renée French. Licensed under Creative Commons 3.0 Attributions.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

type Client struct {
	Base           url.URL
	HTTPClient     *http.Client
	DefaultHeaders http.Header
	DefaultCookies []http.Cookie
}

Client wraps base API URL with default headers and cookies. Base URL can contain scheme, user info, host, path prefix and default query parameters.

func NewClient

func NewClient(base url.URL) *Client

NewClient creates new client with given base URL.

func (*Client) Delete

func (c *Client) Delete(t TestingT, urlStr string, expectedStatuses ...int) *Response

Delete makes DELETE request. See Do for more details.

func (*Client) Do

func (c *Client) Do(t TestingT, req *Request, expectedStatuses ...int) *Response

Do makes request and returns response. It also logs and records them and checks that response status code is equal to one of the provided. Request and response Body fields are filled, inner *http.(Request|Response).Body fields are replaced by stubs. In case of error it fails test.

func (*Client) Get

func (c *Client) Get(t TestingT, urlStr string, expectedStatuses ...int) *Response

Get makes GET request. See Do for more details.

func (*Client) Head

func (c *Client) Head(t TestingT, urlStr string, expectedStatuses ...int) *Response

Head makes HEAD request. See Do for more details.

func (*Client) NewRequest

func (c *Client) NewRequest(t TestingT, method string, urlStr string, body fmt.Stringer) *Request

NewRequest creates new request with given method, URL and body. It adds URL's path and query parameters to client's base URL. It also adds default headers and cookies from client. In case of error if fails test.

func (*Client) Patch

func (c *Client) Patch(t TestingT, urlStr string, body fmt.Stringer, expectedStatuses ...int) *Response

Patch makes PATCH request. See Do for more details.

func (*Client) Post

func (c *Client) Post(t TestingT, urlStr string, body fmt.Stringer, expectedStatuses ...int) *Response

Post makes POST request. See Do for more details.

func (*Client) Put

func (c *Client) Put(t TestingT, urlStr string, body fmt.Stringer, expectedStatuses ...int) *Response

Put makes PUT request. See Do for more details.

type Request

type Request struct {
	*http.Request
	Body []byte // filled by Client.Do

	Recorder   recorders.Interface
	RequestWC  io.WriteCloser
	ResponseWC io.WriteCloser
}

Request represents HTTP request and recording parameters.

func (*Request) AddCookies

func (req *Request) AddCookies(c []http.Cookie) *Request

AddCookies adds cookies to request.

func (*Request) AddHeaders

func (req *Request) AddHeaders(h http.Header) *Request

AddHeaders adds headers to request.

func (*Request) EnableRecording

func (req *Request) EnableRecording(baseFileName string) *Request

EnableRecording enables recording of this request and following response to files with given base name. Recorder type is selected by extension: recorders.APIB for ".apib", recorders.Plain for any other.

func (*Request) SetBodyReader

func (req *Request) SetBodyReader(r io.Reader) *Request

SetBodyReader sets request body with given reader. It also tries to set Content-Length header.

func (*Request) SetBodyString

func (req *Request) SetBodyString(s string) *Request

SetBodyString sets request body with given string. It also sets Content-Length header.

func (*Request) SetBodyStringer

func (req *Request) SetBodyStringer(s fmt.Stringer) *Request

SetBodyStringer sets request body with given Stringer. It also sets Content-Length header.

type Response

type Response struct {
	*http.Response
	Body []byte // filled by Client.Do
}

Response represents HTTP response.

func (*Response) JSON

func (r *Response) JSON(t TestingT) (j jsons.Struct)

JSON returns reponse body as JSON structure. In case of error if fails test.

type TestingT

type TestingT interface {
	// Log formats its arguments using default formatting, analogous to Println, and records the text in the error log.
	Log(args ...interface{})

	// Logf formats its arguments according to the format, analogous to Printf, and records the text in the error log.
	Logf(format string, args ...interface{})

	// Failed reports whether the function has failed.
	Failed() bool

	// Fail marks the function as having failed but continues execution.
	Fail()

	// Error is equivalent to Log followed by Fail.
	Error(args ...interface{})

	// Errorf is equivalent to Logf followed by Fail.
	Errorf(format string, args ...interface{})

	// FailNow marks the function as having failed and stops its execution. Execution will continue at the next test.
	// FailNow must be called from the goroutine running the test function, not from other goroutines created during the test.
	// Calling FailNow does not stop those other goroutines.
	FailNow()

	// Fatal is equivalent to Log followed by FailNow.
	Fatal(args ...interface{})

	// Fatalf is equivalent to Logf followed by FailNow.
	Fatalf(format string, args ...interface{})

	// Skipped reports whether the test was skipped.
	Skipped() bool

	// SkipNow marks the test as having been skipped and stops its execution. Execution will continue at the next test. See also FailNow.
	// SkipNow must be called from the goroutine running the test, not from other goroutines created during the test.
	// Calling SkipNow does not stop those other goroutines.
	SkipNow()

	// Skip is equivalent to Log followed by SkipNow.
	Skip(args ...interface{})

	// Skipf is equivalent to Logf followed by SkipNow.
	Skipf(format string, args ...interface{})
}

TestingT is a copy of testing.TB interface without private methods. It can be used to hook other testing libraries, frameworks, and runners, such as gophers tool.

Directories

Path Synopsis
Package config contains configuration for various Gophers methods.
Package config contains configuration for various Gophers methods.
examples
gophers/placehold
Package placehold contains Gophers examples for placehold.it to be used with gophers tool.
Package placehold contains Gophers examples for placehold.it to be used with gophers tool.
testing/github
Package github contains Gophers examples for github.com to be used with go test tool.
Package github contains Gophers examples for github.com to be used with go test tool.
testing/placehold
Package placehold contains Gophers examples for placehold.it to be used with gophers tool.
Package placehold contains Gophers examples for placehold.it to be used with gophers tool.
exp
glua
Package glua provideds Lua bindigs for Gophers tool.
Package glua provideds Lua bindigs for Gophers tool.
Package gophers implements gophers tool.
Package gophers implements gophers tool.
cmd
Package cmd contains implementation of gophers tool commands.
Package cmd contains implementation of gophers tool commands.
runner
Package runner implements test runner used by gophers tool.
Package runner implements test runner used by gophers tool.
Package jsons allows sloppy work with JSON structures (objects and arrays).
Package jsons allows sloppy work with JSON structures (objects and arrays).
Package recorders providers request/response recorders for Gophers tool.
Package recorders providers request/response recorders for Gophers tool.
utils
log
taskpool
Package taskpool provides task pool with variable amount of worker goroutines.
Package taskpool provides task pool with variable amount of worker goroutines.

Jump to

Keyboard shortcuts

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