cupaloy

package module
v2.3.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2018 License: MIT Imports: 10 Imported by: 0

README

Mascot
Build Status Coverage Status Go Report Card GoDoc Number of users

Incredibly simple Go snapshot testing: cupaloy takes a snapshot of your test output and compares it to a snapshot committed alongside your tests. If the values don't match then the test will be failed.

There's no need to manually manage snapshot files: just use the cupaloy.SnapshotT(t, value) function in your tests and cupaloy will automatically find the relevant snapshot file (based on the test name) and compare it with the given value.

Usage

Write a test

Firstly, write a test case generating some output and pass this output to cupaloy.SnapshotT:

func TestParsing(t *testing.T) {
    ast := ParseFile("test_input")

    // check that the result is the same as the last time the snapshot was updated
    // if the result has changed (e.g. because the behaviour of the parser has changed)
    // then the test will be failed with an error containing a diff of the changes
    cupaloy.SnapshotT(t, ast)
}

The first time this test is run, a snapshot will be automatically created (using the github.com/davecgh/go-spew package).

Update a snapshot

When the behaviour of your software changes causing the snapshot to change, this test will begin to fail with an error showing the difference between the old and new snapshots. Once you are happy that the new snapshot is correct (and hasn't just changed unexpectedly), you can save the new snapshot by setting the UPDATE_SNAPSHOTS environment and re-running your tests:

UPDATE_SNAPSHOTS=true go test ./...

This will fail all tests where the snapshot was updated (to stop you accidentally updating snapshots in CI) but your snapshot files will now have been updated to reflect the current output of your code.

Supported formats

Snapshots of test output are generated using the github.com/davecgh/go-spew package which uses reflection to deep pretty-print your test result and so will support almost all the basic types (from simple strings, slices, and maps to deeply nested structs) without issue. The only types whose contents cannot be fully pretty-printed are functions and channels.

The most important property of your test output is that it is deterministic: if your output contains timestamps or other fields which will change on every run, then cupaloy will detect this as a change and so fail the test.

Further Examples

Table driven tests
var testCases = map[string][]string{
    "TestCaseOne": []string{......},
    "AnotherTestCase": []string{......},
    ....
}

func TestCases(t *testing.T) {
    for testName, args := range testCases {
        t.Run(testName, func(t *testing.T) {
            result := functionUnderTest(args...)
            cupaloy.SnapshotT(t, result)
        })
    }
}
Changing output directory
func TestSubdirectory(t *testing.T) {
    result := someFunction()
    snapshotter := cupaloy.New(cupaloy.SnapshotSubdirectory("testdata"))
    err := snapshotter.Snapshot(result)
    if err != nil {
        t.Fatalf("error: %s", err)
    }
}

For further usage examples see basic_test.go and advanced_test.go in the examples/ directory which are both kept up to date and run on CI.

Documentation

Overview

Package cupaloy provides a simple api for snapshot testing in golang: test that your changes don't unexpectedly alter the results of your code.

cupaloy takes a snapshot of a given value and compares it to a snapshot committed alongside your tests. If the values don't match then you'll be forced to update the snapshot file before the test passes.

Snapshot files are handled automagically: just use the cupaloy.Snapshot(value) function in your tests and cupaloy will automatically find the relevant snapshot file and compare it with the given value.

Installation

go get -u github.com/bradleyjkemp/cupaloy

Usage

func TestExample(t *testing.T) {
  result := someFunction()

  // check that the result is the same as the last time the snapshot was updated
  // if the result has changed then the test will be failed with an error containing
  // a diff of the changes
  cupaloy.SnapshotT(t, result)
}

To update the snapshots simply set the UPDATE_SNAPSHOTS environment variable and run your tests e.g.

UPDATE_SNAPSHOTS=true go test ./...

Your snapshot files will now have been updated to reflect the current output of your code.

Index

Constants

This section is empty.

Variables

View Source
var Global = NewDefaultConfig()

Global is the Config instance used by `cupaloy.SnapshotT` and other package-level functions.

Functions

func Snapshot

func Snapshot(i ...interface{}) error

Snapshot calls Snapshotter.Snapshot with the global config.

func SnapshotMulti

func SnapshotMulti(snapshotID string, i ...interface{}) error

SnapshotMulti calls Snapshotter.SnapshotMulti with the global config.

func SnapshotT added in v1.1.0

func SnapshotT(t TestingT, i ...interface{})

SnapshotT calls Snapshotter.SnapshotT with the global config.

Types

type Config

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

Config provides the same snapshotting functions with additional configuration capabilities.

func New

func New(configurators ...Configurator) *Config

New constructs a new, configured instance of cupaloy using the given Configurators applied to the default config.

func NewDefaultConfig

func NewDefaultConfig() *Config

NewDefaultConfig returns a new Config instance initialised with the same options as the original Global instance (i.e. before any config changes were made to it)

func (*Config) Snapshot

func (c *Config) Snapshot(i ...interface{}) error

Snapshot compares the given value to the it's previous value stored on the filesystem. An error containing a diff is returned if the snapshots do not match. Snapshot determines the snapshot file automatically from the name of the calling function.

func (*Config) SnapshotMulti

func (c *Config) SnapshotMulti(snapshotID string, i ...interface{}) error

SnapshotMulti is identical to Snapshot but can be called multiple times from the same function. This is done by providing a unique snapshotId for each invocation.

func (*Config) SnapshotT

func (c *Config) SnapshotT(t TestingT, i ...interface{})

SnapshotT is identical to Snapshot but gets the snapshot name using t.Name() and calls t.Fail() directly if the snapshots do not match.

func (*Config) WithOptions

func (c *Config) WithOptions(configurators ...Configurator) *Config

WithOptions returns a copy of an existing Config with additional Configurators applied. This can be used to apply a different option for a single call e.g.

snapshotter.WithOptions(cupaloy.SnapshotSubdirectory("testdata")).SnapshotT(t, result)

Or to modify the Global Config e.g.

cupaloy.Global = cupaloy.Global.WithOptions(cupaloy.SnapshotSubdirectory("testdata"))

type Configurator

type Configurator func(*Config)

Configurator is a functional option that can be passed to cupaloy.New() to change snapshotting behaviour.

func CreateNewAutomatically

func CreateNewAutomatically(createNewAutomatically bool) Configurator

CreateNewAutomatically controls whether snapshots should be automatically created if no matching snapshot already exists. Default: true

func EnvVariableName

func EnvVariableName(name string) Configurator

EnvVariableName can be used to customize the environment variable that determines whether snapshots should be updated e.g.

cupaloy.New(EnvVariableName("UPDATE"))

Will create an instance where snapshots will be updated if the UPDATE environment variable is set. Default: UPDATE_SNAPSHOTS

func FailOnUpdate

func FailOnUpdate(failOnUpdate bool) Configurator

FailOnUpdate controls whether tests should be failed when snapshots are updated. By default this is true to prevent snapshots being accidentally updated in CI. Default: true

func FatalOnMismatch

func FatalOnMismatch(fatalOnMismatch bool) Configurator

FatalOnMismatch controls whether failed tests should fail using t.Fatal which should immediately stop any remaining tests. Will use t.Error on false. Default: false

func ShouldUpdate added in v1.3.0

func ShouldUpdate(f func() bool) Configurator

ShouldUpdate can be used to provide custom logic to decide whether or not to update a snapshot e.g.

var update = flag.Bool("update", false, "update snapshots")
cupaloy.New(ShouldUpdate(func () bool { return *update })

Will create an instance where snapshots are updated if the --update flag is passed to go test. Default: checks for the presence of the UPDATE_SNAPSHOTS environment variable

func SnapshotFileExtension

func SnapshotFileExtension(snapshotFileExtension string) Configurator

SnapshotFileExtension allows you to change the extension of the snapshot files that are written. E.g. if you're snapshotting HTML then adding SnapshotFileExtension(".html") will allow for more easier viewing of snapshots. Default: "", no extension is added.

func SnapshotSubdirectory

func SnapshotSubdirectory(name string) Configurator

SnapshotSubdirectory can be used to customize the location that snapshots are stored in. e.g.

cupaloy.New(SnapshotSubdirectory("testdata"))

Will create an instance where snapshots are stored in the "testdata" folder Default: .snapshots

type TestingT

type TestingT interface {
	Helper()
	Failed() bool
	Error(args ...interface{})
	Fatal(args ...interface{})
	Name() string
}

TestingT is a subset of the interface testing.TB allowing it to be mocked in tests.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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