assert

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2024 License: MIT Imports: 6 Imported by: 0

README

assert - Zero cost debug assertions.

PkgGoDev Go Report Card

This package provides zero cost debug assertions to your Go programs. It is based on the excellent github.com/stretchr/testify/assert package and provide the same API (minus t testing.T parameter).

Why ?

This is a complete rewrite of debuggo that aims to be up to date and more maintainable.

It aims to provide the same API as github.com/stretchr/testify/assert.

  • Prints friendly, easy to read failure descriptions
  • Allows for very readable code
  • Optionally annotate each assertion with a message
  • No performance impact on production build (see benchmarks)

Getting started

Here is our example program:

package main

import "github.com/negrel/assert"

func safeIndex(slice []string, index int) string {
	// Ensure index is not out of bounds.
	assert.GreaterOrEqual(index, 0, "negative index not allowed")
	assert.Lessf(index, len(slice), "index out of bounds (slice: %v)", slice)

	return slice[index]
}

func main() {
	days := []string{"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}
	println(safeIndex(days, 8))
}

A simple go run . will produce the following error:

panic: runtime error: index out of range [8] with length 7

goroutine 1 [running]:
main.safeIndex(...)
        /home/anegrel/code/go/assert/example/main.go:10
main.main()
        /home/anegrel/code/go/assert/example/main.go:15 +0xd6
exit status 2

Now, if you enable assertions with a compile time flags, go run -tags assert ., you will get something similar to:

panic:
        Error Trace:    /home/anegrel/code/go/assert/example/main.go:8
                                                /home/anegrel/code/go/assert/example/main.go:15
                                                /nix/store/dwmb0qcai52d0zkgpm6f5ifx2a8yvsdg-go-1.21.3/share/go/src/runtime/proc.go:267
                                                /nix/store/dwmb0qcai52d0zkgpm6f5ifx2a8yvsdg-go-1.21.3/share/go/src/runtime/asm_amd64.s:1650
        Error:          "8" is not less than "7"
        Messages:       index out of bounds (slice: [Monday Tuesday Wednesday Thursday Friday Saturday Sunday])


goroutine 1 [running]:
github.com/negrel/assert.Fail({0xc0001e2168, 0x18}, {0xc0001be240, 0x2, 0x2})
        /home/anegrel/code/go/assert/assertions.go:331 +0x168
github.com/negrel/assert.compareTwoValues({0x53eb00, 0x695cc0}, {0x53eb00, 0x695cb8}, {0xc0001f5e88, 0x1, 0x40e285?}, {0x57307c, 0x1a}, {0xc0001be240, ...})
        /home/anegrel/code/go/assert/assertion_compare.go:425 +0x2af
github.com/negrel/assert.Less(...)
        /home/anegrel/code/go/assert/assertion_compare.go:380
github.com/negrel/assert.Lessf(...)
        /home/anegrel/code/go/assert/assertion_format.go:355
main.safeIndex({0xc0001bdea0?, 0x7, 0x7}, 0x8)
        /home/anegrel/code/go/assert/example/main.go:8 +0x234
main.main()
        /home/anegrel/code/go/assert/example/main.go:15 +0xb4
exit status 2

That's the same output as testify/assert output except that we have a stacktrace because this is a panic.

Benchmarks

As we've seen previously, assertions are hidden behind a compilation flag. If the flag is absent, all assertions functions will be empty/noop function that the compiler will optimize.

WITH -tags assert:

goos: linux
goarch: amd64
pkg: github.com/negrel/assert/tests
cpu: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
BenchmarkSliceIndexWithoutBoundCheckAssertions
BenchmarkSliceIndexWithoutBoundCheckAssertions-8        728439501                1.407 ns/op
BenchmarkSliceIndexWithBoundCheckAssertions
BenchmarkSliceIndexWithBoundCheckAssertions-8           27423670                40.80 ns/op
PASS
ok      github.com/negrel/assert/tests  3.338s

WITHOUT -tags assert:

goos: linux
goarch: amd64
pkg: github.com/negrel/assert/tests
cpu: Intel(R) Core(TM) i5-8250U CPU @ 1.60GHz
BenchmarkSliceIndexWithoutBoundCheckAssertions
BenchmarkSliceIndexWithoutBoundCheckAssertions-8        772181695                1.399 ns/op
BenchmarkSliceIndexWithBoundCheckAssertions
BenchmarkSliceIndexWithBoundCheckAssertions-8           802181890                1.412 ns/op
PASS
ok      github.com/negrel/assert/tests  2.531s

However, keep in mind that assert slightly increase binary size (~1M). If you may know the reason please contact me.

Contributing

If you want to contribute to assert to add a feature or improve the code contact me at negrel.dev@protonmail.com, open an issue or make a pull request.

🌠 Show your support

Please give a ⭐ if this project helped you!

buy me a coffee

📜 License

MIT © Alexandre Negrel

Documentation

Overview

Package assert provides a set of comprehensive testing tools for use with the normal Go testing system.

Example Usage

The following is a complete example using assert in a standard test function:

import (
  "testing"
  "github.com/stretchr/testify/assert"
)

func TestSomething(t *testing.T) {

  var a string = "Hello"
  var b string = "Hello"

  assert.Equal(a, b, "The two words should be the same.")

}

if you assert many times, use the format below:

import (
  "testing"
  "github.com/stretchr/testify/assert"
)

func TestSomething(t *testing.T) {
  assert := assert.New(t)

  var a string = "Hello"
  var b string = "Hello"

  assert.Equal(a, b, "The two words should be the same.")
}

Assertions

Assertions allow you to easily write test code, and are global funcs in the `assert` package. All assertion functions take, as the first argument, the `*testing.T` object provided by the testing framework. This allows the assertion funcs to write the failings and other details to the correct place.

Every assertion function also takes an optional string message as the final argument, allowing custom error messages to be appended to the message the assertion method outputs.

Index

Constants

This section is empty.

Variables

View Source
var AnError = errors.New("assert.AnError general error for testing")

AnError is an error instance useful for testing. If the code does not care about error specifics, and only needs to return the error for example, this error should be used to make the test code more readable.

Functions

func CallerInfo

func CallerInfo()

CallerInfo returns an array of strings containing the file and line number of each stack frame leading from the current test to the assert call that failed.

func Condition

func Condition(comp Comparison, msgAndArgs ...interface{})

Condition uses a Comparison to assert a complex condition.

func Conditionf

func Conditionf(comp Comparison, msg string, args ...interface{})

Conditionf uses a Comparison to assert a complex condition.

func Contains

func Contains(s, contains interface{}, msgAndArgs ...interface{})

Contains asserts that the specified string, list(array, slice...) or map contains the specified substring or element.

assert.Contains("Hello World", "World")
assert.Contains(["Hello", "World"], "World")
assert.Contains({"Hello": "World"}, "Hello")

func Containsf

func Containsf(s interface{}, contains interface{}, msg string, args ...interface{})

Containsf asserts that the specified string, list(array, slice...) or map contains the specified substring or element.

assert.Containsf("Hello World", "World", "error message %s", "formatted")
assert.Containsf(["Hello", "World"], "World", "error message %s", "formatted")
assert.Containsf({"Hello": "World"}, "Hello", "error message %s", "formatted")

func DirExists

func DirExists(path string, msgAndArgs ...interface{})

DirExists checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists.

func DirExistsf

func DirExistsf(path string, msg string, args ...interface{})

DirExistsf checks whether a directory exists in the given path. It also fails if the path is a file rather a directory or there is an error checking whether it exists.

func ElementsMatch

func ElementsMatch(listA, listB interface{}, msgAndArgs ...interface{})

ElementsMatch asserts that the specified listA(array, slice...) is equal to specified listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, the number of appearances of each of them in both lists should match.

assert.ElementsMatch([1, 3, 2, 3], [1, 3, 3, 2])

func ElementsMatchf

func ElementsMatchf(listA interface{}, listB interface{}, msg string, args ...interface{})

ElementsMatchf asserts that the specified listA(array, slice...) is equal to specified listB(array, slice...) ignoring the order of the elements. If there are duplicate elements, the number of appearances of each of them in both lists should match.

assert.ElementsMatchf([1, 3, 2, 3], [1, 3, 3, 2], "error message %s", "formatted")

func Empty

func Empty(object interface{}, msgAndArgs ...interface{})

Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either a slice or a channel with len == 0.

assert.Empty(obj)

func Emptyf

func Emptyf(object interface{}, msg string, args ...interface{})

Emptyf asserts that the specified object is empty. I.e. nil, "", false, 0 or either a slice or a channel with len == 0.

assert.Emptyf(obj, "error message %s", "formatted")

func Equal

func Equal(expected, actual interface{}, msgAndArgs ...interface{})

Equal asserts that two objects are equal.

assert.Equal(123, 123)

Pointer variable equality is determined based on the equality of the referenced values (as opposed to the memory addresses). Function equality cannot be determined and will always fail.

func EqualError

func EqualError(theError error, errString string, msgAndArgs ...interface{})

EqualError asserts that a function returned an error (i.e. not `nil`) and that it is equal to the provided error.

actualObj, err := SomeFunction()
assert.EqualError(err,  expectedErrorString)

func EqualErrorf

func EqualErrorf(theError error, errString string, msg string, args ...interface{})

EqualErrorf asserts that a function returned an error (i.e. not `nil`) and that it is equal to the provided error.

actualObj, err := SomeFunction()
assert.EqualErrorf(err,  expectedErrorString, "error message %s", "formatted")

func EqualExportedValues

func EqualExportedValues(expected, actual interface{}, msgAndArgs ...interface{})

EqualExportedValues asserts that the types of two objects are equal and their public fields are also equal. This is useful for comparing structs that have private fields that could potentially differ.

 type S struct {
	Exported     	int
	notExported   	int
 }
 assert.EqualExportedValues(S{1, 2}, S{1, 3}) => true
 assert.EqualExportedValues(S{1, 2}, S{2, 3}) => false

func EqualExportedValuesf

func EqualExportedValuesf(expected interface{}, actual interface{}, msg string, args ...interface{})

EqualExportedValuesf asserts that the types of two objects are equal and their public fields are also equal. This is useful for comparing structs that have private fields that could potentially differ.

 type S struct {
	Exported     	int
	notExported   	int
 }
 assert.EqualExportedValuesf(S{1, 2}, S{1, 3}, "error message %s", "formatted") => true
 assert.EqualExportedValuesf(S{1, 2}, S{2, 3}, "error message %s", "formatted") => false

func EqualValues

func EqualValues(expected, actual interface{}, msgAndArgs ...interface{})

EqualValues asserts that two objects are equal or convertible to the same types and equal.

assert.EqualValues(uint32(123), int32(123))

func EqualValuesf

func EqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{})

