assert

package
v0.44.0 Latest Latest
Warning

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

Go to latest
Published: Jan 14, 2026 License: MIT Imports: 6 Imported by: 1

README

The assert package

The assert package is a toolkit for Go testing that offers common assertions, integrating well with the standard library. When writing tests, developers often face a choice between using Go's standard testing package or packages like assert. The standard library requires verbose if statements for assertions, which can make tests harder to read. This package, on the other hand, provides one-line asserts, such as assert.NoError, which are more concise and clear. This simplicity helps quickly grasp the intent of each test, enhancing readability.

By making tests easier to write and read, this package hopes to encourage developers to invest more time in testing. Features like immediate feedback with easily readable output and a wide range of assertion functions lower the barrier to writing comprehensive tests. This can lead to better code coverage, as developers are more likely to write and maintain tests when the process is straightforward and rewarding.

Assertions

Most of the assertions are self-explanatory, and I encourage you to see your online documentation. Here we will highlight only the ones that we feel are interesting.

Asserting Structures
type T struct {
    Int int
    Str string
}

have := T{Int: 1, Str: "abc"}
want := T{Int: 2, Str: "xyz"}

assert.Equal(want, have)
// Test Log:
//
// expected values to be equal:
//   trail: T.Int
//    want: 2
//    have: 1
//  ---
//   trail: T.Str
//    want: "xyz"
//    have: "abc"
Asserting Recursive Structures
type T struct {
    Int  int
    Next *T
}

have := T{1, &T{2, &T{3, &T{42, nil}}}}
want := T{1, &T{2, &T{3, &T{4, nil}}}}

assert.Equal(want, have)

// Test Log:
//
// expected values to be equal:
//   trail: T.Next.Next.Next.Int
//    want: 4
//    have: 42
Asserting Maps, Arrays, and Slices

Maps

type T struct {
    Str string
}

want := map[int]T{1: {Str: "abc"}, 2: {Str: "xyz"}}
have := map[int]T{1: {Str: "abc"}, 3: {Str: "xyz"}}

assert.Equal(want, have)

// Test Log:
//
// expected values to be equal:
//       trail: map[2]
//        want:
//              map[int]T{
//                1: {
//                  Str: "abc",
//                },
//                3: {
//                  Str: "xyz",
//                },
//              }
//        have: nil
//   want type: map[int]T
//   have type: <nil>

Slices and arrays

want := []int{1, 2, 3}
have := []int{1, 2, 3, 4}

assert.Equal(want, have)

// Test Log:
//
// expected values to be equal:
//   want len: 3
//   have len: 4
//       want:
//             []int{
//               1,
//               2,
//               3,
//             }
//       have:
//             []int{
//               1,
//               2,
//               3,
//               4,
//             }
Asserting Time
want := time.Date(2025, 1, 1, 0, 0, 0, 0, time.UTC)
have := time.Date(2025, 1, 1, 0, 1, 1, 0, time.UTC)

assert.Time(want, have)

// Test Log:
//
//  expected equal dates:
//   want: 2025-01-01T00:00:00Z
//   have: 2025-01-01T00:01:01Z
//   diff: -1m1s
Asserting JSON Strings
want := `{"A": 1, "B": 2}`
have := `{"A": 1, "B": 3}`

assert.JSON(want, have)

// Test Log:
//
// expected JSON strings to be equal:
//   want: {"A":1,"B":2}
//   have: {"A":1,"B":3}
Worthy mentions
  • Epsilon - assert floating point numbers within given ε.
  • ChannelWillClose - assert channel will be closed within given time.
  • MapSubset - checks the "want" is a subset "have".
  • Wait - Wait waits for "fn" to return true but no longer then given timeout.

See the documentation for the full list.

Advanced usage

Custom Checkers

Custom checkers allow you to define specialized comparison logic for any type or field trail in your Go tests. A custom checker is a function that matches the check.Check signature, enabling fine-grained control over assertions. Below is an example demonstrating how to create and use a custom checker.

type T struct {
    Str string
    Any []any
}

