Git Product home page Git Product logo

abide's Introduction

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"
}

abide's People

Contributors

alexhornbake avatar arp242 avatar b5 avatar meydjer avatar rafaeljusto avatar sjkaliski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

abide's Issues

With Go 1.15, tests fail

I believe this is from 1.15 on (read a long discussion if you're interested):

$ go test ./...
# github.com/beme/abide
./abide_test.go:25:9: conversion from int to string yields a string of one rune, not a string of digits (did you mean fmt.Sprint(x)?)

json unmarshaling asserts an error when using json Encoding

The hard coded implementation in assert.go for parsing json responses breaks when using json.NewEncoder([insert-my-struct]).Enocde(w). It asserts that

To reproduce:

type myStruct struct {
    Message `json:"message"`
}

func myHandler(w http.ResponseWriter, r *http.Request) {
    m := myStruct{
        Message: "hello abide"
    }
    json.NewEncoder(w).Encode(&m)
}

if you call assert http response on the above in some test: abide.AssertHTTPResponse(t, name, w.Result()), assert will return an error for unexpected end of JSON input. This is because there's a new line that seems to be returned from httputil.DumpResponse on the json response when using NewEncoder vs using json.Marshal and writing bytes.

assert.go seems to be manually parsing the lines to determine the body, instead it probably makes more sense to actually read the properties from the response rather than the dump from httputil (I think there are a few cases where the dump won't always be consistent - but can't remember off the top of my head)

Encapsulate Snapshots as collection

Building on the changes described in #39 into a more sustainable solution. I think it would make sense to isolate these configuration details into a struct that behaves in a similar way to http.Client, with a DefaultClient variable that is automatically loaded to maintain current behaviour.

Something like:

// Snapshots is a collection of snapshots for testing purposes
type Snapshots struct {
  Dir string
  Ext string
  Separator string
  snapshots map[snapshotID]*snapshot
}

// NewSnapshots creates a Snapshots collection with Default settings
func NewSnapshots() Snapshots {
  return Snapshots{
    Dir: SnapshotsDir,
    Ext: SnapshotExt,
    Separator: snapshotSeparator,
  }
}

// DefaultSnapshots is the default snapshot collection used
// without any additional configuration required
var DefaultSnapshots = NewSnapshots()

This is obviously a big change worth discussing first, but the upside would be the capacity to provision multiple instances of snapshot collections, allowing users to setup & teardown snapshots for versioned API tests in specific test funcs, etc.

Make snapshots concurrency safe

I may tackle this one, but want to raise here first.

I think it would be worth converting snapshots map[snapshotID]*snapshot to use sync.Map, or perhaps just use a mutex to protect it. Wondering if there is a preference for minimum golang version that should be targeted, since sync.Map was introduced in golang 1.9. Thoughts?

For context, my use case is a set of tests that assert snapshots from multiple concurrent goroutines. As written, it hits the error: fatal error: concurrent map writes while updating snapshots on github.com/beme/abide/abide.go:230.

abide.json

Hey,

Love the library been really helpful in taking snapshot testing to our go libs. I've been trying to use abide.json defaults with code that looks like something like the following:

type UserData struct {
	Name           string `json:"name"`
	Email          string `json:"email"`
}

func TestMyFn(t *testing.T) {
    randNum := rand.Intn(1000000000)
    // we generate random emails as user factories in our tests
    email := fmt.Sprintf("shlomo-%[email protected]", randNum)

    u := []UserData{{"shlomo", email}}
    userBytes, err := json.Marshal(users)
    abide.AssertReader(t, tt.name, bytes.NewReader(userBytes))
}

my abide.json:

{
    "defaults": {
        "email": "foo"
    }
}

but it doesn't seem like abide picks up the defaults and in the snapshot the random email is stored and subsequent tests without an update fail. i define abide.json on the defaults of the lib. Happy to share a larger example if it's helpful.

Thanks!

support updating a snaphot

If a snapshot is out of date and the user wants to automatically update it, passing the -u flag should do so and notify the user that it's been updated.

$ go test -v -- -u

add option write to `testdata` instead of `__snapshots__`?

Fantastic tool! Love bringing react concepts into go land ๐Ÿ˜„.

While go tool has special treatment for directories & filenames that start with .,_, or testdata, the testdata directory it's considered by some to be idiomatic. I know it's a totally irate thing, but would it be great if I could chose to write snapshots to testdata/__snapshots_. One way might be to export the default hardcoded snapshots var. I'd be happy to submit a PR if you're ok with the idea!

ability to pretty-print non http requests

It would be awesome to able to be able to specify that you want to assert any arbitrary struct via it's json representation and to pretty print that struct in the snapshot. Right now instead I rely on encoding the struct and then passing it to AssertReader which doesn't pretty print the struct which makes comparisons between snapshots and to visualization json results difficult for large responses.

Use cases for this are larger structs that I would love to be able to assert via json (they never pass through an http endpoint).

I haven't looked through the internals of abide, but would be happy to take a look if it was something that you're interested in adding and we can agree on a correct interface for such an assertion

add docs and examples for `Assert` and `Assertable`

This package supports asserting arbitrary types so long as they implement the Assertable interface. This feature is not particularly well documented, and #33 highlighted a few common use cases that may be helpful to include.

Fail test on missing/new snapshot

Pairing with @colinmcardell and explaining the how/why of snapshots it occured to me that it would be really helpful that default case should be a failure.

If no snapshot exists, treat the snapshot as "" such that the new response is logged. Do not capture a snapshot until the user explicitly runs -- -u

Config for HTTP headers

Is it possible to replace a dynamic generated HTTP header using the config? I have an Etag HTTP header that is different every time I receive the response (time based).

Cache test results

Because abide library always write the snapshot file here when calling abide.Cleanup() the tests are never cached. Do we need to save those snapshots every time in the cleanup?

abidecache.go

package abidecache

import (
	"encoding/json"
	"net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
	data := map[string]string{
		"foo": "bar",
	}

	body, err := json.Marshal(data)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.Write(body)
}

abidecache_test.go

package abidecache

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

	"github.com/beme/abide"
)

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

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

Running (snapshots already updated)

โžœ  go test ./...
ok  	labs/abidecache	0.018s
โžœ  go test ./...
ok  	labs/abidecache	0.022s

Running (abide.Cleanup commented)

โžœ  go test ./...
ok  	labs/abidecache	0.018s
โžœ  go test ./...
ok  	labs/abidecache	(cached)

custom http dump

  • json key ordering
  • res.Body prettyprint
  • offers opportunity for .abide file w/ custom rules

snapshot file naming and location

Instead of having a single snapshot directory and file each directory should have it's own snapshot directory and each test file should have it's own snapshot file, e.g.

main.go
main_test.go
__snapshots__/
  main.snapshot
models/
  user.go
  user_test.go
  post.go
  post_test.go
  __snapshots__/
    user.snapshot
    post.snapshot

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.