EqualValuesf asserts that two objects are equal or convertible to the same types and equal.

assert.EqualValuesf(uint32(123), int32(123), "error message %s", "formatted")

func Equalf

func Equalf(expected interface{}, actual interface{}, msg string, args ...interface{})

Equalf asserts that two objects are equal.

assert.Equalf(123, 123, "error message %s", "formatted")

Pointer variable equality is determined based on the equality of the referenced values (as opposed to the memory addresses). Function equality cannot be determined and will always fail.

func Error

func Error(err error, msgAndArgs ...interface{})

Error asserts that a function returned an error (i.e. not `nil`).

  actualObj, err := SomeFunction()
  if assert.Error(err) {
	   assert.Equal(expectedError, err)
  }

func ErrorAs

func ErrorAs(err error, target interface{}, msgAndArgs ...interface{})

ErrorAs asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. This is a wrapper for errors.As.

func ErrorAsf

func ErrorAsf(err error, target interface{}, msg string, args ...interface{})

ErrorAsf asserts that at least one of the errors in err's chain matches target, and if so, sets target to that error value. This is a wrapper for errors.As.

func ErrorContains

func ErrorContains(theError error, contains string, msgAndArgs ...interface{})

ErrorContains asserts that a function returned an error (i.e. not `nil`) and that the error contains the specified substring.