chk := func(want, have any, opts ...any) error {
    wVal := want.(float64)
    hVal := want.(float64)
    return check.Epsilon(wVal, 0.01, hVal, opts...)
}
opt := check.WithTrailChecker("T.Any[1]", chk)

want := T{Str: "abc", Any: []any{1, 2.123, "abc"}}
have := T{Str: "abc", Any: []any{1, 2.124, "abc"}}

assert.Equal(want, have, opt)

// Test Log:
//
//  <nil>

In this example, the custom checker chk compares float64 values at the trail T.Any[1] with a tolerance of 0.01. The assertion passes because 2.123 and 2.124 are within the specified epsilon.

Also, see the example in custom_assertion_test.go.

Understanding Trails

A trail uniquely identifies a struct field, slice or array element, or map key visited during an assertion. The assert package automatically tracks trails for composite types, enabling precise targeting for custom checkers. To inspect all visited trails, use the check.WithTrailLog option, as shown below:

type T struct {
    Int  int
    Next *T
}

have := T{1, &T{2, &T{3, &T{42, nil}}}}
want := T{1, &T{2, &T{3, &T{42, nil}}}}
trails := make([]string, 0)

assert.Equal(want, have, check.WithTrailLog(&trails))

fmt.Println(strings.Join(trails, "\n"))
// Output:
// T.Int
// T.Next.Int
// T.Next.Next.Int
// T.Next.Next.Next.Int
// T.Next.Next.Next.Next

This output shows the hierarchical paths visited, including fields of nested structs. Trails are essential for registering checkers at specific points in a complex type.

Registering Custom Type Checkers

You can register custom checkers for entire types using the check.WithTypeChecker option. This is useful for types with complex comparison logic, such as those requiring deep equality checks or custom tolerances. The process is similar to check.WithTrailChecker, but applies to all instances of a type rather than a specific trail.

Custom type checkers are also invaluable when working with types that have non-exported fields. In Go, non-exported fields are inaccessible outside their defining package, which prevents the assert package from directly comparing them. By defining a custom type checker, you can implement comparison logic that accesses these private fields within the same package, ensuring accurate assertions for such types.

type T struct{ value float64 }

chk := func(want, have any, opts ...any) error {
    w := want.(T)
    h := have.(T)
    return check.Epsilon(w.value, h.value, 0.001, opts...)
}

opt := check.WithTypeChecker(T{}, chk)

want := T{value: 1.2345}
have := T{value: 1.2346}
err := check.Equal(want, have, opt)

fmt.Println(err)
// Output:
//  <nil>
Registering Global Type Checkers

Global checkers provide a convenient way to apply custom comparison logic across all assertions for a specific type, without needing to specify the checker in each assert.Equal call. This is particularly useful for complex types with non-exported fields or custom comparison requirements. Use the check.RegisterTypeChecker function to register a global checker.

Key Points for Global Checkers:

  • Registration: call check.RegisterTypeChecker once, typically during package initialization or in a TestMain function, to ensure the checker is available for all tests.
  • Scope: the checker applies to all assertions involving the registered type, streamlining test code.
  • Non-Exported Fields: global checkers are ideal for types with non-exported fields, as they allow you to define comparison logic that accesses private data.
  • Thread Safety: ensure the checker function is thread-safe, as it may be called concurrently in tests.

There are two suggested ways to register a global type checker. Either using TestMain function or init function in one of your _test.go files.

To register a global type checker, you can use either the TestMain function or an init function in a _test.go file. The TestMain approach is preferred for centralized test setup, ensuring the checker is registered before any tests run. An init function in a test file is suitable for package-specific checkers, automatically executed when the test package is loaded.

func TestMain(m *testing.M) {
    check.RegisterTypeChecker(LocalType{}, checker)
    os.Exit(m.Run())
}

// or

func init() {
    check.RegisterTypeChecker(LocalType{}, checker)
}

Every time the new global type checker is registered, you will also see the below line in the test log:

*** CHECK /path/to/registration/call/all_test.go:20: Registering type checker for: mocker.goimp

Every time a check overrides the global type checker with checker.WithTypeChecker option the log is written:

*** CHECK /path/to/option/call/file_test.go:20: Overwriting the global type checker for: mocker.goimp
Skipping Fields, Elements, or Indexes

You can ask for certain trials to be skipped when asserting.

type T struct {
    Int  int
    Next *T
}

have := T{1, &T{2, &T{3, &T{42, nil}}}}
want := T{1, &T{2, &T{8, &T{42, nil}}}}
trails := make([]string, 0)

assert.Equal(
    want,
    have,
    check.WithTrailLog(&trails),
    check.WithSkipTrail("T.Next.Next.Int"),
)

fmt.Println(strings.Join(trails, "\n"))
// Test Log:
//
// T.Int
// T.Next.Int
// T.Next.Next.Int <skipped>
// T.Next.Next.Next.Int
// T.Next.Next.Next.Next

Notice that the requested trail was skipped from assertion even though the values were not equal 3 != 8. The skipped paths are always marked with <skipped> tag.

Skipping unexported fields

The assert.Equal will fail the test if the compared values (structs) have unexported fields. This happens by design to make sure the equality check doesn't silently ignore unexported fields. In cases like this the testing module requires from a developer either explicitly specify fields to skip during comparison or enable a mode that ignores all unexported fields, as supported by the testing framework.

type T struct {
    Int  int
    prv  int
    Next *T
}

have := T{1, -1, &T{2, -2, &T{3, -3, &T{42, -4, nil}}}}
want := T{1, -7, &T{2, -7, &T{3, -7, &T{42, -7, nil}}}}
trails := make([]string, 0)

err := check.Equal(
    want,
    have,
    check.WithTrailLog(&trails),
    check.WithSkipUnexported,
)

fmt.Println(err)
fmt.Println(strings.Join(trails, "\n"))
// Output:
// <nil>
// T.Int
// T.prv <skipped>
// T.Next.Int
// T.Next.prv <skipped>
// T.Next.Next.Int
// T.Next.Next.prv <skipped>
// T.Next.Next.Next.Int
// T.Next.Next.Next.prv <skipped>
// T.Next.Next.Next.Next

Documentation

Overview

Package assert provides assertion functions.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func After

func After(t tester.T, mark, date time.Time, opts ...any) bool

After asserts "date" is after the "mark" date. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "date" and "mark" might be date representations in the form of string, int, int64 or time.Time. For string representations the check.Options.TimeFormat is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.

func AfterOrEqual

func AfterOrEqual(t tester.T, mark, date any, opts ...any) bool

AfterOrEqual asserts "date" is equal or after "mark". Returns true if it's, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "date" and "mark" might be date representations in the form of a string, int, int64 or time.Time. For string representations the check.Options.TimeFormat is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.

func Before

func Before(t tester.T, mark, date any, opts ...any) bool

Before asserts "date" is before the "mark" date. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "date" and "mark" might be date representations in the form of string, int, int64 or time.Time. For string representations the check.Options.TimeFormat is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.

func BeforeOrEqual

func BeforeOrEqual(t tester.T, mark, date time.Time, opts ...any) bool

BeforeOrEqual asserts "date" is equal or before the "mark" date. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "date" and "mark" might be date representations in the form of a string, int, int64 or time.Time. For string representations the check.Options.TimeFormat is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.

func Cap added in v0.28.0

func Cap(t tester.T, want int, have any, opts ...any) bool

Cap asserts "have" has "want" capacity. Returns true if it is, otherwise it marks the test as failed, writes an error message to the test log and returns false.

func ChannelWillClose

func ChannelWillClose[C any](t tester.T, within any, c <-chan C, opts ...any) bool

ChannelWillClose asserts the channel will be closed "within" a given time duration. Returns true if it was, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "within" may represent duration in the form of a string, int, int64 or time.Duration.

func Contain

func Contain(t tester.T, want, have string, opts ...any) bool

Contain asserts "want" is a substring of "have". Returns true if it's, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Count

func Count(t tester.T, count int, what, where any, opts ...any) bool

Count asserts there is "count" occurrences of "what" in "where". Returns true if the count matches, otherwise marks the test as failed, writes an error message to the test log and returns false.

Currently, only strings are supported.

