abide

package module
Version: v0.0.0-...-635a098 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2019 License: Apache-2.0 Imports: 16 Imported by: 0

README

abide

A testing utility for http response snapshots. Inspired by Jest.

Build Status GoDoc

Usage

  1. Include abide in your project.
import "github.com/beme/abide"
  1. Within your test function, capture the response to an http request, set a unique identifier, and assert.
func TestFunction(t *testing.T) {
  req := httptest.NewRequest("GET", "http://example.com/", nil)
  w := httptest.NewRecorder()
  exampleHandler(w, req)
  res := w.Result()
  abide.AssertHTTPResponse(t, "example route", res)
}
  1. Run your tests.
$ go test -v
  1. If the output of your http response does not equal the existing snapshot, the difference will be printed in the test output. If this change was intentional, the snapshot can be updated by including the -u flag.
$ go test -v -- -u

Any snapshots created/updated will be located in package/__snapshots__.

  1. Cleanup

To ensure only the snapshots in-use are included, add the following to TestMain. If your application does not have one yet, you can read about TestMain usage here.

func TestMain(m *testing.M) {
  exit := m.Run()
  abide.Cleanup()
  os.Exit(exit)
}

Once included, if the update -u flag is used when running tests, any snapshot that is no longer in use will be removed. Note: if a single test is run, pruning will not occur.

Snapshots

A snapshot is essentially a lock file for an http response. Instead of having to manually compare every aspect of an http response to it's expected value, it can be automatically generated and used for matching in subsequent testing.

Here's an example snapshot:

/* snapshot: example route */
HTTP/1.1 200 OK
Connection: close
Content-Type: application/json

{
  "key": "value"
}

When working with snapshots in a git repository, you could face some end line replacements that can cause comparison issues (warning: CRLF will be replaced by LF in ...). To solve that just configure the snapshots as binary files in .gitattributes of your project root:

*.snapshot binary

abide also supports testing outside of http responses, by providing an Assert(*testing.T, string, Assertable) method which will create snapshots for any type that implements String() string.

Example

See /example for the usage of abide in a basic web server. To run tests, simply $ go test -v

Config

In some cases, attributes in a JSON response can by dynamic (e.g unique id's, dates, etc.), which can disrupt snapshot testing. To resolve this, an abide.json file config can be included to override values with defaults. Consider the config in the supplied example project:

{
  "defaults": {
    "Etag": "default-etag-value",
    "updated_at": 0,
    "foo": "foobar"
  }
}

When used with AssertHTTPResponse, for any response with Content-Type: application/json, the key-value pairs in defaults will be used to override the JSON response, allowing for consistent snapshot testing. Any HTTP headers will also be override for key matches in defaults.

Using custom __snapshot__ directory

To write snapshots to a directory other than the default __snapshot__, adjust abide.SnapshotDir before any call to an Assert function. See example/models package for a working example

func init() {
  abide.SnapshotDir = "testdata"
}

Documentation

Overview

Package abide is a testing utility for http response snapshots inspired by Facebook's Jest.

It is designed to be used alongside Go's existing testing package and enable broader coverage of http APIs. When included in version control it can provide a historical log of API and application changes over time.

Snapshot

A snapshot is essentially a lockfile representing an http response.

/* snapshot: api endpoint */
HTTP/1.1 200 OK
Connection: close
Content-Type: application/json

{
  "foo": "bar"
}

In addition to testing `http.Response`, abide provides methods for testing `io.Reader` and any object that implements `Assertable`.

Snapshots are saved in a directory named __snapshots__ at the root of the package. These files are intended to be saved and included in version control.

Creating a Snapshot

Snapshots are automatically generated during the initial test run. For example this will create a snapshot identified by "example" for this http.Response.

func TestFunction(t *testing.T) {
   req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
   w := httptest.NewRecorder()
   handler(w, req)
   res := w.Result()
   abide.AssertHTTPResponse(t, "example", res)
}

Comparing and Updating

In subsequent test runs the existing snapshot is compared to the new results. In the event they do not match, the test will fail, and the diff will be printed. If the change was intentional, the snapshot can be updated.

$ go test -- -u

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// SnapshotsDir is the directory snapshots will be read to & written from
	// relative directories are resolved to present-working-directory of the executing process
	SnapshotsDir = "__snapshots__"
)

Functions

func Assert

func Assert(t *testing.T, id string, a Assertable)

Assert asserts the value of an object with implements Assertable.

func AssertHTTPRequest

func AssertHTTPRequest(t *testing.T, id string, r *http.Request)

AssertHTTPRequest asserts the value of an http.Request. Intended for use when testing incoming client requests See https://golang.org/pkg/net/http/httputil/#DumpRequest for more

func AssertHTTPRequestOut

func AssertHTTPRequestOut(t *testing.T, id string, r *http.Request)

AssertHTTPRequestOut asserts the value of an http.Request. Intended for use when testing outgoing client requests See https://golang.org/pkg/net/http/httputil/#DumpRequestOut for more

func AssertHTTPResponse

func AssertHTTPResponse(t *testing.T, id string, w *http.Response)

AssertHTTPResponse asserts the value of an http.Response.

Example
package main

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/beme/abide"
)

var (
	handler = func(*httptest.ResponseRecorder, *http.Request) {}
	t       = &testing.T{}
)

func main() {
	req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
	w := httptest.NewRecorder()
	handler(w, req)
	res := w.Result()
	abide.AssertHTTPResponse(t, "http response", res)
}
Output:

func AssertReader

func AssertReader(t *testing.T, id string, r io.Reader)

AssertReader asserts the value of an io.Reader.

Example
package main

import (
	"net/http"
	"net/http/httptest"
	"os"
	"testing"

	"github.com/beme/abide"
)

var t = &testing.T{}

func main() {
	file, _ := os.Open("/path/to/file")
	abide.AssertReader(t, "io reader", file)
}
Output:

func Cleanup

func Cleanup() error

Cleanup is an optional method which will execute cleanup operations affiliated with abide testing, such as pruning snapshots.

Types

type Assertable

type Assertable interface {
	String() string
}

Assertable represents an object that can be asserted.

func Interface

func Interface(i interface{}) Assertable

Interface is syntactic sugar. It is a helper that converts any type to an Assertable.

Example
package main

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/beme/abide"
)

var t = &testing.T{}

func main() {
	type MyStruct struct {
		Field1 string
		Field2 int64
		Field3 bool
		field4 string
	}
	myStruct := MyStruct{
		"String1",
		1234567,
		true,
		"string4",
	}
	abide.Assert(t, "assertable struct", abide.Interface(myStruct))
}
Output:

func String

func String(s string) Assertable

String is syntactic sugar. It is a helper that converts a string to an Assertable

Example
package main

import (
	"net/http"
	"net/http/httptest"
	"testing"

	"github.com/beme/abide"
)

var t = &testing.T{}

func main() {
	myString := "this is a string I want to snapshot"
	abide.Assert(t, "assertable string", abide.String(myString))
}
Output:

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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