actualObj, err := SomeFunction()
assert.ErrorContains(err,  expectedErrorSubString)

func ErrorContainsf

func ErrorContainsf(theError error, contains string, msg string, args ...interface{})

ErrorContainsf asserts that a function returned an error (i.e. not `nil`) and that the error contains the specified substring.

actualObj, err := SomeFunction()
assert.ErrorContainsf(err,  expectedErrorSubString, "error message %s", "formatted")

func ErrorIs

func ErrorIs(err, target error, msgAndArgs ...interface{})

ErrorIs asserts that at least one of the errors in err's chain matches target. This is a wrapper for errors.Is.

func ErrorIsf

func ErrorIsf(err error, target error, msg string, args ...interface{})

ErrorIsf asserts that at least one of the errors in err's chain matches target. This is a wrapper for errors.Is.

func Errorf

func Errorf(err error, msg string, args ...interface{})

Errorf asserts that a function returned an error (i.e. not `nil`).

  actualObj, err := SomeFunction()
  if assert.Errorf(err, "error message %s", "formatted") {
	   assert.Equal(expectedErrorf, err)
  }

func Eventually

func Eventually(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{})

Eventually asserts that given condition will be met in waitFor time, periodically checking target function each tick.

assert.Eventually(func() bool { return true; }, time.Second, 10*time.Millisecond)

func Eventuallyf

func Eventuallyf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{})

Eventuallyf asserts that given condition will be met in waitFor time, periodically checking target function each tick.

assert.Eventuallyf(func() bool { return true; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")

func Exactly

func Exactly(expected, actual interface{}, msgAndArgs ...interface{})

Exactly asserts that two objects are equal in value and type.

assert.Exactly(int32(123), int64(123))

func Exactlyf

func Exactlyf(expected interface{}, actual interface{}, msg string, args ...interface{})

Exactlyf asserts that two objects are equal in value and type.

assert.Exactlyf(int32(123), int64(123), "error message %s", "formatted")

func Fail

func Fail(failureMessage string, msgAndArgs ...interface{})

Fail reports a failure through

func FailNow

func FailNow(failureMessage string, msgAndArgs ...interface{})

FailNow fails test

func FailNowf

func FailNowf(failureMessage string, msg string, args ...interface{})

FailNowf fails test

func Failf

func Failf(failureMessage string, msg string, args ...interface{})

Failf reports a failure through

func False

func False(value bool, msgAndArgs ...interface{})

False asserts that the specified value is false.

assert.False(myBool)

func Falsef

func Falsef(value bool, msg string, args ...interface{})

Falsef asserts that the specified value is false.

assert.Falsef(myBool, "error message %s", "formatted")

func FileExists

func FileExists(path string, msgAndArgs ...interface{})

FileExists checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.

func FileExistsf

func FileExistsf(path string, msg string, args ...interface{})

FileExistsf checks whether a file exists in the given path. It also fails if the path points to a directory or there is an error when trying to check the file.

func Greater

func Greater(e1 interface{}, e2 interface{}, msgAndArgs ...interface{})

Greater asserts that the first element is greater than the second

assert.Greater(2, 1)
assert.Greater(float64(2), float64(1))
assert.Greater("b", "a")

func GreaterOrEqual

func GreaterOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{})

GreaterOrEqual asserts that the first element is greater than or equal to the second

assert.GreaterOrEqual(2, 1)
assert.GreaterOrEqual(2, 2)
assert.GreaterOrEqual("b", "a")
assert.GreaterOrEqual("b", "b")

func GreaterOrEqualf

func GreaterOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{})

GreaterOrEqualf asserts that the first element is greater than or equal to the second

assert.GreaterOrEqualf(2, 1, "error message %s", "formatted")
assert.GreaterOrEqualf(2, 2, "error message %s", "formatted")
assert.GreaterOrEqualf("b", "a", "error message %s", "formatted")
assert.GreaterOrEqualf("b", "b", "error message %s", "formatted")

func Greaterf

func Greaterf(e1 interface{}, e2 interface{}, msg string, args ...interface{})

Greaterf asserts that the first element is greater than the second

assert.Greaterf(2, 1, "error message %s", "formatted")
assert.Greaterf(float64(2), float64(1), "error message %s", "formatted")
assert.Greaterf("b", "a", "error message %s", "formatted")

func HTTPBody

func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values)

HTTPBody is a helper that returns HTTP body of the response. It returns empty string if building a new request fails.

func HTTPBodyContains

func HTTPBodyContains(handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{})

HTTPBodyContains asserts that a specified handler returns a body that contains a string.

assert.HTTPBodyContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")

