FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

assert package - github.com/pierrre/assert - Go Packages

  1. Discover Packages
  2. github.com/pierrre/assert

assert

package module
v0.15.7 Latest Latest

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

Go to latest
Published: Aug 22, 2026 License: MIT Imports: 20 Imported by: 1
Main Versions Licenses Imports Imported By

Details

Repository

Links

README

README

Assert

Go test assertion library.

Features

Assertions

A simple assertion:

assert.Equal(t, value, 1)

By default, assertions fail with Fatal(). It can be changed with the Report() option:

assert.Equal(t, value, 1, assert.ReportError())

The report message can be customized:

assert.Equal(t, value, 1, assert.MessageWrap("test"))

Why?

This assertion library is an experiment to see if it is possible to do better than github.com/stretchr/testify, by using generics.

Here is an example of an issue with github.com/stretchr/testify:

func Test(t *testing.T) {
    value := getValue()
    require.Equal(t, 1, value)
}

func getValue() int64 {
    return 1
}

Surprisingly, this test fails with this error:

Error: Not equal:
expected: int(1)
actual  : int64(1)

This issue is caused by the types, which are not identical (the 1 constant is an int and not an int64), and it's possible to fix it:

Convert the value to int64:

require.Equal(t, int64(1), value)

Use EqualValues() which converts the values to the same type:

require.EqualValues(t, 1, value)

But the internal implementation is not simple: it requires heavy usage of reflection, and the code is quite complex.

What if we could simply use the == operator? This is the solution chosen by this library. It uses generics to do the comparison, and it works with any comparable type:

func Equal[T comparable](tb testing.TB, v1, v2 T, opts ...Option) bool {
    tb.Helper()
    ok := v1 == v2
    if !ok {
        Fail(...)
    }
    return ok
}
assert.Equal(t, 1, value)

The constant 1 is automatically converted to the type of the value variable without using reflection.

However, this approach has a limitation: it requires writing a different assertion function for each "kind" (map, slice, etc...).

Customization

The default behavior can be customized:

Auto-updating assertions

The assertauto sub-package provides assertions that automatically update their expected values. It compares actual values against expected values stored in files, and is useful for snapshot testing.

Unlike assert.Equal(), the expected value is not passed to the function but stored in a file:

assertauto.Equal(t, value)

To generate or update the expected values, run the tests with the environment variable ASSERTAUTO_UPDATE=true:

ASSERTAUTO_UPDATE=true go test ./...

The expected values are stored in the _assertauto directory, relative to the tested package. Each test creates a file named after the test, with the .txt extension. Values from the same test are stored sequentially in the same file. The storage directory can be changed with the environment variable ASSERTAUTO_DIRECTORY.

It also provides AllocsPerRun() to assert the number of allocations of a function.

The value stringer and the assert options can be customized with ValueStringer() and AssertOptions().

FAQ

Why not use github.com/stretchr/testify?

I think it's a great library, but I wanted to try something different. I also wanted to try generics, and to see if it was possible to make an assertion library without reflection.

Where are Nil() and NotNil()?

Documentation

Overview

Package assert provides utilities to assert conditions in tests.

Assertion functions return a boolean value indicating whether the assertion succeeded.

By default, assertion failures are reported using testing.TB.Fatal. This can be customized with the Report() option.

Index

Constants

This section is empty.

Variables

View Source
var DeepEqualer atomicutil.Value[func(v1, v2 any) (string, bool)]

DeepEqualer is a function that checks if two values are deeply equal.

By default, it uses compare.DefaultComparator.

View Source
var DefaultReport atomicutil.Value[ReportFunc]

DefaultReport is the default ReportFunc used for assertion failures. See the Report option.

By default it uses testing.TB.Fatal.

View Source
var DefaultShowStack atomic.Bool

DefaultShowStack is the default value used to show stack traces on assertion failures. See the ShowStack option.

By default it is true.

View Source
var ValueStringer atomicutil.Value[func(any) string]

