assert

package module
v0.0.0-...-3b23232 Latest Latest
Warning

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

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

README

go-assert Build Status Go Report Card

Simple and no intrusive Go test library.

Documentation.

Getting started

Install the library (required Go 1.10 or superior):

go get -u github.com/gribouille/go-assert
dep ensure -add github.com/gribouille/go-assert

Create a test file:

package module_test

import (
  "testing"

  T "github.com/gribouille/go-assert"
)

func TestFunc(t *testing.T) {
  a := T.New(t)
  // ready...
}

Chain the assertions:

a.
  Equal(3, 3, "Equal success").
  Equal("not", "equal", "Equal failed").
  Equal("a", "b").
  True(true, "True success").
  True(2 == 3, "True failed").
  False(2 == 3, "False success").
  False(4 == 4, "False failed").
  NotEqual(2, 3, "NotEqual success").
  NotEqual("a", "a", "NotEqual failed")

Use the BDD style:

T.New(t).
  It("sub test 1", func(a *T.Assert) {
    // ...
  }).
  It("sub test 2", func(a *T.Assert) {
    // ...
  })

Add custom messages if the assertion failed:

a.
  Equal("a", "b"). // no message
  Equal("a", "b", "a is different of b").
  Equal("a", "b", "%s is different of %s", "a", "b")

Many utils comparison functions:

// Classic assertion
a.Equal(...)
a.True(...).
a.False(...)
a.NotEqual(...)
a.EqualDeep(...)
a.NotEqualDeep(...)
a.EqualSlice(...)
a.EqualStringSlice(...)
a.Nil(...)
a.NotNil(...)
a.Error(err, "open %s: no such file or directory", file)

// Advanced matching
a.Match(`^[a-z]+\[[0-9]+\]$`, "adam[23]")
a.EqualFile(got, "testdata/lorem.txt")

data := struct {
  Version string
  Authors []string
}{
  Version: "2.0",
  Authors: []string{"Bob Leponge", "Mr. Krabs"},
}
a.EqualTemplate(got, "testdata/version.tpl", data)

// Filesystem
a.IsFile("/etc/passwd")
a.IsDir("/usr/bin/")
a.NotExists("/file/not/exist")

Create temporary testing environments to execute your tests:

T.New(t).
  ItEnv("Sub test 1 with temp dir",
    T.Copy{"testdata/a", "a"},
    T.Copy{"testdata/version.tpl", "version.tpl"},
    T.Copy{"testdata/ipsum.txt", "a/ipsum.txt"},
  )(func(a *T.Assert, dir string) {
  // here you have a temporary directory with the test data copied inside
  // this directory will be deleted at the end of this function
})

Test crashable function:

T.New(t).Crash("Sub test crash", func() {
  // function that uses os.Exit(...)
}, func(a *T.Assert, code int, stdout, stderr string) {
  // here your test
})

Capture the standard output and error:

T.New(t).Capture("Sub test capture", func() {
  // function that prints messages on stdout and stderr
}, func(a *T.Assert, stdout, stderr string) {
  // here your test
})

Customize the behavior with environment variables or with custom constructor:

// fatal = true: use t.Fatal for the error
// stack = true: show the stack trace
a := T.NewCustom(t, true, true)

See more details in the examples and in the documentation.

Tests

To execute the tests:

go test -v .

TODO

  • Improve the documentation
  • Add net functions

References

License

This project is licensed under Mozilla Public License Version 2.0.

Documentation

Overview

Package assert provides a simple and no intrusive Go test library.

Installation

Use go get tool:

go get -u github.com/gribouille/go-assert

Or dep tool:

dep ensure -add github.com/gribouille/go-assert

Behavior

All errors that are not assertions are panic, for example:

a.EqualTemplate(got, filename, data)

will cause a panic if the filename does not exist or if the data does not match with the template.