Returns whether the assertion was successful (true) or not (false).

func HTTPBodyContainsf

func HTTPBodyContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{})

HTTPBodyContainsf asserts that a specified handler returns a body that contains a string.

assert.HTTPBodyContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")

Returns whether the assertion was successful (true) or not (false).

func HTTPBodyNotContains

func HTTPBodyNotContains(handler http.HandlerFunc, method, url string, values url.Values, str interface{}, msgAndArgs ...interface{})

HTTPBodyNotContains asserts that a specified handler returns a body that does not contain a string.

assert.HTTPBodyNotContains(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky")

Returns whether the assertion was successful (true) or not (false).

func HTTPBodyNotContainsf

func HTTPBodyNotContainsf(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}, msg string, args ...interface{})

HTTPBodyNotContainsf asserts that a specified handler returns a body that does not contain a string.

assert.HTTPBodyNotContainsf(myHandler, "GET", "www.google.com", nil, "I'm Feeling Lucky", "error message %s", "formatted")

Returns whether the assertion was successful (true) or not (false).

func HTTPError

func HTTPError(handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{})

HTTPError asserts that a specified handler returns an error status code.

assert.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}

Returns whether the assertion was successful (true) or not (false).

func HTTPErrorf

func HTTPErrorf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{})

HTTPErrorf asserts that a specified handler returns an error status code.

assert.HTTPErrorf(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}}

Returns whether the assertion was successful (true) or not (false).

func HTTPRedirect

func HTTPRedirect(handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{})

HTTPRedirect asserts that a specified handler returns a redirect status code.

assert.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}

Returns whether the assertion was successful (true) or not (false).

func HTTPRedirectf

func HTTPRedirectf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{})

HTTPRedirectf asserts that a specified handler returns a redirect status code.

assert.HTTPRedirectf(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}}

Returns whether the assertion was successful (true) or not (false).

func HTTPStatusCode

func HTTPStatusCode(handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msgAndArgs ...interface{})

HTTPStatusCode asserts that a specified handler returns a specified status code.

assert.HTTPStatusCode(myHandler, "GET", "/notImplemented", nil, 501)

Returns whether the assertion was successful (true) or not (false).

func HTTPStatusCodef

func HTTPStatusCodef(handler http.HandlerFunc, method string, url string, values url.Values, statuscode int, msg string, args ...interface{})

HTTPStatusCodef asserts that a specified handler returns a specified status code.

assert.HTTPStatusCodef(myHandler, "GET", "/notImplemented", nil, 501, "error message %s", "formatted")

Returns whether the assertion was successful (true) or not (false).

func HTTPSuccess

func HTTPSuccess(handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...interface{})

HTTPSuccess asserts that a specified handler returns a success status code.

assert.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil)

Returns whether the assertion was successful (true) or not (false).

func HTTPSuccessf

func HTTPSuccessf(handler http.HandlerFunc, method string, url string, values url.Values, msg string, args ...interface{})

HTTPSuccessf asserts that a specified handler returns a success status code.

assert.HTTPSuccessf(myHandler, "POST", "http://www.google.com", nil, "error message %s", "formatted")

Returns whether the assertion was successful (true) or not (false).

func Implements

func Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{})

Implements asserts that an object is implemented by the specified interface.

assert.Implements((*MyInterface)(nil), new(MyObject))

func Implementsf

func Implementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{})

Implementsf asserts that an object is implemented by the specified interface.

assert.Implementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted")

func InDelta

func InDelta(expected, actual interface{}, delta float64, msgAndArgs ...interface{})

InDelta asserts that the two numerals are within delta of each other.

assert.InDelta(math.Pi, 22/7.0, 0.01)

func InDeltaMapValues

func InDeltaMapValues(expected, actual interface{}, delta float64, msgAndArgs ...interface{})

InDeltaMapValues is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.

func InDeltaMapValuesf

func InDeltaMapValuesf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{})

InDeltaMapValuesf is the same as InDelta, but it compares all values between two maps. Both maps must have exactly the same keys.

func InDeltaSlice

func InDeltaSlice(expected, actual interface{}, delta float64, msgAndArgs ...interface{})

InDeltaSlice is the same as InDelta, except it compares two slices.

func InDeltaSlicef

func InDeltaSlicef(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{})

InDeltaSlicef is the same as InDelta, except it compares two slices.

func InDeltaf

func InDeltaf(expected interface{}, actual interface{}, delta float64, msg string, args ...interface{})

InDeltaf asserts that the two numerals are within delta of each other.

assert.InDeltaf(math.Pi, 22/7.0, 0.01, "error message %s", "formatted")

func InEpsilon

func InEpsilon(expected, actual interface{}, epsilon float64, msgAndArgs ...interface{})

InEpsilon asserts that expected and actual have a relative error less than epsilon

func InEpsilonSlice

func InEpsilonSlice(expected, actual interface{}, epsilon float64, msgAndArgs ...interface{})

InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices.

func InEpsilonSlicef

func InEpsilonSlicef(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{})

InEpsilonSlicef is the same as InEpsilon, except it compares each value from two slices.

func InEpsilonf

func InEpsilonf(expected interface{}, actual interface{}, epsilon float64, msg string, args ...interface{})

InEpsilonf asserts that expected and actual have a relative error less than epsilon

func IsDecreasing

func IsDecreasing(object interface{}, msgAndArgs ...interface{})

IsDecreasing asserts that the collection is decreasing

assert.IsDecreasing([]int{2, 1, 0})
assert.IsDecreasing([]float{2, 1})
assert.IsDecreasing([]string{"b", "a"})