ValueStringer is a function that returns the string representation of a value.

By default, it uses pretty.String.

Functions

func AllocsPerRun added in v0.1.2

func AllocsPerRun(tb testing.TB, runs int, f func(), allocs float64, opts ...Option) bool

AllocsPerRun asserts that a function allocates a certain number of times per run.

If the race detector is enabled, this function does nothing and returns true. This prevents tests from failing due to the increased number of allocations.

func BytesContains added in v0.6.1

func BytesContains(tb testing.TB, b, subslice []byte, opts ...Option) bool

BytesContains asserts that b contains subslice. It uses bytes.Contains to check if subslice is contained in b.

func BytesEqual

func BytesEqual(tb testing.TB, b1, b2 []byte, opts ...Option) bool

BytesEqual asserts that b1 and b2 are equal. It uses bytes.Equal to compare the two byte slices.

func BytesEqualFold added in v0.15.0

func BytesEqualFold(tb testing.TB, b1, b2 []byte, opts ...Option) bool

BytesEqualFold asserts that b1 and b2 are equal, ignoring case. It uses bytes.EqualFold to compare the two byte slices.

func BytesHasPrefix added in v0.12.1

func BytesHasPrefix(tb testing.TB, b, prefix []byte, opts ...Option) bool

BytesHasPrefix asserts that b begins with prefix. It uses bytes.HasPrefix to check if b begins with prefix.

func BytesHasSuffix added in v0.12.1

func BytesHasSuffix(tb testing.TB, b, suffix []byte, opts ...Option) bool

BytesHasSuffix asserts that b ends with suffix. It uses bytes.HasSuffix to check if b ends with suffix.

func BytesNotContains added in v0.6.1

func BytesNotContains(tb testing.TB, b, subslice []byte, opts ...Option) bool

BytesNotContains asserts that b does not contain subslice. It uses bytes.Contains to check if subslice is contained in b.

func BytesNotEqual

func BytesNotEqual(tb testing.TB, b1, b2 []byte, opts ...Option) bool

BytesNotEqual asserts that b1 and b2 are not equal. It uses bytes.Equal to compare the two byte slices.

func BytesNotEqualFold added in v0.15.0

func BytesNotEqualFold(tb testing.TB, b1, b2 []byte, opts ...Option) bool

BytesNotEqualFold asserts that b1 and b2 are not equal, ignoring case. It uses bytes.EqualFold to compare the two byte slices.

func BytesNotHasPrefix added in v0.12.1

func BytesNotHasPrefix(tb testing.TB, b, prefix []byte, opts ...Option) bool

BytesNotHasPrefix asserts that b does not begin with prefix. It uses bytes.HasPrefix to check if b begins with prefix.

func BytesNotHasSuffix added in v0.12.1

func BytesNotHasSuffix(tb testing.TB, b, suffix []byte, opts ...Option) bool

BytesNotHasSuffix asserts that b does not end with suffix. It uses bytes.HasSuffix to check if b ends with suffix.

func ChanEmpty

func ChanEmpty[T any](tb testing.TB, c chan T, opts ...Option) bool

ChanEmpty asserts that c is empty.

func ChanLen

func ChanLen[T any](tb testing.TB, c chan T, l int, opts ...Option) bool

ChanLen asserts that c has length l.

func ChanNil

func ChanNil[T any](tb testing.TB, c chan T, opts ...Option) bool

ChanNil asserts that c is nil.

func ChanNotEmpty

func ChanNotEmpty[T any](tb testing.TB, c chan T, opts ...Option) bool

ChanNotEmpty asserts that c is not empty.

func ChanNotNil

func ChanNotNil[T any](tb testing.TB, c chan T, opts ...Option) bool

ChanNotNil asserts that c is not nil.

func ChanRecvEmpty added in v0.15.4

func ChanRecvEmpty[T any](tb testing.TB, c <-chan T, opts ...Option) bool

