assert

package module
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2024 License: MIT Imports: 13 Imported by: 0

README

Assert

Go test assertion library.

Go Reference

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.Report(t.Error))

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
}

Surprinsingly, this test fails with this error:

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

This issue is caused by the types, which are no 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 approchach has a limitation: it requires to write a different assertion function for each "kind" (map, slice, etc...)

Customization

The default behavior can be customized:

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. It can be customized with the Report() option.

Index

Constants

This section is empty.

Variables

View Source
var DeepEqualer = func(v1, v2 any) (diff string, equal bool) {
	res := compare.Compare(v1, v2)
	if len(res) == 0 {
		return "", true
	}
	diff = fmt.Sprintf("%+v", res)
	return diff, false
}

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

It can be customized to provide a better comparison.

By default it uses compare.Compare.

View Source
var ErrorStringer func(error) string = error.Error

ErrorStringer is a function that returns a string representation of an error.

It can be customized to provide a better error message.

View Source
var ValueStringer func(any) string = pretty.String

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

It can be customized to provide a better string representation.

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.

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 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 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 ChanNotEmpty

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

ChanNotEmpty asserts that c is not empty.

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 deep equal according to DeepEqualer.

func Equal

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

Equal asserts that v1 == v2.

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.

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, 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 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 SignedAndFloat](tb testing.TB, v T, opts ...Option) bool

Negative asserts that the value is negative.

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 deep 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.

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.

func Positive

func Positive[T SignedAndFloat](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 SliceContainsAll

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

SliceContainsAll asserts that s1 contains all elements in s2.

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 SliceNotContainsAll

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

SliceNotContainsAll asserts that s1 does not contain all elements in s2.

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 StringEmpty

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

StringEmpty asserts that s is empty.

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 StringNotEmpty

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

StringNotEmpty asserts that s is not empty.

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 TypeString

func TypeString[T any]() string

TypeString returns a string representation of a type.

func Zero

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

Zero asserts that v == zero.

Types

type Option

type Option func(*options)

Option is an option for an assertion.

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 function are added, they're 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 Report

func Report(f ReportFunc) Option

Report returns an Option that sets the report function.

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(args ...any)

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

It is implemented by [testing.TB.Fatal]|[testing.TB.Error]|[testing.TB.Skip]|[testing.TB.Log].

type SignedAndFloat

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

SignedAndFloat is a constraint that requires a type to be signed or float.

Directories

Path Synopsis
Package assertauto provides helpers to automatically update the expected values of assertions.
Package assertauto provides helpers to automatically update the expected values of assertions.
Package asserttest provides utilities to test assertions.
Package asserttest provides utilities to test assertions.

Jump to

Keyboard shortcuts

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