func IsDecreasingf

func IsDecreasingf(object interface{}, msg string, args ...interface{})

IsDecreasingf asserts that the collection is decreasing

assert.IsDecreasingf([]int{2, 1, 0}, "error message %s", "formatted")
assert.IsDecreasingf([]float{2, 1}, "error message %s", "formatted")
assert.IsDecreasingf([]string{"b", "a"}, "error message %s", "formatted")

func IsIncreasing

func IsIncreasing(object interface{}, msgAndArgs ...interface{})

IsIncreasing asserts that the collection is increasing

assert.IsIncreasing([]int{1, 2, 3})
assert.IsIncreasing([]float{1, 2})
assert.IsIncreasing([]string{"a", "b"})

func IsIncreasingf

func IsIncreasingf(object interface{}, msg string, args ...interface{})

IsIncreasingf asserts that the collection is increasing

assert.IsIncreasingf([]int{1, 2, 3}, "error message %s", "formatted")
assert.IsIncreasingf([]float{1, 2}, "error message %s", "formatted")
assert.IsIncreasingf([]string{"a", "b"}, "error message %s", "formatted")

func IsNonDecreasing

func IsNonDecreasing(object interface{}, msgAndArgs ...interface{})

IsNonDecreasing asserts that the collection is not decreasing

assert.IsNonDecreasing([]int{1, 1, 2})
assert.IsNonDecreasing([]float{1, 2})
assert.IsNonDecreasing([]string{"a", "b"})

func IsNonDecreasingf

func IsNonDecreasingf(object interface{}, msg string, args ...interface{})

IsNonDecreasingf asserts that the collection is not decreasing

assert.IsNonDecreasingf([]int{1, 1, 2}, "error message %s", "formatted")
assert.IsNonDecreasingf([]float{1, 2}, "error message %s", "formatted")
assert.IsNonDecreasingf([]string{"a", "b"}, "error message %s", "formatted")

func IsNonIncreasing

func IsNonIncreasing(object interface{}, msgAndArgs ...interface{})

IsNonIncreasing asserts that the collection is not increasing

assert.IsNonIncreasing([]int{2, 1, 1})
assert.IsNonIncreasing([]float{2, 1})
assert.IsNonIncreasing([]string{"b", "a"})

func IsNonIncreasingf

func IsNonIncreasingf(object interface{}, msg string, args ...interface{})

IsNonIncreasingf asserts that the collection is not increasing

assert.IsNonIncreasingf([]int{2, 1, 1}, "error message %s", "formatted")
assert.IsNonIncreasingf([]float{2, 1}, "error message %s", "formatted")
assert.IsNonIncreasingf([]string{"b", "a"}, "error message %s", "formatted")

func IsType

func IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{})

IsType asserts that the specified objects are of the same type.

func IsTypef

func IsTypef(expectedType interface{}, object interface{}, msg string, args ...interface{})

IsTypef asserts that the specified objects are of the same type.

func JSONEq

func JSONEq(expected string, actual string, msgAndArgs ...interface{})

JSONEq asserts that two JSON strings are equivalent.

assert.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`)

func JSONEqf

func JSONEqf(expected string, actual string, msg string, args ...interface{})

JSONEqf asserts that two JSON strings are equivalent.

assert.JSONEqf(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`, "error message %s", "formatted")

func Len

func Len(object interface{}, length int, msgAndArgs ...interface{})

Len asserts that the specified object has specific length. Len also fails if the object has a type that len() not accept.

assert.Len(mySlice, 3)

func Lenf

func Lenf(object interface{}, length int, msg string, args ...interface{})

Lenf asserts that the specified object has specific length. Lenf also fails if the object has a type that len() not accept.

assert.Lenf(mySlice, 3, "error message %s", "formatted")

func Less

func Less(e1 interface{}, e2 interface{}, msgAndArgs ...interface{})

Less asserts that the first element is less than the second

assert.Less(1, 2)
assert.Less(float64(1), float64(2))
assert.Less("a", "b")

func LessOrEqual

func LessOrEqual(e1 interface{}, e2 interface{}, msgAndArgs ...interface{})

LessOrEqual asserts that the first element is less than or equal to the second

assert.LessOrEqual(1, 2)
assert.LessOrEqual(2, 2)
assert.LessOrEqual("a", "b")
assert.LessOrEqual("b", "b")

func LessOrEqualf

func LessOrEqualf(e1 interface{}, e2 interface{}, msg string, args ...interface{})

LessOrEqualf asserts that the first element is less than or equal to the second

assert.LessOrEqualf(1, 2, "error message %s", "formatted")
assert.LessOrEqualf(2, 2, "error message %s", "formatted")
assert.LessOrEqualf("a", "b", "error message %s", "formatted")
assert.LessOrEqualf("b", "b", "error message %s", "formatted")

func Lessf

func Lessf(e1 interface{}, e2 interface{}, msg string, args ...interface{})

Lessf asserts that the first element is less than the second

assert.Lessf(1, 2, "error message %s", "formatted")
assert.Lessf(float64(1), float64(2), "error message %s", "formatted")
assert.Lessf("a", "b", "error message %s", "formatted")

func Negative

func Negative(e interface{}, msgAndArgs ...interface{})

Negative asserts that the specified element is negative

assert.Negative(-1)
assert.Negative(-1.23)

func Negativef

func Negativef(e interface{}, msg string, args ...interface{})

Negativef asserts that the specified element is negative

assert.Negativef(-1, "error message %s", "formatted")
assert.Negativef(-1.23, "error message %s", "formatted")

func Never

func Never(condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...interface{})