func Decreasing added in v0.22.0

func Decreasing[T constraints.Ordered](
	t tester.T,
	seq []T,
	opts ...any,
) bool

Decreasing checks if the given sequence has values in the decreasing order. You may use the check.WithDecreasingSoft option to allow consecutive values to be equal. It returns true if the sequence is decreasing otherwise, marks the test as failed, writes an error message to the test log and returns false.

func Delta added in v0.23.0

func Delta[T, E constraints.Number](
	t tester.T,
	want T, delta E, have T,
	opts ...any,
) bool

Delta asserts both values are within the given delta. Returns true if they are, otherwise marks the test as failed, writes an error message to the test log and returns false.

|w-h|/|w| <= delta

func DeltaSlice added in v0.23.0

func DeltaSlice[T, E constraints.Number](
	t tester.T,
	want []T, delta E, have []T,
	opts ...any,
) bool

DeltaSlice asserts values are within the given delta for all respective slice indexes. It returns true if all differences are within the delta; otherwise, marks the test as failed, writes an error message to the test log and returns false.

|w[i]-h[i]| <= delta

func DirExist

func DirExist(t tester.T, pth string, opts ...any) bool

DirExist asserts "pth" points to an existing directory. It fails if the path points to a filesystem entry, which is not a directory, or there is an error when trying to check the path. Returns true on success, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Duration

func Duration(t tester.T, want, have any, opts ...any) bool

Duration asserts "want" and "have" durations are equal. Returns true if they are, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "want" and "have" might be duration representation in the form of string, int, int64 or time.Duration.

func Empty

func Empty(t tester.T, have any, opts ...any) bool

Empty asserts "have" is empty. Returns true if it's, otherwise marks the test as failed, writes an error message to the test log and returns false.

See check.Empty for the list of values which are considered empty.

func Epsilon

func Epsilon[T, E constraints.Number](
	t tester.T,
	want T, epsilon E, have T,
	opts ...any,
) bool

Epsilon asserts the relative error is less than epsilon. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

|w-h|/|w| <= epsilon

func EpsilonSlice added in v0.21.0

func EpsilonSlice[T, E constraints.Number](
	t tester.T,
	want []T, epsilon E, have []T,
	opts ...any,
) bool

EpsilonSlice asserts the relative error is less than epsilon for all respective values in the provided slices. It returns true if all differences are within the delta; otherwise, marks the test as failed, writes an error message to the test log and returns false.

|w[i]-h[i]|/|w[i]| <= epsilon

func Equal

func Equal(t tester.T, want, have any, opts ...any) bool

Equal asserts both values are equal. Returns true if they are, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Error

func Error(t tester.T, err error, opts ...any) bool

Error asserts "err" is not nil. Returns true if it's, otherwise marks the test as failed, writes an error message to the test log and returns false.

func ErrorAs

func ErrorAs(t tester.T, want any, err error, opts ...any) bool

ErrorAs finds the first error in "err" tree that matches the "want" target, and if one is found, sets a target to that error. Returns true if it does, otherwise marks the test as failed, writes an error message to the test log and returns false.

func ErrorContain

func ErrorContain(t tester.T, want string, err error, opts ...any) bool

ErrorContain asserts "err" is not nil and its message contains "want". Returns true if it does, otherwise marks the test as failed, writes an error message to the test log and returns false.

func ErrorEqual

func ErrorEqual(t tester.T, want string, err error, opts ...any) bool

ErrorEqual asserts "err" is not nil and its message equals to "want". Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

func ErrorIs

func ErrorIs(t tester.T, want, err error, opts ...any) bool

ErrorIs asserts whether any error in "err" tree matches the "want" target. Returns true if it does, otherwise marks the test as failed, writes an error message to the test log and returns false.

func ErrorRegexp

func ErrorRegexp(t tester.T, want string, err error, opts ...any) bool

ErrorRegexp asserts "err" is not nil and its message matches the "want" regex. Returns true if it does, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "want" can be either a regular expression string or instance of regexp.Regexp. The fmt.Sprint is used to get string representation of have argument.

func Exact

func Exact(t tester.T, want, have any, opts ...any) bool