You could customize the behavior of the library with the environment variables:

  • GO_ASSERT_STACK: show the stacktrace if the test fails
  • GO_ASSERT_FATAL: uses fatal errors
  • GO_ASSERT_TMP_DISABLE: disable the deletion of temporary directory with ItTmp and ItEnv
  • GO_ASSERT_OS: test for a specific OS (the possible values are similar to runtime.GOOS)

or with the NewCustom constructor.

a := T.NewCustom(t, true, false)

Examples

See the examples/*.go for more examples.

func TestXXX(t *testing.T) {
	T.New(t).
		It("sub test 1", func(a *T.Assert) {
			a.Equal(...)
			// ...
		}).
		It("sub test 2", func(a *T.Assert) {
			// ...
		})
}

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cp

func Cp(src, dest string) error

Cp copies src to dest, doesn't matter if src is a directory or a file

Types

type Assert

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

Assert wraps the standard testing.T structure.

func New

func New(t *testing.T) *Assert

New creates a new Assert object.

Uses the environments variables to customize the behavior:

  • GO_ASSERT_STACK: show the stacktrace if the test fails
  • GO_ASSERT_FATAL: uses fatal errors
  • GO_ASSERT_OS: test for a specific OS (the possible values are similar to runtime.GOOS)

func NewCustom

func NewCustom(t *testing.T, fatal, stack bool) *Assert

NewCustom is similar to New but not uses the environment variables.

If stack is true then the stacktrace is showed; if fatal is true then uses the fatal errors.

func (*Assert) Capture

func (a *Assert) Capture(msg string, act func(), fn func(*Assert, string, string)) *Assert

Capture the messages sends to the standard output and the standard error of the function.

Example:

T.New(t).Capture("Sub test capture", func() {
	fmt.Fprintf(os.Stdout, "Hello")
	fmt.Fprintf(os.Stderr, "World")
}, func(a *T.Assert, stdout, stderr string) {
	a.Equal("Hello", stdout).Equal("World", stderr)
})

func (*Assert) Crash

func (a *Assert) Crash(msg string, act func(), fn func(*Assert, int, string, string)) *Assert

Crash is similar to Capture but the function should exit the program too. The assertion captures the return code too.

func (*Assert) Equal

func (a *Assert) Equal(exp, got interface{}, msg ...interface{}) *Assert

Equal assertion.

The assertion function can add an optional custom error message:

a.Equal("a", "b"). // no message
a.Equal("a", "b", "a is different of b").
a.Equal("a", "b", "%s is different of %s", "a", "b")

The assertion function can be chained:

a.Nil(...).Equal(...).True(...)

func (*Assert) EqualDeep

func (a *Assert) EqualDeep(exp, got interface{}, msg ...interface{}) *Assert

EqualDeep is similar to Equal but uses reflect.DeepEqual to test the equality.

func (*Assert) EqualFAbs

func (a *Assert) EqualFAbs(exp, got, epsilon float64, msg ...interface{}) *Assert

EqualFAbs compares 2 floats numbers with an absolute tolerance.

func (*Assert) EqualFRel

func (a *Assert) EqualFRel(exp, got, epsilon float64, msg ...interface{}) *Assert

EqualFRel compares 2 floats numbers with an relative tolerance.

func (*Assert) EqualFile

func (a *Assert) EqualFile(got string, filename string, msg ...interface{}) *Assert

EqualFile tests the equality between the content of file and the got string.

func (*Assert) EqualSlice

func (a *Assert) EqualSlice(exp, got []interface{}, msg ...interface{}) *Assert

EqualSlice compares two slices of interface{}.

func (*Assert) EqualStringSlice

func (a *Assert) EqualStringSlice(exp, got []string, msg ...interface{}) *Assert

EqualStringSlice compares tow slices of strings.

If the assertion fails then a message shows the first differences:

Error:
  Exp: [aaa bbb ccc ddd]
  Got: [aaa bbc ccc ddd]
   ┗━━━━━━━━━┛

func (*Assert) EqualTemplate

func (a *Assert) EqualTemplate(got string, filename string, data interface{}, msg ...interface{}) *Assert

EqualTemplate is similar to EqualFile but the file can be a template. The spaces are trimed. Example:

data := struct {
	Version string
	Authors []string
}{
	Version: "2.0",
	Authors: []string{"Bob Leponge", "Mr. Krabs"},
}
a.EqualTemplate(got, "testdata/version.tpl", data)

func (*Assert) Error

func (a *Assert) Error(err error, errFormat string, errA ...interface{}) *Assert

Error message assertion.

Example:

file := "/file/not/exist"
_, err := ioutil.ReadFile(file)
a.Error(err, "open %s: no such file or directory", file)

func (*Assert) False

func (a *Assert) False(v bool, msg ...interface{}) *Assert

False assertion.

func (*Assert) IsDir

func (a *Assert) IsDir(pth string, msg ...interface{}) *Assert

IsDir tests if the directory exists.

func (*Assert) IsFile

func (a *Assert) IsFile(pth string, msg ...interface{}) *Assert

IsFile tests if the file exists.

func (*Assert) It

func (a *Assert) It(msg string, fn func(*Assert)) *Assert

It defines a new subtest.

func (*Assert) ItEnv

func (a *Assert) ItEnv(msg string, copies ...Copy) func(func(*Assert, string)) *Assert

ItEnv is similar to ItTmp but it copies the files or the folders in the temporary directory.

Example:

T.New(t).ItEnv("Sub test 1 with temp dir",
	T.Copy{"testdata/a", "a"},
	T.Copy{"testdata/version.tpl", "version.tpl"},
	T.Copy{"testdata/ipsum.txt", "a/ipsum.txt"},
)(func(a *T.Assert, dir string) {
// ...
})

func (*Assert) ItTmp

func (a *Assert) ItTmp(msg string, fn func(*Assert, string)) *Assert

ItTmp creates a sub test with a temporary directory. This directory is clean up after the test.

For debugging, the deletion of temporary folder can be disable with the environment variable GO_ASSERT_TMP_DISABLE=1.

Example:

a.ItTmp("Sub test 1 with temp dir", func(a *T.Assert, dir string) {
	// dir is the temporary directory
})

func (*Assert) Match

func (a *Assert) Match(pattern, s string, msg ...interface{}) *Assert

Match a string to a regex expression.

Example:

a.Match(`^[a-z]+\[[0-9]+\]$`, "adam[23]")

func (*Assert) Nil

func (a *Assert) Nil(v interface{}, msg ...interface{}) *Assert

Nil assertion.

func (*Assert) NotEqual

func (a *Assert) NotEqual(exp, got interface{}, msg ...interface{}) *Assert

NotEqual assertion.

func (*Assert) NotEqualDeep

func (a *Assert) NotEqualDeep(exp, got interface{}, msg ...interface{}) *Assert

NotEqualDeep is the inverse of EqualDeep.

func (*Assert) NotExists

func (a *Assert) NotExists(pth string, msg ...interface{}) *Assert

NotExists tests if the path does not exist.

func (*Assert) NotNil

func (a *Assert) NotNil(v interface{}, msg ...interface{}) *Assert

NotNil assertion.

func (*Assert) SetFatal

func (a *Assert) SetFatal(v bool) *Assert

SetFatal sets to true if the assert must use the Fatal method.

func (*Assert) SetOS

func (a *Assert) SetOS(v string) *Assert

SetOS specifies if the test is operating system dependant.

The possible values are similar to the values of runtime.GOOS.

func (*Assert) SetStack

func (a *Assert) SetStack(v bool) *Assert

SetStack sets to true if the stacktrace must be showed after an error.

func (*Assert) Skip

func (a *Assert) Skip(args ...interface{}) *Assert

Skip the test.

func (*Assert) True

func (a *Assert) True(v bool, msg ...interface{}) *Assert

True assertion.

type Copy

type Copy struct {
	Source, Dest string
}

Copy is a file or a directory copied in the temporary directory.

Jump to

Keyboard shortcuts

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