Never asserts that the given condition doesn't satisfy in waitFor time, periodically checking the target function each tick.

assert.Never(func() bool { return false; }, time.Second, 10*time.Millisecond)

func Neverf

func Neverf(condition func() bool, waitFor time.Duration, tick time.Duration, msg string, args ...interface{})

Neverf asserts that the given condition doesn't satisfy in waitFor time, periodically checking the target function each tick.

assert.Neverf(func() bool { return false; }, time.Second, 10*time.Millisecond, "error message %s", "formatted")

func Nil

func Nil(object interface{}, msgAndArgs ...interface{})

Nil asserts that the specified object is nil.

assert.Nil(err)

func Nilf

func Nilf(object interface{}, msg string, args ...interface{})

Nilf asserts that the specified object is nil.

assert.Nilf(err, "error message %s", "formatted")

func NoDirExists

func NoDirExists(path string, msgAndArgs ...interface{})

NoDirExists checks whether a directory does not exist in the given path. It fails if the path points to an existing _directory_ only.

func NoDirExistsf

func NoDirExistsf(path string, msg string, args ...interface{})

NoDirExistsf checks whether a directory does not exist in the given path. It fails if the path points to an existing _directory_ only.

func NoError

func NoError(err error, msgAndArgs ...interface{})

NoError asserts that a function returned no error (i.e. `nil`).

  actualObj, err := SomeFunction()
  if assert.NoError(err) {
	   assert.Equal(expectedObj, actualObj)
  }

func NoErrorf

func NoErrorf(err error, msg string, args ...interface{})

NoErrorf asserts that a function returned no error (i.e. `nil`).

  actualObj, err := SomeFunction()
  if assert.NoErrorf(err, "error message %s", "formatted") {
	   assert.Equal(expectedObj, actualObj)
  }

func NoFileExists

func NoFileExists(path string, msgAndArgs ...interface{})

NoFileExists checks whether a file does not exist in a given path. It fails if the path points to an existing _file_ only.

func NoFileExistsf

func NoFileExistsf(path string, msg string, args ...interface{})

NoFileExistsf checks whether a file does not exist in a given path. It fails if the path points to an existing _file_ only.

func NotContains

func NotContains(s, contains interface{}, msgAndArgs ...interface{})

NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the specified substring or element.

assert.NotContains("Hello World", "Earth")
assert.NotContains(["Hello", "World"], "Earth")
assert.NotContains({"Hello": "World"}, "Earth")

func NotContainsf

func NotContainsf(s interface{}, contains interface{}, msg string, args ...interface{})

NotContainsf asserts that the specified string, list(array, slice...) or map does NOT contain the specified substring or element.

assert.NotContainsf("Hello World", "Earth", "error message %s", "formatted")
assert.NotContainsf(["Hello", "World"], "Earth", "error message %s", "formatted")
assert.NotContainsf({"Hello": "World"}, "Earth", "error message %s", "formatted")

func NotEmpty

func NotEmpty(object interface{}, msgAndArgs ...interface{})

NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either a slice or a channel with len == 0.

if assert.NotEmpty(obj) {
  assert.Equal("two", obj[1])
}

func NotEmptyf

func NotEmptyf(object interface{}, msg string, args ...interface{})

NotEmptyf asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either a slice or a channel with len == 0.

if assert.NotEmptyf(obj, "error message %s", "formatted") {
  assert.Equal("two", obj[1])
}

func NotEqual

func NotEqual(expected, actual interface{}, msgAndArgs ...interface{})

NotEqual asserts that the specified values are NOT equal.

assert.NotEqual(obj1, obj2)

Pointer variable equality is determined based on the equality of the referenced values (as opposed to the memory addresses).

func NotEqualValues

func NotEqualValues(expected, actual interface{}, msgAndArgs ...interface{})

NotEqualValues asserts that two objects are not equal even when converted to the same type

assert.NotEqualValues(obj1, obj2)

func NotEqualValuesf

func NotEqualValuesf(expected interface{}, actual interface{}, msg string, args ...interface{})

NotEqualValuesf asserts that two objects are not equal even when converted to the same type

assert.NotEqualValuesf(obj1, obj2, "error message %s", "formatted")

func NotEqualf

func NotEqualf(expected interface{}, actual interface{}, msg string, args ...interface{})

NotEqualf asserts that the specified values are NOT equal.

assert.NotEqualf(obj1, obj2, "error message %s", "formatted")

Pointer variable equality is determined based on the equality of the referenced values (as opposed to the memory addresses).

func NotErrorIs

func NotErrorIs(err, target error, msgAndArgs ...interface{})

NotErrorIs asserts that at none of the errors in err's chain matches target. This is a wrapper for errors.Is.

func NotErrorIsf

func NotErrorIsf(err error, target error, msg string, args ...interface{})

NotErrorIsf asserts that at none of the errors in err's chain matches target. This is a wrapper for errors.Is.

func NotImplements added in v0.2.0

func NotImplements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{})

NotImplements asserts that an object does not implement the specified interface.

assert.NotImplements((*MyInterface)(nil), new(MyObject))

func NotImplementsf added in v0.2.0

func NotImplementsf(interfaceObject interface{}, object interface{}, msg string, args ...interface{})

NotImplementsf asserts that an object does not implement the specified interface.

assert.NotImplementsf((*MyInterface)(nil), new(MyObject), "error message %s", "formatted")

func NotNil

func NotNil(object interface{}, msgAndArgs ...interface{})

NotNil asserts that the specified object is not nil.

assert.NotNil(err)

func NotNilf

func NotNilf(object interface{}, msg string, args ...interface{})