ChanRecvEmpty asserts that c is empty.

func ChanRecvLen added in v0.15.4

func ChanRecvLen[T any](tb testing.TB, c <-chan T, l int, opts ...Option) bool

ChanRecvLen asserts that c has length l.

func ChanRecvNil added in v0.15.4

func ChanRecvNil[T any](tb testing.TB, c <-chan T, opts ...Option) bool

ChanRecvNil asserts that c is nil.

func ChanRecvNotEmpty added in v0.15.4

func ChanRecvNotEmpty[T any](tb testing.TB, c <-chan T, opts ...Option) bool

ChanRecvNotEmpty asserts that c is not empty.

func ChanRecvNotNil added in v0.15.4

func ChanRecvNotNil[T any](tb testing.TB, c <-chan T, opts ...Option) bool

ChanRecvNotNil asserts that c is not nil.

func ChanSendEmpty added in v0.15.4

func ChanSendEmpty[T any](tb testing.TB, c chan<- T, opts ...Option) bool

ChanSendEmpty asserts that c is empty.

func ChanSendLen added in v0.15.4

func ChanSendLen[T any](tb testing.TB, c chan<- T, l int, opts ...Option) bool

ChanSendLen asserts that c has length l.

func ChanSendNil added in v0.15.4

func ChanSendNil[T any](tb testing.TB, c chan<- T, opts ...Option) bool

ChanSendNil asserts that c is nil.

func ChanSendNotEmpty added in v0.15.4

func ChanSendNotEmpty[T any](tb testing.TB, c chan<- T, opts ...Option) bool

ChanSendNotEmpty asserts that c is not empty.

func ChanSendNotNil added in v0.15.4

func ChanSendNotNil[T any](tb testing.TB, c chan<- T, opts ...Option) bool

ChanSendNotNil asserts that c is not nil.

func Condition

func Condition(tb testing.TB, f func() bool, opts ...Option) bool

Condition asserts that f returns true.

func DeepEqual

func DeepEqual[T any](tb testing.TB, v1, v2 T, opts ...Option) bool

DeepEqual asserts that v1 and v2 are deeply equal according to DeepEqualer.

func Equal

func Equal[T comparable](tb testing.TB, v1, v2 T, opts ...Option) bool

Equal asserts that v1 == v2.

For floating-point values, note that NaN != NaN, so Equal will always fail when comparing NaN to itself. Use FloatNaN or FloatNotNaN instead.

func Error

func Error(tb testing.TB, err error, opts ...Option) bool

Error asserts that err is not nil.

func ErrorAs

func ErrorAs(tb testing.TB, err error, target any, opts ...Option) bool

ErrorAs asserts that errors.As returns true.

target must be a non-nil pointer to a type that implements error, or to any interface type.

func ErrorAsType added in v0.13.0

func ErrorAsType[E error](tb testing.TB, err error, opts ...Option) (E, bool)

ErrorAsType asserts that errors.AsType returns true and returns the error of type E.

func ErrorContains

func ErrorContains(tb testing.TB, err error, substr string, opts ...Option) bool

ErrorContains asserts that the result of [error.Error] contains substr.

func ErrorEqual

func ErrorEqual(tb testing.TB, err error, message string, opts ...Option) bool

ErrorEqual asserts that the result of [error.Error] is equal to message.

func ErrorIs

func ErrorIs(tb testing.TB, err, target error, opts ...Option) bool

ErrorIs asserts that errors.Is returns true.

func ErrorNotIs

func ErrorNotIs(tb testing.TB, err, target error, opts ...Option) bool

ErrorNotIs asserts that errors.Is returns false.

func Fail

func Fail(tb testing.TB, name string, msg string, stackSkip int, opts ...Option)

Fail handles assertion failure. It calls the ReportFunc with the given message.

func False

func False(tb testing.TB, v bool, opts ...Option) bool

False asserts that v == false.

func FloatInf added in v0.14.0