Exact asserts "want" and "have" dates are equal and are in the same timezone. Returns true if they are, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "want" and "have" might be date representations in the form of a string, int, int64 or time.Time. For string representations the check.Options.TimeFormat is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.

func ExitCode

func ExitCode(t tester.T, want int, err error, opts ...any) bool

ExitCode asserts "err" is a pointer to [exec.ExitError] with exit code equal to "want". Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

func False

func False(t tester.T, have bool, opts ...any) bool

False asserts "have" is false. Returns true if it's, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Fields

func Fields(t tester.T, want int, s any, opts ...any) bool

Fields asserts struct or pointer to a struct "s" has "want" number of fields. Returns true if it does, otherwise marks the test as failed, writes an error message to the test log and returns false.

func FileContain

func FileContain[T check.Content](t tester.T, want T, pth string, opts ...any) bool

FileContain asserts a file at "pth" can be read and its string content contains "want". It fails if the path points to a filesystem entry, which is not a file, or there is an error reading the file. The file is read in full, then Contain assertion is used to check it contains the "want" string. Returns true on success, otherwise marks the test as failed, writes an error message to the test log and returns false.

func FileExist

func FileExist(t tester.T, pth string, opts ...any) bool

FileExist asserts "pth" points to an existing file. It fails if the path points to a filesystem entry, which is not a file, or there is an error when trying to check the path. Returns true on success, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Greater added in v0.22.0

func Greater[T constraints.Ordered](
	t tester.T,
	want, have T,
	opts ...any,
) bool

Greater checks the "have" value is greater than the "want" value. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

func GreaterOrEqual added in v0.22.0

func GreaterOrEqual[T constraints.Ordered](
	t tester.T,
	want, have T,
	opts ...any,
) bool

GreaterOrEqual checks the "have" value is greater or equal than the "want" value. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Has

func Has[T comparable](t tester.T, want T, bag []T, opts ...any) bool

Has asserts the slice has "want" value. Returns true if it does, otherwise marks the test as failed, writes an error message to the test log and returns false.

func HasKey

func HasKey[K comparable, V any](t tester.T, key K, set map[K]V, opts ...any) (V, bool)

HasKey asserts the map has a key. Returns true if it does, otherwise marks the test as failed, writes an error message to the test log and returns false.

func HasKeyValue

func HasKeyValue[K, V comparable](
	t tester.T,
	key K,
	want V,
	set map[K]V,
	opts ...any,
) bool

HasKeyValue asserts the map has a key with the given value. Returns true if it doesn't, otherwise marks the test as failed, writes an error message to the test log and returns false.

func HasNo

func HasNo[T comparable](t tester.T, want T, bag []T, opts ...any) bool

HasNo asserts slice does not have a "want" value. Returns true if it does not, otherwise marks the test as failed, writes an error message to the test log and returns false.

func HasNoKey

func HasNoKey[K comparable, V any](t tester.T, key K, set map[K]V, opts ...any) bool

HasNoKey asserts the map has no key. Returns true if it doesn't, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Increasing added in v0.22.0

func Increasing[T constraints.Ordered](
	t tester.T,
	seq []T,
	opts ...any,
) bool

Increasing checks if the given sequence has values in the increasing order. You may use the check.WithIncreasingSoft option to allow consecutive values to be equal. It returns true if the sequence is increasing otherwise, marks the test as failed, writes an error message to the test log and returns false.

func JSON

func JSON(t tester.T, want, have string, opts ...any) bool

JSON asserts that two JSON strings are equivalent. Returns true if they are, otherwise marks the test as failed, writes an error message to the test log and returns false.

Example:

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

func Len

func Len(t tester.T, want int, have any, opts ...any) bool

Len asserts "have" has "want" length. Returns true if it is, otherwise it marks the test as failed, writes an error message to the test log and returns false.

func MapSubset

func MapSubset[K cmp.Ordered, V any](
	t tester.T,
	want, have map[K]V,
	opts ...any,
) bool

MapSubset asserts the "want" is a subset "have". In other words, all keys and their corresponding values in the "want" map must be in the "have" map. It is not an error when the "have" map has some other keys. Returns true if "want is a subset of "have", otherwise marks the test as failed, writes an error message to the test log and returns false.