NotNilf asserts that the specified object is not nil.

assert.NotNilf(err, "error message %s", "formatted")

func NotPanics

func NotPanics(f PanicTestFunc, msgAndArgs ...interface{})

NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic.

assert.NotPanics(func(){ RemainCalm() })

func NotPanicsf

func NotPanicsf(f PanicTestFunc, msg string, args ...interface{})

NotPanicsf asserts that the code inside the specified PanicTestFunc does NOT panic.

assert.NotPanicsf(func(){ RemainCalm() }, "error message %s", "formatted")

func NotRegexp

func NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{})

NotRegexp asserts that a specified regexp does not match a string.

assert.NotRegexp(regexp.MustCompile("starts"), "it's starting")
assert.NotRegexp("^start", "it's not starting")

func NotRegexpf

func NotRegexpf(rx interface{}, str interface{}, msg string, args ...interface{})

NotRegexpf asserts that a specified regexp does not match a string.

assert.NotRegexpf(regexp.MustCompile("starts"), "it's starting", "error message %s", "formatted")
assert.NotRegexpf("^start", "it's not starting", "error message %s", "formatted")

func NotSame

func NotSame(expected, actual interface{}, msgAndArgs ...interface{})

NotSame asserts that two pointers do not reference the same object.

assert.NotSame(ptr1, ptr2)

Both arguments must be pointer variables. Pointer variable sameness is determined based on the equality of both type and value.

func NotSamef

func NotSamef(expected interface{}, actual interface{}, msg string, args ...interface{})

NotSamef asserts that two pointers do not reference the same object.

assert.NotSamef(ptr1, ptr2, "error message %s", "formatted")

Both arguments must be pointer variables. Pointer variable sameness is determined based on the equality of both type and value.

func NotSubset

func NotSubset(list, subset interface{}, msgAndArgs ...interface{})

NotSubset asserts that the specified list(array, slice...) or map does NOT contain all elements given in the specified subset list(array, slice...) or map.

assert.NotSubset([1, 3, 4], [1, 2])
assert.NotSubset({"x": 1, "y": 2}, {"z": 3})

func NotSubsetf

func NotSubsetf(list interface{}, subset interface{}, msg string, args ...interface{})

NotSubsetf asserts that the specified list(array, slice...) or map does NOT contain all elements given in the specified subset list(array, slice...) or map.

assert.NotSubsetf([1, 3, 4], [1, 2], "error message %s", "formatted")
assert.NotSubsetf({"x": 1, "y": 2}, {"z": 3}, "error message %s", "formatted")

func NotZero

func NotZero(i interface{}, msgAndArgs ...interface{})

NotZero asserts that i is not the zero value for its type.

func NotZerof

func NotZerof(i interface{}, msg string, args ...interface{})

NotZerof asserts that i is not the zero value for its type.

func ObjectsAreEqual

func ObjectsAreEqual(expected, actual interface{})

ObjectsAreEqual determines if two objects are considered equal.

This function does no assertion of any kind.

func ObjectsAreEqualValues

func ObjectsAreEqualValues(expected, actual interface{})

ObjectsAreEqualValues gets whether two objects are equal, or if their values are equal.

func ObjectsExportedFieldsAreEqual deprecated

func ObjectsExportedFieldsAreEqual(expected, actual interface{})

ObjectsExportedFieldsAreEqual determines if the exported (public) fields of two objects are considered equal. This comparison of only exported fields is applied recursively to nested data structures.

This function does no assertion of any kind.

Deprecated: Use EqualExportedValues instead.

func Panics

func Panics(f PanicTestFunc, msgAndArgs ...interface{})

Panics asserts that the code inside the specified PanicTestFunc panics.

assert.Panics(func(){ GoCrazy() })

func PanicsWithError

func PanicsWithError(errString string, f PanicTestFunc, msgAndArgs ...interface{})

PanicsWithError asserts that the code inside the specified PanicTestFunc panics, and that the recovered panic value is an error that satisfies the EqualError comparison.

assert.PanicsWithError("crazy error", func(){ GoCrazy() })

func PanicsWithErrorf

func PanicsWithErrorf(errString string, f PanicTestFunc, msg string, args ...interface{})

PanicsWithErrorf asserts that the code inside the specified PanicTestFunc panics, and that the recovered panic value is an error that satisfies the EqualError comparison.

assert.PanicsWithErrorf("crazy error", func(){ GoCrazy() }, "error message %s", "formatted")

func PanicsWithValue

func PanicsWithValue(expected interface{}, f PanicTestFunc, msgAndArgs ...interface{})

PanicsWithValue asserts that the code inside the specified PanicTestFunc panics, and that the recovered panic value equals the expected panic value.

assert.PanicsWithValue("crazy error", func(){ GoCrazy() })

func PanicsWithValuef

func PanicsWithValuef(expected interface{}, f PanicTestFunc, msg string, args ...interface{})

PanicsWithValuef asserts that the code inside the specified PanicTestFunc panics, and that the recovered panic value equals the expected panic value.

assert.PanicsWithValuef("crazy error", func(){ GoCrazy() }, "error message %s", "formatted")

func Panicsf

func Panicsf(f PanicTestFunc, msg string, args ...interface{})

Panicsf asserts that the code inside the specified PanicTestFunc panics.

assert.Panicsf(func(){ GoCrazy() }, "error message %s", "formatted")

func Positive

func Positive(e interface{}, msgAndArgs ...interface{})

Positive asserts that the specified element is positive

assert.Positive(1)
assert.Positive(1.23)

func Positivef

func Positivef(e interface{}, msg string, args ...interface{})