func FloatInf[T Float](tb testing.TB, f T, sign int, opts ...Option) bool

FloatInf asserts that f is an infinity according to sign. If sign > 0, asserts that f is positive infinity. If sign < 0, asserts that f is negative infinity. If sign == 0, asserts that f is either positive or negative infinity.

func FloatNaN added in v0.14.0

func FloatNaN[T Float](tb testing.TB, f T, opts ...Option) bool

FloatNaN asserts that f is NaN (not-a-number).

func FloatNotInf added in v0.14.0

func FloatNotInf[T Float](tb testing.TB, f T, sign int, opts ...Option) bool

FloatNotInf asserts that f is not an infinity according to sign. If sign > 0, asserts that f is not positive infinity. If sign < 0, asserts that f is not negative infinity. If sign == 0, asserts that f is not any infinity (finite value).

func FloatNotNaN added in v0.14.0

func FloatNotNaN[T Float](tb testing.TB, f T, opts ...Option) bool

FloatNotNaN asserts that f is not NaN (not-a-number).

func Greater

func Greater[T cmp.Ordered](tb testing.TB, v1, v2 T, opts ...Option) bool

Greater asserts that v1 > v2.

func GreaterOrEqual

func GreaterOrEqual[T cmp.Ordered](tb testing.TB, v1, v2 T, opts ...Option) bool

GreaterOrEqual asserts that v1 >= v2.

func Less

func Less[T cmp.Ordered](tb testing.TB, v1, v2 T, opts ...Option) bool

Less asserts that v1 < v2.

func LessOrEqual

func LessOrEqual[T cmp.Ordered](tb testing.TB, v1, v2 T, opts ...Option) bool

LessOrEqual asserts that v1 <= v2.

func MapEmpty

func MapEmpty[M ~map[K]V, K comparable, V any](tb testing.TB, m M, opts ...Option) bool

MapEmpty asserts that m is empty.

func MapEqual

func MapEqual[M1, M2 ~map[K]V, K, V comparable](tb testing.TB, m1 M1, m2 M2, opts ...Option) bool

MapEqual asserts that m1 and m2 are equal.

func MapLen

func MapLen[M ~map[K]V, K comparable, V any](tb testing.TB, m M, l int, opts ...Option) bool

MapLen asserts that m has length l.

func MapNil

func MapNil[M ~map[K]V, K comparable, V any](tb testing.TB, m M, opts ...Option) bool

MapNil asserts that m is nil.

func MapNotEmpty

func MapNotEmpty[M ~map[K]V, K comparable, V any](tb testing.TB, m M, opts ...Option) bool

MapNotEmpty asserts that m is not empty.

func MapNotEqual

func MapNotEqual[M1, M2 ~map[K]V, K, V comparable](tb testing.TB, m1 M1, m2 M2, opts ...Option) bool

MapNotEqual asserts that m1 and m2 are not equal.

func MapNotNil

func MapNotNil[M ~map[K]V, K comparable, V any](tb testing.TB, m M, opts ...Option) bool

MapNotNil asserts that m is not nil.

func Negative

func Negative[T SignedNumber](tb testing.TB, v T, opts ...Option) bool

Negative asserts that the value is negative.

func NewDeepEqualerWithComparator added in v0.6.0

func NewDeepEqualerWithComparator(cr *compare.Comparator) func(v1, v2 any) (string, bool)

NewDeepEqualerWithComparator creates a new DeepEqualer with a custom compare.Comparator.

func NoError

func NoError(tb testing.TB, err error, opts ...Option) bool

NoError asserts that err is nil.

func NotDeepEqual

func NotDeepEqual[T any](tb testing.TB, v1, v2 T, opts ...Option) bool

NotDeepEqual asserts that v1 and v2 are not deeply equal according to DeepEqualer.

func NotEqual

func NotEqual[T comparable](tb testing.TB, v1, v2 T, opts ...Option) bool

NotEqual asserts that v1 != v2.