func MapsSubset

func MapsSubset[K cmp.Ordered, V any](
	t tester.T,
	want, have []map[K]V,
	opts ...any,
) bool

MapsSubset asserts all the "want" maps are subsets of corresponding "have" maps using MapSubset. Returns true if all "want" maps are subset of corresponding "have" maps, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Nil

func Nil(t tester.T, have any, opts ...any) bool

Nil asserts "have" is nil. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

func NoDirExist

func NoDirExist(t tester.T, pth string, opts ...any) bool

NoDirExist asserts "pth" points to not existing directory. It fails if the path points to an existing filesystem entry. Returns true on success, otherwise marks the test as failed, writes an error message to the test log and returns false.

func NoError

func NoError(t tester.T, err error, opts ...any) bool

NoError asserts "err" is nil. Returns true if it is not, otherwise marks the test as failed, writes an error message to the test log and returns false.

func NoFileExist

func NoFileExist(t tester.T, pth string, opts ...any) bool

NoFileExist asserts "pth" points to a not existing file. It fails if the path points to an existing filesystem entry. Returns true on success, otherwise marks the test as failed, writes an error message to the test log and returns false.

func NoPanic

func NoPanic(t tester.T, fn check.TestFunc, opts ...any) bool

NoPanic asserts "fn" does not panic. Returns true if it did not panic, otherwise marks the test as failed, writes an error message to the test log and returns false.

func NotContain

func NotContain(t tester.T, want, have string, opts ...any) bool

NotContain asserts "want" is not a substring of "have". Returns true if it's not, otherwise marks the test as failed, writes an error message to the test log and returns false.

func NotDecreasing added in v0.22.0

func NotDecreasing[T constraints.Ordered](
	t tester.T,
	seq []T,
	opts ...any,
) bool

NotDecreasing is inverse of Decreasing.

func NotEmpty

func NotEmpty(t tester.T, have any, opts ...any) bool

NotEmpty asserts "have" is not empty. Returns true if it is not, otherwise marks the test as failed, writes an error message to the test log and returns false.

See check.Empty for the list of values which are considered empty.

func NotEqual

func NotEqual(t tester.T, want, have any, opts ...any) bool

NotEqual asserts both values are not equal. Returns true if they are not, otherwise marks the test as failed, writes an error message to the test log and returns false.

func NotIncreasing added in v0.22.0

func NotIncreasing[T constraints.Ordered](
	t tester.T,
	seq []T,
	opts ...any,
) bool

NotIncreasing is inverse of Increasing.

func NotNil

func NotNil(t tester.T, have any, opts ...any) bool

NotNil asserts "have" is not nil. Returns true if it is not, otherwise marks the test as failed, writes an error message to the test log and returns false.

func NotSame

func NotSame(t tester.T, want, have any, opts ...any) bool

NotSame asserts "want" and "have" are generic pointers and that both do not reference the same object. Returns true if they are not, otherwise marks the test as failed, writes an error message to the test log and returns false.

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

func NotSameType added in v0.38.0

func NotSameType(t tester.T, want, have any, opts ...any) bool

NotSameType asserts that the arguments are not of the same type. Returns true if they are not, otherwise marks the test as failed, writes an error message to the test log and returns false.

Assertion uses reflect.TypeOf equality to determine the type.

func NotZero

func NotZero(t tester.T, have any, opts ...any) bool

NotZero asserts "have" is not the zero value for its type. Returns true if it is not, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Panic

func Panic(t tester.T, fn check.TestFunc, opts ...any) bool

Panic asserts "fn" panics. Returns true if it panicked, otherwise marks the test as failed, writes an error message to the test log and returns false.

func PanicContain

func PanicContain(t tester.T, want string, fn check.TestFunc, opts ...any) bool

PanicContain asserts "fn" panics, and the recovered panic value represented as a string contains "want". Returns true if it panics and does contain the wanted string, otherwise marks the test as failed, writes an error message to the test log and returns false.

func PanicMsg