Positivef asserts that the specified element is positive

assert.Positivef(1, "error message %s", "formatted")
assert.Positivef(1.23, "error message %s", "formatted")

func Regexp

func Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{})

Regexp asserts that a specified regexp matches a string.

assert.Regexp(regexp.MustCompile("start"), "it's starting")
assert.Regexp("start...$", "it's not starting")

func Regexpf

func Regexpf(rx interface{}, str interface{}, msg string, args ...interface{})

Regexpf asserts that a specified regexp matches a string.

assert.Regexpf(regexp.MustCompile("start"), "it's starting", "error message %s", "formatted")
assert.Regexpf("start...$", "it's not starting", "error message %s", "formatted")

func Same

func Same(expected, actual interface{}, msgAndArgs ...interface{})

Same asserts that two pointers reference the same object.

assert.Same(ptr1, ptr2)

Both arguments must be pointer variables. Pointer variable sameness is determined based on the equality of both type and value.

func Samef

func Samef(expected interface{}, actual interface{}, msg string, args ...interface{})

Samef asserts that two pointers reference the same object.

assert.Samef(ptr1, ptr2, "error message %s", "formatted")

Both arguments must be pointer variables. Pointer variable sameness is determined based on the equality of both type and value.

func Subset

func Subset(list, subset interface{}, msgAndArgs ...interface{})

Subset asserts that the specified list(array, slice...) or map contains all elements given in the specified subset list(array, slice...) or map.

assert.Subset([1, 2, 3], [1, 2])
assert.Subset({"x": 1, "y": 2}, {"x": 1})

func Subsetf

func Subsetf(list interface{}, subset interface{}, msg string, args ...interface{})

Subsetf asserts that the specified list(array, slice...) or map contains all elements given in the specified subset list(array, slice...) or map.

assert.Subsetf([1, 2, 3], [1, 2], "error message %s", "formatted")
assert.Subsetf({"x": 1, "y": 2}, {"x": 1}, "error message %s", "formatted")

func True

func True(value bool, msgAndArgs ...interface{})

True asserts that the specified value is true.

assert.True(myBool)

func Truef

func Truef(value bool, msg string, args ...interface{})

Truef asserts that the specified value is true.

assert.Truef(myBool, "error message %s", "formatted")

func WithinDuration

func WithinDuration(expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{})

WithinDuration asserts that the two times are within duration delta of each other.

assert.WithinDuration(time.Now(), time.Now(), 10*time.Second)

func WithinDurationf

func WithinDurationf(expected time.Time, actual time.Time, delta time.Duration, msg string, args ...interface{})

WithinDurationf asserts that the two times are within duration delta of each other.

assert.WithinDurationf(time.Now(), time.Now(), 10*time.Second, "error message %s", "formatted")

func WithinRange

func WithinRange(actual, start, end time.Time, msgAndArgs ...interface{})

WithinRange asserts that a time is within a time range (inclusive).

assert.WithinRange(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))

func WithinRangef

func WithinRangef(actual time.Time, start time.Time, end time.Time, msg string, args ...interface{})

WithinRangef asserts that a time is within a time range (inclusive).

assert.WithinRangef(time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second), "error message %s", "formatted")

func YAMLEq

func YAMLEq(expected string, actual string, msgAndArgs ...interface{})

YAMLEq asserts that two YAML strings are equivalent.

func YAMLEqf

func YAMLEqf(expected string, actual string, msg string, args ...interface{})

YAMLEqf asserts that two YAML strings are equivalent.

func Zero

func Zero(i interface{}, msgAndArgs ...interface{})

Zero asserts that i is the zero value for its type.

func Zerof

func Zerof(i interface{}, msg string, args ...interface{})

Zerof asserts that i is the zero value for its type.

Types

type BoolAssertionFunc

type BoolAssertionFunc func(TestingT, bool, ...interface{}) bool

BoolAssertionFunc is a common function prototype when validating a bool value. Can be useful for table driven tests.

type CollectT

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

CollectT implements the TestingT interface and collects all errors.

func (*CollectT) Copy deprecated

func (*CollectT) Copy(TestingT)

Deprecated: That was a method for internal usage that should not have been published. Now just panics.

func (*CollectT) Errorf

func (c *CollectT) Errorf(format string, args ...interface{})

Errorf collects the error.

func (*CollectT) FailNow

func (*CollectT) FailNow()

FailNow panics.

func (*CollectT) Reset deprecated

func (*CollectT) Reset()

Deprecated: That was a method for internal usage that should not have been published. Now just panics.

type CompareType

type CompareType int

type Comparison

type Comparison func() (success bool)

Comparison is a custom function that returns true on success and false on failure

type ComparisonAssertionFunc

type ComparisonAssertionFunc func(TestingT, interface{}, interface{}, ...interface{}) bool

ComparisonAssertionFunc is a common function prototype when comparing two values. Can be useful for table driven tests.

type ErrorAssertionFunc

type ErrorAssertionFunc func(TestingT, error, ...interface{}) bool

ErrorAssertionFunc is a common function prototype when validating an error value. Can be useful for table driven tests.

type PanicTestFunc

type PanicTestFunc func()

PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics methods, and represents a simple func that takes no arguments, and returns nothing.

type TestingT

type TestingT interface {
	Errorf(format string, args ...interface{})
}

TestingT is an interface wrapper around *testing.T

type ValueAssertionFunc

type ValueAssertionFunc func(TestingT, interface{}, ...interface{}) bool

ValueAssertionFunc is a common function prototype when validating a single value. Can be useful for table driven tests.

Jump to

Keyboard shortcuts

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