func NotPanics

func NotPanics(tb testing.TB, f func(), opts ...Option) (ok bool)

NotPanics asserts that the code inside the function f does not panic.

It returns true if no panic occurred, or false if f panicked.

func NotType added in v0.15.0

func NotType[T any](tb testing.TB, v any, opts ...Option) bool

NotType asserts that v is not of type T.

func NotZero

func NotZero[T comparable](tb testing.TB, v T, opts ...Option) bool

NotZero asserts that v != zero.

func Panics

func Panics(tb testing.TB, f func(), opts ...Option) (rec any, ok bool)

Panics asserts that the code inside the function f panics.

It returns the recovered value and true if a panic occurred, or nil and false if f did not panic.

func Positive

func Positive[T SignedNumber](tb testing.TB, v T, opts ...Option) bool

Positive asserts that the value is positive.

func RegexpMatch

func RegexpMatch[RS RegexpString](tb testing.TB, rs RS, s string, opts ...Option) bool

RegexpMatch asserts that rs matches s.

func RegexpNotMatch

func RegexpNotMatch[RS RegexpString](tb testing.TB, rs RS, s string, opts ...Option) bool

RegexpNotMatch asserts that rs doesn't match s.

func SliceContains

func SliceContains[S ~[]E, E comparable](tb testing.TB, s S, v E, opts ...Option) bool

SliceContains asserts that s contains v.

func SliceElementsMatch added in v0.15.4

func SliceElementsMatch[S ~[]E, E comparable](tb testing.TB, s1, s2 S, opts ...Option) bool

SliceElementsMatch asserts that s1 and s2 contain the same elements, regardless of order.

func SliceEmpty

func SliceEmpty[S ~[]E, E any](tb testing.TB, s S, opts ...Option) bool

SliceEmpty asserts that s is empty.

func SliceEqual

func SliceEqual[S ~[]E, E comparable](tb testing.TB, s1, s2 S, opts ...Option) bool

SliceEqual asserts that s1 and s2 are equal.

func SliceLen

func SliceLen[S ~[]E, E any](tb testing.TB, s S, l int, opts ...Option) bool

SliceLen asserts that s has length l.

func SliceNil

func SliceNil[S ~[]E, E any](tb testing.TB, s S, opts ...Option) bool

SliceNil asserts that s is nil.

func SliceNotContains

func SliceNotContains[S ~[]E, E comparable](tb testing.TB, s S, v E, opts ...Option) bool

SliceNotContains asserts that s does not contain v.

func SliceNotEmpty

func SliceNotEmpty[S ~[]E, E any](tb testing.TB, s S, opts ...Option) bool

SliceNotEmpty asserts that s is not empty.

func SliceNotEqual

func SliceNotEqual[S ~[]E, E comparable](tb testing.TB, s1, s2 S, opts ...Option) bool

SliceNotEqual asserts that s1 and s2 are not equal.

func SliceNotNil

func SliceNotNil[S ~[]E, E any](tb testing.TB, s S, opts ...Option) bool

SliceNotNil asserts that s is not nil.

func StringContains

func StringContains(tb testing.TB, s, substr string, opts ...Option) bool

StringContains asserts that s contains substr.

func StringEqualFold

func StringEqualFold(tb testing.TB, s1, s2 string, opts ...Option) bool

StringEqualFold asserts that s1 and s2 are equal, ignoring case.

func StringHasPrefix

func StringHasPrefix(tb testing.TB, s, prefix string, opts ...Option) bool

StringHasPrefix asserts that s begins with prefix.

func StringHasSuffix

func StringHasSuffix(tb testing.TB, s, suffix string, opts ...Option) bool

StringHasSuffix asserts that s ends with suffix.

func StringLen

func StringLen(tb testing.TB, s string, l int, opts ...Option) bool

StringLen asserts that s has length l.

func StringNotContains

func StringNotContains(tb testing.TB, s, substr string, opts ...Option) bool