func PanicMsg(t tester.T, fn check.TestFunc, opts ...any) *string

PanicMsg asserts the "fn" panics and returns the recovered panic value represented as a string. If the function did not panic, it marks the test as failed and writes an error message to the test log.

func Recent

func Recent(t tester.T, have any, opts ...any) bool

Recent asserts "have" is within check.Options.Recent from time.Now. Returns nil if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "have" may represent date in the form of a string, int, int64 or time.Time. For string representations the check.Options.TimeFormat is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.

func Regexp

func Regexp(t tester.T, want, have any, opts ...any) bool

Regexp asserts that "want" regexp matches a string representation of "have. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "want" can be either a regular expression string or instance of regexp.Regexp. The fmt.Sprint s used to get string representation of have argument.

func Same

func Same(t tester.T, want, have any, opts ...any) bool

Same asserts "want" and "have" are generic pointers and that both reference the same object. Returns true if they are, otherwise marks the test as failed, writes an error message to the test log and returns false.

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

func SameType added in v0.37.0

func SameType(t tester.T, want, have any, opts ...any) bool

SameType asserts that both arguments are of the same type. Returns true if they are, otherwise marks the test as failed, writes an error message to the test log and returns false.

Assertion uses reflect.TypeOf equality to determine the type.

func SliceSubset

func SliceSubset[T comparable](t tester.T, want, have []T, opts ...any) bool

SliceSubset checks the "want" is a subset "have". In other words, all values in the "want" slice must be in the "have" slice. Returns nil if they are, otherwise returns an error with a message indicating the expected and actual values.

func Smaller added in v0.22.0

func Smaller[T constraints.Ordered](
	t tester.T,
	want, have T,
	opts ...any,
) bool

Smaller checks the "have" value is smaller than the "want" value. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

func SmallerOrEqual added in v0.22.0

func SmallerOrEqual[T constraints.Ordered](
	t tester.T,
	want, have T,
	opts ...any,
) bool

SmallerOrEqual checks the "have" value is smaller or equal than the "want" value. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Time

func Time(t tester.T, want, have any, opts ...any) bool

Time asserts "want" and "have" dates are equal. Returns true if they are, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "want" and "have" might be date representations in the form of a string, int, int64 or time.Time. For string representations the check.Options.TimeFormat is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.

func True

func True(t tester.T, have bool, opts ...any) bool

True asserts "have" is true. Returns true if it's, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Type

func Type(t tester.T, want, have any, opts ...any) bool

Type asserts that the "src" can be type assigned to the pointer of the "target" (same as target, ok := src.(target)). Returns true if it can be done, otherwise marks the test as failed, writes an error message to the test log and returns false.

Example:

var target int
var src any = 42
assert.Type(t, &target, src)

func Wait added in v0.32.0

func Wait(t tester.T, timeout string, fn func() bool, opts ...any) bool

Wait waits for "fn" to return true but no longer then given timeout. By default, calls to "fn" are throttled with a default throttle set in check.Options.WaitThrottle - use check.WithWaitThrottle option to change it. Returns true when the function returns true within given timeout, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "timeout" may represent duration in the form of a string, int, int64 or time.Duration.

func Within

func Within(t tester.T, want, within, have any, opts ...any) bool

Within asserts "want" and "have" dates are equal "within" given duration. Returns true if they are, otherwise marks the test as failed, writes an error message to the test log and returns false.

The "want" and "have" might be date representations in the form of a string, int, int64 or time.Time. For string representations the check.Options.TimeFormat is used during parsing and the returned date is always in UTC. The int and int64 types are interpreted as Unix Timestamp, and the date returned is also in UTC.

func Zero

func Zero(t tester.T, have any, opts ...any) bool

Zero asserts "have" is the zero value for its type. Returns true if it is, otherwise marks the test as failed, writes an error message to the test log and returns false.

func Zone

func Zone(t tester.T, want, have *time.Location, opts ...any) bool

Zone asserts "want" and "have" timezones are equal. Returns true if they are, otherwise marks the test as failed, writes an error message to the test log and returns false.

Types

This section is empty.

Jump to

Keyboard shortcuts

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