StringNotContains asserts that s does not contain substr.

func StringNotHasPrefix added in v0.14.1

func StringNotHasPrefix(tb testing.TB, s, prefix string, opts ...Option) bool

StringNotHasPrefix asserts that s does not begin with prefix.

func StringNotHasSuffix added in v0.14.1

func StringNotHasSuffix(tb testing.TB, s, suffix string, opts ...Option) bool

StringNotHasSuffix asserts that s does not end with suffix.

func True

func True(tb testing.TB, v bool, opts ...Option) bool

True asserts that v == true.

func Type

func Type[T any](tb testing.TB, v any, opts ...Option) (T, bool)

Type asserts that v is of type T, and returns it.

func Zero

func Zero[T comparable](tb testing.TB, v T, opts ...Option) bool

Zero asserts that v == zero.

Types

type Float added in v0.14.0

type Float interface {
	~float32 | ~float64
}

Float represents all floating-point numeric types.

type Option

type Option func(*options)

Option is an option for an assertion.

func Lazy added in v0.5.0

func Lazy(f func() Option) Option

Lazy returns an Option that defers the evaluation of the option.

It helps to reduce allocations when the option is not used.

func Message

func Message(msg string) Option

Message returns an Option that sets the message.

func MessageTransform

func MessageTransform(f func(msg string) string) Option

MessageTransform returns an Option that adds a message transform function. The function is called before the ReportFunc. If several functions are added, they are called in order.

func MessageWrap

func MessageWrap(msg string) Option

MessageWrap returns an Option that wraps the message. The final message is "<msg>: <original message>".

func MessageWrapf

func MessageWrapf(format string, args ...any) Option

MessageWrapf returns an Option that wraps the message. The final message is "<format msg>: <original message>".

func Messagef

func Messagef(format string, args ...any) Option

Messagef returns an Option that sets the formatted message.

func Options added in v0.5.0

func Options(opts ...Option) Option

Options returns an Option that combines several options.

func Report

func Report(f ReportFunc) Option

Report returns an Option that sets the ReportFunc. The default value is DefaultReport.

func ReportError added in v0.9.0

func ReportError() Option

ReportError returns an Option that sets the ReportFunc to testing.TB.Error.

func ReportFatal added in v0.9.0

func ReportFatal() Option

ReportFatal returns an Option that sets the ReportFunc to testing.TB.Fatal.

func ReportLog added in v0.9.0

func ReportLog() Option

ReportLog returns an Option that sets the ReportFunc to testing.TB.Log.

func ReportSkip added in v0.9.0

func ReportSkip() Option

ReportSkip returns an Option that sets the ReportFunc to testing.TB.Skip.

func ShowStack added in v0.10.0

func ShowStack(show bool) Option

ShowStack returns an Option that sets whether to show the stack trace on failure. The default value is DefaultShowStack.

type RegexpString

type RegexpString interface {
	*regexp.Regexp | string
}

RegexpString is a type that can be either a *regexp.Regexp or a string.

If it's a string, it's automatically compiled to a *regexp.Regexp.

type ReportFunc

type ReportFunc func(tb testing.TB, args ...any)

ReportFunc is a function that is called when an assertion fails.

It can be set to method expressions such as testing.TB.Fatal, testing.TB.Error, testing.TB.Skip, or testing.TB.Log. The default value is DefaultReport.

type SignedNumber added in v0.14.1

type SignedNumber interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64
}

SignedNumber represents all signed numeric types (signed integers and floats).

Directories

Path Synopsis
Package assertauto provides helpers to automatically update the expected values of test assertions.
Package assertauto provides helpers to automatically update the expected values of test assertions.
internal
Package diff is a copy of https://pkg.go.dev/internal/diff.
Package diff is a copy of https://pkg.go.dev/internal/diff.
Package asserttest provides utilities to test assertions.
Package asserttest provides utilities to test assertions.

Back | FazBrowse Home | New Git URL