assertions

package
v2.2.0 Latest Latest
Warning

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

Go to latest
Published: Jan 24, 2026 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Overview

Package assertions holds the internal implementation of all the helper functions exposed by testify.

It serves as a base to develop and test testify, whereas the publicly exposed API (in packages assert and require) is generated.

For convenience, assertion functions are classified by domain. The entire API can be searched by domain at https://go-openapi.github.io/testify/api. # Domains

- boolean: asserting boolean values - collection: asserting slices and maps - comparison: comparing ordered values - condition: expressing assertions using conditions - equality: asserting two things are equal - error: asserting errors - file: asserting OS files - http: asserting HTTP response and body - json: asserting JSON documents - number: asserting numbers - ordering: asserting how collections are ordered - panic: asserting a panic behavior - string: asserting strings - testing: mimicks methods from the testing standard library - time: asserting times and durations - type: asserting types rather than values - yaml: asserting yaml documents

Index

Constants

This section is empty.

Variables

View Source
var ErrTest = errors.New("assert.ErrTest general error for testing") // Proposal for enhancement: make a type and a const.

ErrTest 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() []string

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(t T, comp Comparison, msgAndArgs ...any) bool

Condition uses a Comparison to assert a complex condition.

Usage

assertions.Condition(t, func() bool { return myCondition })

Examples

success:  func() bool { return true }
failure:  func() bool { return false }

func Contains

func Contains(t T, s, contains any, msgAndArgs ...any) bool

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

Usage

assertions.Contains(t, "Hello World", "World")
assertions.Contains(t, []string{"Hello", "World"}, "World")
assertions.Contains(t, map[string]string{"Hello": "World"}, "Hello")

Examples

success: []string{"A","B"}, "A"
failure: []string{"A","B"}, "C"

func DirExists

func DirExists(t T, path string, msgAndArgs ...any) bool

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.

Usage

assertions.DirExists(t, "path/to/directory")

Examples

success: filepath.Join(testDataPath(),"existing_dir")
failure: filepath.Join(testDataPath(),"non_existing_dir")

func DirNotExists added in v2.2.0

func DirNotExists(t T, path string, msgAndArgs ...any) bool

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

Usage

assertions.DirNotExists(t, "path/to/directory")

Examples

success: filepath.Join(testDataPath(),"non_existing_dir")
failure: filepath.Join(testDataPath(),"existing_dir")

func ElementsMatch

func ElementsMatch(t T, listA, listB any, msgAndArgs ...any) (ok bool)

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.

Usage

assertions.ElementsMatch(t, []int{1, 3, 2, 3}, []int{1, 3, 3, 2})

Examples

success: []int{1, 3, 2, 3}, []int{1, 3, 3, 2}
failure: []int{1, 2, 3}, []int{1, 2, 4}

func ElementsMatchT added in v2.2.0

func ElementsMatchT[E comparable](t T, listA, listB []E, msgAndArgs ...any) bool

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

Usage

assertions.ElementsMatchT(t, []int{1, 3, 2, 3}, []int{1, 3, 3, 2})

Examples

success: []int{1, 3, 2, 3}, []int{1, 3, 3, 2}
failure: []int{1, 2, 3}, []int{1, 2, 4}

func Empty

func Empty(t T, object any, msgAndArgs ...any) bool

Empty asserts that the given value is "empty".

Zero values are "empty".

Arrays are "empty" if every element is the zero value of the type (stricter than "empty").

Slices, maps and channels with zero length are "empty".

Pointer values are "empty" if the pointer is nil or if the pointed value is "empty".

Usage

assertions.Empty(t, obj)

Examples

success: ""
failure: "not empty"

func Equal

func Equal(t T, expected, actual any, msgAndArgs ...any) bool

Equal asserts that two objects are equal.

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.

Usage

assertions.Equal(t, 123, 123)

Examples

success: 123, 123
failure: 123, 456

func EqualError

func EqualError(t T, err error, errString string, msgAndArgs ...any) bool

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

Usage

actualObj, err := SomeFunction()
assertions.EqualError(t, err,  expectedErrorString)

Examples

success: ErrTest, "assert.ErrTest general error for testing"
failure: ErrTest, "wrong error message"

func EqualExportedValues

func EqualExportedValues(t T, expected, actual any, msgAndArgs ...any) bool

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.

Function equality cannot be determined and will always fail.

Usage

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

Examples

success: &dummyStruct{A: "a", b: 1}, &dummyStruct{A: "a", b: 2}
failure:  &dummyStruct{A: "a", b: 1}, &dummyStruct{A: "b", b: 1}

func EqualT added in v2.2.0

func EqualT[V comparable](t T, expected, actual V, msgAndArgs ...any) bool

EqualT asserts that two objects of the same comparable type are equal.

Pointer variable equality is determined based on the equality of the memory addresses (unlike Equal, but like Same).

Functions, slices and maps are not comparable. See also ComparisonOperators.

If you need to compare values of non-comparable types, or compare pointers by the value they point to, use Equal instead.

Usage

assertions.EqualT(t, 123, 123)

Examples

success: 123, 123
failure: 123, 456

func EqualValues

func EqualValues(t T, expected, actual any, msgAndArgs ...any) bool

EqualValues asserts that two objects are equal or convertible to the larger type and equal.

Function equality cannot be determined and will always fail.

Usage

assertions.EqualValues(t, uint32(123), int32(123))

Examples

success: uint32(123), int32(123)
failure: uint32(123), int32(456)

func Error

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

Error asserts that a function returned a non-nil error (ie. an error).

Usage

actualObj, err := SomeFunction()
assertions.Error(t, err)

Examples

success: ErrTest
failure: nil

func ErrorAs

func ErrorAs(t T, err error, target any, msgAndArgs ...any) bool

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.

Usage

assertions.ErrorAs(t, err, &target)

Examples

success: fmt.Errorf("wrap: %w", &dummyError{}), new(*dummyError)
failure: ErrTest, new(*dummyError)

func ErrorContains

func ErrorContains(t T, err error, contains string, msgAndArgs ...any) bool

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

Usage

actualObj, err := SomeFunction()
assertions.ErrorContains(t, err,  expectedErrorSubString)

Examples

success: ErrTest, "general error"
failure: ErrTest, "not in message"

func ErrorIs

func ErrorIs(t T, err, target error, msgAndArgs ...any) bool

ErrorIs asserts that at least one of the errors in err's chain matches target.

This is a wrapper for errors.Is.

Usage

assertions.ErrorIs(t, err, io.EOF)

Examples

success: fmt.Errorf("wrap: %w", io.EOF), io.EOF
failure: ErrTest, io.EOF

func Eventually

func Eventually(t T, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...any) bool

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

Eventually waits until the condition returns true, for at most waitFor, or until the parent context of the test is cancelled.

If the condition takes longer than waitFor to complete, Eventually fails but waits for the current condition execution to finish before returning.

For long-running conditions to be interrupted early, check testing.T.Context which is cancelled on test failure.

Usage

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

Concurrency

The condition function is never executed in parallel: only one goroutine executes it. It may write to variables outside its scope without triggering race conditions.

A blocking condition will cause Eventually to hang until it returns.

Examples

success:  func() bool { return true }, 100*time.Millisecond, 20*time.Millisecond
failure:  func() bool { return false }, 100*time.Millisecond, 20*time.Millisecond

func EventuallyWithT

func EventuallyWithT(t T, condition func(collect *CollectT), waitFor time.Duration, tick time.Duration, msgAndArgs ...any) bool

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

In contrast to Eventually, the condition function is supplied with a CollectT to accumulate errors from calling other assertions.

The condition is considered "met" if no errors are raised in a tick. The supplied CollectT collects all errors from one tick.

If the condition is not met before waitFor, the collected errors from the last tick are copied to t.

Calling CollectT.FailNow cancels the condition immediately and fails the assertion.

Usage

externalValue := false
go func() {
	time.Sleep(8*time.Second)
	externalValue = true
}()

assertions.EventuallyWithT(t, func(c *assertions.CollectT) {
	// add assertions as needed; any assertion failure will fail the current tick
	assertions.True(c, externalValue, "expected 'externalValue' to be true")
}, 10*time.Second, 1*time.Second, "external state has not changed to 'true'; still false")

Concurrency

The condition function is never executed in parallel: only one goroutine executes it. It may write to variables outside its scope without triggering race conditions.

Examples

success: func(c *CollectT) { True(c,true) }, 100*time.Millisecond, 20*time.Millisecond
failure: func(c *CollectT) { False(c,true) }, 100*time.Millisecond, 20*time.Millisecond

func Exactly

func Exactly(t T, expected, actual any, msgAndArgs ...any) bool

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

Usage

assertions.Exactly(t, int32(123), int64(123))

Examples

success: int32(123), int32(123)
failure: int32(123), int64(123)

func Fail

func Fail(t T, failureMessage string, msgAndArgs ...any) bool

Fail reports a failure through.

Usage

assertions.Fail(t, "failed")

Examples

failure: "failed"

func FailNow

func FailNow(t T, failureMessage string, msgAndArgs ...any) bool

FailNow fails test.

Usage

assertions.FailNow(t, "failed")

Examples

failure: "failed"

func False

func False(t T, value bool, msgAndArgs ...any) bool

False asserts that the specified value is false.

Usage

assertions.False(t, myBool)

Examples

success: 1 == 0
failure: 1 == 1

func FalseT added in v2.2.0

func FalseT[B Boolean](t T, value B, msgAndArgs ...any) bool

FalseT asserts that the specified value is false.

Usage

 type B bool
 var b B = true

	assertions.FalseT(t, b)

Examples

success: 1 == 0
failure: 1 == 1

func FileEmpty

func FileEmpty(t T, path string, msgAndArgs ...any) bool

FileEmpty checks whether a file exists in the given path and is empty. It fails if the file is not empty, if the path points to a directory or there is an error when trying to check the file.

Usage

assertions.FileEmpty(t, "path/to/file")

Examples

success: filepath.Join(testDataPath(),"empty_file")
failure: filepath.Join(testDataPath(),"existing_file")

func FileExists

func FileExists(t T, path string, msgAndArgs ...any) bool

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.

Usage

assertions.FileExists(t, "path/to/file")

Examples

success: filepath.Join(testDataPath(),"existing_file")
failure: filepath.Join(testDataPath(),"non_existing_file")

func FileNotEmpty

func FileNotEmpty(t T, path string, msgAndArgs ...any) bool

FileNotEmpty checks whether a file exists in the given path and is not empty. It fails if the file is empty, if the path points to a directory or there is an error when trying to check the file.

Usage

assertions.FileNotEmpty(t, "path/to/file")

Examples

success: filepath.Join(testDataPath(),"existing_file")
failure: filepath.Join(testDataPath(),"empty_file")

func FileNotExists added in v2.2.0

func FileNotExists(t T, path string, msgAndArgs ...any) bool

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

Usage

assertions.FileNotExists(t, "path/to/file")

Examples

success: filepath.Join(testDataPath(),"non_existing_file")
failure: filepath.Join(testDataPath(),"existing_file")

func Greater

func Greater(t T, e1 any, e2 any, msgAndArgs ...any) bool

Greater asserts that the first element is strictly greater than the second.

Both elements must be of the same type in the reflect.Kind sense. To compare values that need a type conversion (e.g. float32 against float64), you need to convert types beforehand.

Usage

assertions.Greater(t, 2, 1)
assertions.Greater(t, float64(2), float64(1))
assertions.Greater(t, "b", "a")

Examples

success: 2, 1
failure: 1, 2

func GreaterOrEqual

func GreaterOrEqual(t T, e1 any, e2 any, msgAndArgs ...any) bool

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

See also Greater.

Usage

assertions.GreaterOrEqual(t, 2, 1)
assertions.GreaterOrEqual(t, 2, 2)
assertions.GreaterOrEqual(t, "b", "a")
assertions.GreaterOrEqual(t, "b", "b")

Examples

success: 2, 1
failure: 1, 2

func GreaterOrEqualT added in v2.2.0

func GreaterOrEqualT[Orderable Ordered](t T, e1, e2 Orderable, msgAndArgs ...any) bool

GreaterOrEqualT asserts that for two elements of the same type, the first element is greater than or equal to the second.

The Ordered type can be any of Go's cmp.Ordered (strings, numeric types), []byte (uses bytes.Compare) and time.Time (uses time.Time.Compare.

Notice that pointers are not Ordered, but uintptr are. So you can't call GreaterOrEqualT with *time.Time.

GreaterOrEqualT ensures type safety at build time. If you need to compare values with a dynamically assigned type, use GreaterOrEqual instead.

To compare values that need a type conversion (e.g. float32 against float64), you need to convert types beforehand.

Usage

assertions.GreaterOrEqualT(t, 2, 1)
assertions.GreaterOrEqualT(t, 2, 2)
assertions.GreaterOrEqualT(t, "b", "a")
assertions.GreaterOrEqualT(t, "b", "b")

Examples

success: 2, 1
failure: 1, 2

func GreaterT added in v2.2.0

func GreaterT[Orderable Ordered](t T, e1, e2 Orderable, msgAndArgs ...any) bool

GreaterT asserts that for two elements of the same type, the first element is strictly greater than the second.

The Ordered type can be any of Go's cmp.Ordered (strings, numeric types), []byte (uses bytes.Compare) and time.Time (uses time.Time.Compare.

Notice that pointers are not Ordered, but uintptr are. So you can't call GreaterT with *time.Time.

GreaterT ensures type safety at build time. If you need to compare values with a dynamically assigned type, use Greater instead.

To compare values that need a type conversion (e.g. float32 against float64), you need to convert types beforehand.

Usage

assertions.GreaterT(t, 2, 1)
assertions.GreaterT(t, float64(2), float64(1))
assertions.GreaterT(t, "b", "a")
assertions.GreaterT(t, time.Date(2026,1,1,0,0,0,0,nil), time.Now())

Examples

success: 2, 1
failure: 1, 2

func HTTPBody

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

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

func HTTPBodyContains

func HTTPBodyContains(t T, handler http.HandlerFunc, method, url string, values url.Values, str any, msgAndArgs ...any) bool

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

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

Usage

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

Examples

success: httpBody, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, World!"
failure: httpBody, "GET", "/", url.Values{"name": []string{"Bob"}}, "Hello, World!"

func HTTPBodyNotContains

func HTTPBodyNotContains(t T, handler http.HandlerFunc, method, url string, values url.Values, str any, msgAndArgs ...any) bool

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

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

Usage

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

Examples

success: httpBody, "GET", "/", url.Values{"name": []string{"World"}}, "Hello, Bob!"
failure: httpBody, "GET", "/", url.Values{"name": []string{"Bob"}}, "Hello, Bob!"

func HTTPError

func HTTPError(t T, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...any) bool

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

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

Usage

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

Examples

success: httpError, "GET", "/", nil
failure: httpOK, "GET", "/", nil

func HTTPRedirect

func HTTPRedirect(t T, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...any) bool

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

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

Usage

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

Examples

success: httpRedirect, "GET", "/", nil
failure: httpError, "GET", "/", nil

func HTTPStatusCode

func HTTPStatusCode(t T, handler http.HandlerFunc, method, url string, values url.Values, statuscode int, msgAndArgs ...any) bool

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

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

Usage

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

Examples

success: httpOK, "GET", "/", nil, http.StatusOK
failure: httpError, "GET", "/", nil, http.StatusOK

func HTTPSuccess

func HTTPSuccess(t T, handler http.HandlerFunc, method, url string, values url.Values, msgAndArgs ...any) bool

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

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

Usage

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

Examples

success: httpOK, "GET", "/", nil
failure: httpError, "GET", "/", nil

func Implements

func Implements(t T, interfaceObject any, object any, msgAndArgs ...any) bool

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

Usage

assertions.Implements(t, (*MyInterface)(nil), new(MyObject))

Examples

success: ptr(dummyInterface), new(testing.T)
failure: (*error)(nil), new(testing.T)

func InDelta

func InDelta(t T, expected, actual any, delta float64, msgAndArgs ...any) bool

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

Delta must be greater than or equal to zero.

Expected and actual values should convert to float64. To compare large integers that can't be represented accurately as float64 (eg. uint64), prefer InDeltaT to preserve the original type.

Behavior with IEEE floating point arithmetics

  • expected NaN is matched only by a NaN, e.g. this works: InDeltaT(math.NaN(), math.Sqrt(-1), 0.0)
  • expected +Inf is matched only by a +Inf
  • expected -Inf is matched only by a -Inf

Usage

assertions.InDelta(t, math.Pi, 22/7.0, 0.01)

Examples

success: 1.0, 1.01, 0.02
failure: 1.0, 1.1, 0.05

func InDeltaMapValues

func InDeltaMapValues(t T, expected, actual any, delta float64, msgAndArgs ...any) bool

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

See InDelta.

Usage

assertions.InDeltaMapValues(t, map[string]float64{"a": 1.0}, map[string]float64{"a": 1.01}, 0.02)

Examples

success: map[string]float64{"a": 1.0}, map[string]float64{"a": 1.01}, 0.02
failure: map[string]float64{"a": 1.0}, map[string]float64{"a": 1.1}, 0.05

func InDeltaSlice

func InDeltaSlice(t T, expected, actual any, delta float64, msgAndArgs ...any) bool

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

See InDelta.

Usage

assertions.InDeltaSlice(t, []float64{1.0, 2.0}, []float64{1.01, 2.01}, 0.02)

Examples

success: []float64{1.0, 2.0}, []float64{1.01, 2.01}, 0.02
failure: []float64{1.0, 2.0}, []float64{1.1, 2.1}, 0.05

func InDeltaT added in v2.2.0

func InDeltaT[Number Measurable](t T, expected, actual, delta Number, msgAndArgs ...any) bool

InDeltaT asserts that the two numerals of the same type numerical type are within delta of each other.

InDeltaT accepts any go numeric type, including integer types.

The main difference with InDelta is that the delta is expressed with the same type as the values, not necessarily a float64.

Delta must be greater than or equal to zero.

Behavior with IEEE floating point arithmetics

  • expected NaN is matched only by a NaN, e.g. this works: InDeltaT(math.NaN(), math.Sqrt(-1), 0.0)
  • expected +Inf is matched only by a +Inf
  • expected -Inf is matched only by a -Inf

Usage

assertions.InDeltaT(t, math.Pi, 22/7.0, 0.01)

Examples

success: 1.0, 1.01, 0.02
failure: 1.0, 1.1, 0.05

func InEpsilon

func InEpsilon(t T, expected, actual any, epsilon float64, msgAndArgs ...any) bool

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

Behavior with IEEE floating point arithmetics

  • expected NaN is matched only by a NaN, e.g. this works: InDeltaT(math.NaN(), math.Sqrt(-1), 0.0)
  • expected +Inf is matched only by a +Inf
  • expected -Inf is matched only by a -Inf

Edge case: for very large integers that do not convert accurately to a float64 (e.g. uint64), prefer InDeltaT.

Formula:

  • If expected == 0: fail if |actual - expected| > epsilon
  • If expected != 0: fail if |actual - expected| > epsilon * |expected|

This allows InEpsilonT to work naturally across the full numeric range including zero.

Usage

assertions.InEpsilon(t, 100.0, 101.0, 0.02)

Examples

success: 100.0, 101.0, 0.02
failure: 100.0, 110.0, 0.05

func InEpsilonSlice

func InEpsilonSlice(t T, expected, actual any, epsilon float64, msgAndArgs ...any) bool

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

See InEpsilon.

Usage

assertions.InEpsilonSlice(t, []float64{100.0, 200.0}, []float64{101.0, 202.0}, 0.02)

Examples

success: []float64{100.0, 200.0}, []float64{101.0, 202.0}, 0.02
failure: []float64{100.0, 200.0}, []float64{110.0, 220.0}, 0.05

func InEpsilonT added in v2.2.0

func InEpsilonT[Number Measurable](t T, expected, actual Number, epsilon float64, msgAndArgs ...any) bool

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

When expected is zero, epsilon is interpreted as an absolute error threshold, since relative error is mathematically undefined for zero values.

Unlike InDeltaT, which preserves the original type, InEpsilonT converts the expected and actual numbers to float64, since the relative error doesn't make sense as an integer.

Behavior with IEEE floating point arithmetics

  • expected NaN is matched only by a NaN, e.g. this works: InDeltaT(math.NaN(), math.Sqrt(-1), 0.0)
  • expected +Inf is matched only by a +Inf
  • expected -Inf is matched only by a -Inf

Edge case: for very large integers that do not convert accurately to a float64 (e.g. uint64), prefer InDeltaT.

Formula:

  • If expected == 0: fail if |actual - expected| > epsilon
  • If expected != 0: fail if |actual - expected| > epsilon * |expected|

This allows InEpsilonT to work naturally across the full numeric range including zero.

Usage

assertions.InEpsilon(t, 100.0, 101.0, 0.02)

Examples

success: 100.0, 101.0, 0.02
failure: 100.0, 110.0, 0.05

func IsDecreasing

func IsDecreasing(t T, collection any, msgAndArgs ...any) bool

IsDecreasing asserts that the collection is strictly decreasing.

Usage

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

Examples

success: []int{3, 2, 1}
failure: []int{1, 2, 3}

func IsDecreasingT added in v2.2.0

func IsDecreasingT[OrderedSlice ~[]E, E Ordered](t T, collection OrderedSlice, msgAndArgs ...any) bool

IsDecreasingT asserts that a slice of Ordered is strictly decreasing.

Usage

assertions.IsDecreasingT(t, []int{2, 1, 0})
assertions.IsDecreasingT(t, []float{2, 1})
assertions.IsDecreasingT(t, []string{"b", "a"})

Examples

success: []int{3, 2, 1}
failure: []int{1, 2, 3}

func IsIncreasing

func IsIncreasing(t T, collection any, msgAndArgs ...any) bool

IsIncreasing asserts that the collection is strictly increasing.

Usage

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

Examples

success: []int{1, 2, 3}
failure: []int{1, 1, 2}

func IsIncreasingT added in v2.2.0

func IsIncreasingT[OrderedSlice ~[]E, E Ordered](t T, collection OrderedSlice, msgAndArgs ...any) bool

IsIncreasingT asserts that a slice of Ordered is strictly increasing.

Usage

assertions.IsIncreasingT(t, []int{1, 2, 3})
assertions.IsIncreasingT(t, []float{1, 2})
assertions.IsIncreasingT(t, []string{"a", "b"})

Examples

success: []int{1, 2, 3}
failure: []int{1, 1, 2}

func IsNonDecreasing

func IsNonDecreasing(t T, collection any, msgAndArgs ...any) bool

IsNonDecreasing asserts that the collection is not strictly decreasing.

Usage

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

Examples

success: []int{1, 1, 2}
failure: []int{2, 1, 0}

func IsNonDecreasingT added in v2.2.0

func IsNonDecreasingT[OrderedSlice ~[]E, E Ordered](t T, collection OrderedSlice, msgAndArgs ...any) bool

IsNonDecreasingT asserts that a slice of Ordered is not decreasing.

Usage

assertions.IsNonDecreasingT(t, []int{1, 1, 2})
assertions.IsNonDecreasingT(t, []float{1, 2})
assertions.IsNonDecreasingT(t, []string{"a", "b"})

Examples

success: []int{1, 1, 2}
failure: []int{2, 1, 0}

func IsNonIncreasing

func IsNonIncreasing(t T, collection any, msgAndArgs ...any) bool

IsNonIncreasing asserts that the collection is not increasing.

Usage

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

Examples

success: []int{2, 1, 1}
failure: []int{1, 2, 3}

func IsNonIncreasingT added in v2.2.0

func IsNonIncreasingT[OrderedSlice ~[]E, E Ordered](t T, collection OrderedSlice, msgAndArgs ...any) bool

IsNonIncreasingT asserts that a slice of Ordered is NOT strictly increasing.

Usage

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

Examples

success: []int{2, 1, 1}
failure: []int{1, 2, 3}

func IsNotOfTypeT added in v2.2.0

func IsNotOfTypeT[EType any](t T, object any, msgAndArgs ...any) bool

IsNotOfTypeT asserts that an object is of a given type.

Usage

assertions.IsOfType[MyType](t,myVar)

Examples

success: 123.123
failure: myType(123.123)

func IsNotType

func IsNotType(t T, theType, object any, msgAndArgs ...any) bool

IsNotType asserts that the specified objects are not of the same type.

Usage

assertions.IsNotType(t, &NotMyStruct{}, &MyStruct{})

Examples

success: int32(123), int64(456)
failure: 123, 456

func IsOfTypeT added in v2.2.0

func IsOfTypeT[EType any](t T, object any, msgAndArgs ...any) bool

IsOfTypeT asserts that an object is of a given type.

Usage

assertions.IsOfTypeT[MyType](t,myVar)

Examples

success: myType(123.123)
failure: 123.123

func IsType

func IsType(t T, expectedType, object any, msgAndArgs ...any) bool

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

Usage

assertions.IsType(t, &MyStruct{}, &MyStruct{})

Examples

success: 123, 456
failure: int32(123), int64(456)

func JSONEq

func JSONEq(t T, expected, actual string, msgAndArgs ...any) bool

JSONEq asserts that two JSON strings are equivalent.

Expected and actual must be valid JSON.

Usage

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

Examples

success: `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`
failure: `{"hello": "world", "foo": "bar"}`, `[{"foo": "bar"}, {"hello": "world"}]`

func JSONEqBytes

func JSONEqBytes(t T, expected, actual []byte, msgAndArgs ...any) bool

JSONEqBytes asserts that two JSON slices of bytes are equivalent.

Expected and actual must be valid JSON.

Usage

assertions.JSONEqBytes(t, []byte(`{"hello": "world", "foo": "bar"}`), []byte(`{"foo": "bar", "hello": "world"}`))

Examples

success: []byte(`{"hello": "world", "foo": "bar"}`), []byte(`{"foo": "bar", "hello": "world"}`)
failure: []byte(`{"hello": "world", "foo": "bar"}`), []byte(`[{"foo": "bar"}, {"hello": "world"}]`)

func JSONEqT added in v2.2.0

func JSONEqT[EDoc, ADoc Text](t T, expected EDoc, actual ADoc, msgAndArgs ...any) bool

JSONEqT asserts that two JSON documents are equivalent.

The expected and actual arguments may be string or []byte. They do not need to be of the same type.

Expected and actual must be valid JSON.

Usage

assertions.JSONEqT(t, `{"hello": "world", "foo": "bar"}`, []byte(`{"foo": "bar", "hello": "world"}`))

Examples

success: `{"hello": "world", "foo": "bar"}`, []byte(`{"foo": "bar", "hello": "world"}`)
failure: `{"hello": "world", "foo": "bar"}`, `[{"foo": "bar"}, {"hello": "world"}]`

func Kind added in v2.2.0

func Kind(t T, expectedKind reflect.Kind, object any, msgAndArgs ...any) bool

Kind asserts that the reflect.Kind of a given object matches the expected reflect.Kind.

Kind reflects the concrete value stored in the object. The nil value (or interface with nil value) are comparable to reflect.Invalid. See also reflect.Value.Kind.

Usage

assertions.Kind(t, reflect.String, "Hello World")

Examples

success: reflect.String, "hello"
failure: reflect.String, 0

func Len

func Len(t T, object any, length int, msgAndArgs ...any) bool

Len asserts that the specified object has specific length.

Len also fails if the object has a type that len() does not accept.

The asserted object can be a string, a slice, a map, an array or a channel.

See also reflect.Len.

Usage

assertions.Len(t, mySlice, 3)
assertions.Len(t, myString, 4)
assertions.Len(t, myMap, 5)

Examples

success: []string{"A","B"}, 2
failure: []string{"A","B"}, 1

func Less

func Less(t T, e1 any, e2 any, msgAndArgs ...any) bool

Less asserts that the first element is strictly less than the second.

Both elements must be of the same type in the reflect.Kind sense. To compare values that need a type conversion (e.g. float32 against float64), you need to convert types beforehand.

Usage

assertions.Less(t, 1, 2)
assertions.Less(t, float64(1), float64(2))
assertions.Less(t, "a", "b")

Examples

success: 1, 2
failure: 2, 1

func LessOrEqual

func LessOrEqual(t T, e1 any, e2 any, msgAndArgs ...any) bool

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

Usage

assertions.LessOrEqual(t, 1, 2)
assertions.LessOrEqual(t, 2, 2)
assertions.LessOrEqual(t, "a", "b")
assertions.LessOrEqual(t, "b", "b")

Examples

success: 1, 2
failure: 2, 1

func LessOrEqualT added in v2.2.0

func LessOrEqualT[Orderable Ordered](t T, e1, e2 Orderable, msgAndArgs ...any) bool

LessOrEqualT asserts that for two elements of the same type, the first element is less than or equal to the second.

The Ordered type can be any of Go's cmp.Ordered (strings, numeric types), []byte (uses bytes.Compare) and time.Time (uses time.Time.Compare.

Notice that pointers are not Ordered, but uintptr are. So you can't call LessOrEqualT with *time.Time.

LessOrEqualT ensures type safety at build time. If you need to compare values with a dynamically assigned type, use LessOrEqual instead.

To compare values that need a type conversion (e.g. float32 against float64), you should use LessOrEqual instead.

Usage

assertions.LessOrEqualT(t, 1, 2)
assertions.LessOrEqualT(t, 2, 2)
assertions.LessOrEqualT(t, "a", "b")
assertions.LessOrEqualT(t, "b", "b")

Examples

success: 1, 2
failure: 2, 1

func LessT added in v2.2.0

func LessT[Orderable Ordered](t T, e1, e2 Orderable, msgAndArgs ...any) bool

LessT asserts that for two elements of the same type, the first element is strictly less than the second.

The Ordered type can be any of Go's cmp.Ordered (strings, numeric types), []byte (uses bytes.Compare) and time.Time (uses time.Time.Compare.

Notice that pointers are not Ordered, but uintptr are. So you can't call LessT with *time.Time.

LessT ensures type safety at build time. If you need to compare values with a dynamically assigned type, use Less instead.

To compare values that need a type conversion (e.g. float32 against float64), you need to convert types beforehand.

Usage

assertions.LessT(t, 1, 2)
assertions.LessT(t, float64(1), float64(2))
assertions.LessT(t, "a", "b")

Examples

success: 1, 2
failure: 2, 1

func MapContainsT added in v2.2.0

func MapContainsT[Map ~map[K]V, K comparable, V any](t T, m Map, key K, msgAndArgs ...any) bool

MapContainsT asserts that the specified map contains a key.

Usage

assertions.MapContainsT(t, map[string]string{"Hello": "x","World": "y"}, "World")

Examples

success: map[string]string{"A": "B"}, "A"
failure: map[string]string{"A": "B"}, "C"

func MapNotContainsT added in v2.2.0

func MapNotContainsT[Map ~map[K]V, K comparable, V any](t T, m Map, key K, msgAndArgs ...any) bool

MapNotContainsT asserts that the specified map does not contain a key.

Usage

assertions.MapNotContainsT(t, map[string]string{"Hello": "x","World": "y"}, "hi")

Examples

success: map[string]string{"A": "B"}, "C"
failure: map[string]string{"A": "B"}, "A"

func Negative

func Negative(t T, e any, msgAndArgs ...any) bool

Negative asserts that the specified element is strictly negative.

Usage

assertions.Negative(t, -1)
assertions.Negative(t, -1.23)

Examples

success: -1
failure: 1

func NegativeT added in v2.2.0

func NegativeT[SignedNumber SignedNumeric](t T, e SignedNumber, msgAndArgs ...any) bool

NegativeT asserts that the specified element of a signed numeric type is strictly negative.

Usage

assertions.NegativeT(t, -1)
assertions.NegativeT(t, -1.23)

Examples

success: -1
failure: 1

func Never

func Never(t T, condition func() bool, waitFor time.Duration, tick time.Duration, msgAndArgs ...any) bool

Never asserts that the given condition is never satisfied within waitFor time, periodically checking the target function at each tick.

Never is the opposite of Eventually. It succeeds if the waitFor timeout is reached without the condition ever returning true.

If the parent context is cancelled before the timeout, Never fails.

Usage

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

Concurrency

The condition function is never executed in parallel: only one goroutine executes it. It may write to variables outside its scope without triggering race conditions.

A blocking condition will cause Never to hang until it returns.

Examples

success:  func() bool { return false }, 100*time.Millisecond, 20*time.Millisecond
failure:  func() bool { return true }, 100*time.Millisecond, 20*time.Millisecond

func Nil

func Nil(t T, object any, msgAndArgs ...any) bool

Nil asserts that the specified object is nil.

Usage

assertions.Nil(t, err)

Examples

success: nil
failure: "not nil"

func NoError

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

NoError asserts that a function returned a nil error (ie. no error).

Usage

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

Examples

success: nil
failure: ErrTest

func NotContains

func NotContains(t T, s, contains any, msgAndArgs ...any) bool

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

Usage

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

Examples

success: []string{"A","B"}, "C"
failure: []string{"A","B"}, "B"

func NotElementsMatch

func NotElementsMatch(t T, listA, listB any, msgAndArgs ...any) (ok bool)

NotElementsMatch asserts that the specified listA(array, slice...) is NOT 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 not match. This is an inverse of ElementsMatch.

Usage

assertions.NotElementsMatch(t, []int{1, 1, 2, 3}, []int{1, 1, 2, 3}) -> false
assertions.NotElementsMatch(t, []int{1, 1, 2, 3}, []int{1, 2, 3}) -> true
assertions.NotElementsMatch(t, []int{1, 2, 3}, []int{1, 2, 4}) -> true

Examples

success: []int{1, 2, 3}, []int{1, 2, 4}
failure: []int{1, 3, 2, 3}, []int{1, 3, 3, 2}

func NotElementsMatchT added in v2.2.0

func NotElementsMatchT[E comparable](t T, listA, listB []E, msgAndArgs ...any) (ok bool)

NotElementsMatchT asserts that the specified listA(array, slice...) is NOT 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 not match. This is an inverse of ElementsMatch.

Usage

assertions.NotElementsMatchT(t, []int{1, 1, 2, 3}, []int{1, 1, 2, 3}) -> false
assertions.NotElementsMatchT(t, []int{1, 1, 2, 3}, []int{1, 2, 3}) -> true
assertions.NotElementsMatchT(t, []int{1, 2, 3}, []int{1, 2, 4}) -> true

Examples

success: []int{1, 2, 3}, []int{1, 2, 4}
failure: []int{1, 3, 2, 3}, []int{1, 3, 3, 2}

func NotEmpty

func NotEmpty(t T, object any, msgAndArgs ...any) bool

NotEmpty asserts that the specified object is NOT Empty.

Usage

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

Examples

success: "not empty"
failure: ""

func NotEqual

func NotEqual(t T, expected, actual any, msgAndArgs ...any) bool

NotEqual asserts that the specified values are NOT equal.

Usage

assertions.NotEqual(t, obj1, obj2)

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.

Examples

success: 123, 456
failure: 123, 123

func NotEqualT added in v2.2.0

func NotEqualT[V comparable](t T, expected, actual V, msgAndArgs ...any) bool

NotEqualT asserts that the specified values of the same comparable type are NOT equal.

See EqualT.

Usage

assertions.NotEqualT(t, obj1, obj2)

Examples

success: 123, 456
failure: 123, 123

func NotEqualValues

func NotEqualValues(t T, expected, actual any, msgAndArgs ...any) bool

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

Function equality cannot be determined and will always fail.

Usage

assertions.NotEqualValues(t, obj1, obj2)

Examples

success: uint32(123), int32(456)
failure: uint32(123), int32(123)

func NotErrorAs

func NotErrorAs(t T, err error, target any, msgAndArgs ...any) bool

NotErrorAs asserts that none of the errors in err's chain matches target, but if so, sets target to that error value.

Usage

assertions.NotErrorAs(t, err, &target)

Examples

success: ErrTest, new(*dummyError)
failure: fmt.Errorf("wrap: %w", &dummyError{}), new(*dummyError)

func NotErrorIs

func NotErrorIs(t T, err, target error, msgAndArgs ...any) bool

NotErrorIs asserts that none of the errors in err's chain matches target.

This is a wrapper for errors.Is.

Usage

assertions.NotErrorIs(t, err, io.EOF)

Examples

success: ErrTest, io.EOF
failure: fmt.Errorf("wrap: %w", io.EOF), io.EOF

func NotImplements

func NotImplements(t T, interfaceObject any, object any, msgAndArgs ...any) bool

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

Usage

assertions.NotImplements(t, (*MyInterface)(nil), new(MyObject))

Examples

success: (*error)(nil), new(testing.T)
failure: ptr(dummyInterface), new(testing.T)

func NotKind added in v2.2.0

func NotKind(t T, expectedKind reflect.Kind, object any, msgAndArgs ...any) bool

NotKind asserts that the reflect.Kind of a given object does not match the expected reflect.Kind.

Kind reflects the concrete value stored in the object. The nil value (or interface with nil value) are comparable to reflect.Invalid. See also reflect.Value.Kind.

Usage

assertions.NotKind(t, reflect.Int, "Hello World")

Examples

success: reflect.String, 0
failure: reflect.String, "hello"

func NotNil

func NotNil(t T, object any, msgAndArgs ...any) bool

NotNil asserts that the specified object is not nil.

Usage

assertions.NotNil(t, err)

Examples

success: "not nil"
failure: nil

func NotPanics

func NotPanics(t T, f PanicTestFunc, msgAndArgs ...any) bool

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

Usage

assertions.NotPanics(t, func(){ RemainCalm() })

Examples

success: func() { }
failure: func() { panic("panicking") }

func NotRegexp

func NotRegexp(t T, rx any, actual any, msgAndArgs ...any) bool

NotRegexp asserts that a specified regular expression does not match a string.

See Regexp.

Usage

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

Examples

success: "^start", "not starting"
failure: "^start", "starting"

func NotRegexpT added in v2.2.0

func NotRegexpT[Rex RegExp, ADoc Text](t T, rx Rex, actual ADoc, msgAndArgs ...any) bool

NotRegexpT asserts that a specified regular expression does not match a string.

See RegexpT.

Usage

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

Examples

success: "^start", "not starting"
failure: "^start", "starting"

func NotSame

func NotSame(t T, expected, actual any, msgAndArgs ...any) bool

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

See Same.

Usage

assertions.NotSame(t, ptr1, ptr2)

Examples

success: &staticVar, ptr("static string")
failure: &staticVar, staticVarPtr

func NotSameT added in v2.2.0

func NotSameT[P any](t T, expected, actual *P, msgAndArgs ...any) bool

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

See SameT.

Usage

assertions.NotSameT(t, ptr1, ptr2)

Examples

success: &staticVar, ptr("static string")
failure: &staticVar, staticVarPtr

func NotSortedT added in v2.2.0

func NotSortedT[OrderedSlice ~[]E, E Ordered](t T, collection OrderedSlice, msgAndArgs ...any) bool

NotSortedT asserts that the slice of Ordered is NOT sorted (i.e. non-strictly increasing).

Unlike IsDecreasingT, it accepts slices that are neither increasing nor decreasing.

Usage

assertions.NotSortedT(t, []int{3, 2, 3})
assertions.NotSortedT(t, []float{2, 1})
assertions.NotSortedT(t, []string{"b", "a"})

Examples

success: []int{3, 1, 3}
failure: []int{1, 4, 8}

func NotSubset

func NotSubset(t T, list, subset any, msgAndArgs ...any) (ok bool)

NotSubset asserts that the list (array, slice, or map) does NOT contain all elements given in the subset (array, slice, or map). Map elements are key-value pairs unless compared with an array or slice where only the map key is evaluated.

Usage

assertions.NotSubset(t, [1, 3, 4], [1, 2])
assertions.NotSubset(t, {"x": 1, "y": 2}, {"z": 3})
assertions.NotSubset(t, [1, 3, 4], {1: "one", 2: "two"})
assertions.NotSubset(t, {"x": 1, "y": 2}, ["z"])

Examples

success: []int{1, 2, 3}, []int{4, 5}
failure: []int{1, 2, 3}, []int{1, 2}

func NotZero

func NotZero(t T, i any, msgAndArgs ...any) bool

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

Usage

assertions.NotZero(t, obj)

Examples

success: 1
failure: 0

func ObjectsAreEqual

func ObjectsAreEqual(expected, actual any) bool

ObjectsAreEqual determines if two objects are considered equal.

This function does no assertion of any kind.

func ObjectsAreEqualValues

func ObjectsAreEqualValues(expected, actual any) bool

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

func Panics

func Panics(t T, f PanicTestFunc, msgAndArgs ...any) bool

Panics asserts that the code inside the specified PanicTestFunc panics.

Usage

assertions.Panics(t, func(){ GoCrazy() })

Examples

success: func() { panic("panicking") }
failure: func() { }

func PanicsWithError

func PanicsWithError(t T, errString string, f PanicTestFunc, msgAndArgs ...any) bool

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

Usage

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

Examples

success: ErrTest.Error(), func() { panic(ErrTest) }
failure: ErrTest.Error(), func() { }

func PanicsWithValue

func PanicsWithValue(t T, expected any, f PanicTestFunc, msgAndArgs ...any) bool

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

Usage

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

Examples

success: "panicking", func() { panic("panicking") }
failure: "panicking", func() { }

func Positive

func Positive(t T, e any, msgAndArgs ...any) bool

Positive asserts that the specified element is strictly positive.

Usage

assertions.Positive(t, 1)
assertions.Positive(t, 1.23)

Examples

success: 1
failure: -1

func PositiveT added in v2.2.0

func PositiveT[SignedNumber SignedNumeric](t T, e SignedNumber, msgAndArgs ...any) bool

PositiveT asserts that the specified element of a signed numeric type is strictly positive.

Usage

assertions.PositiveT(t, 1)
assertions.PositiveT(t, 1.23)

Examples

success: 1
failure: -1

func Regexp

func Regexp(t T, rx any, actual any, msgAndArgs ...any) bool

Regexp asserts that a specified regular expression matches a string.

The regular expression may be passed as a regexp.Regexp, a string or a []byte and will be compiled.

The actual argument to be matched may be a string, []byte or anything that prints as a string with fmt.Sprint.

Usage

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

Examples

success: "^start", "starting"
failure: "^start", "not starting"

func RegexpT added in v2.2.0

func RegexpT[Rex RegExp, ADoc Text](t T, rx Rex, actual ADoc, msgAndArgs ...any) bool

RegexpT asserts that a specified regular expression matches a string.

The actual argument to be matched may be a string or []byte.

See Regexp.

Examples

success: "^start", "starting"
failure: "^start", "not starting"

func Same

func Same(t T, expected, actual any, msgAndArgs ...any) bool

Same asserts that two pointers reference the same object.

Both arguments must be pointer variables.

Pointer variable sameness is determined based on the equality of both type and value.

Unlike Equal pointers, Same pointers point to the same memory address.

Usage

assertions.Same(t, ptr1, ptr2)

Examples

success: &staticVar, staticVarPtr
failure: &staticVar, ptr("static string")

func SameT added in v2.2.0

func SameT[P any](t T, expected, actual *P, msgAndArgs ...any) bool

SameT asserts that two pointers of the same type reference the same object.

See Same.

Usage

assertions.SameT(t, ptr1, ptr2)

Examples

success: &staticVar, staticVarPtr
failure: &staticVar, ptr("static string")

func SeqContainsT added in v2.2.0

func SeqContainsT[E comparable](t T, iter iter.Seq[E], element E, msgAndArgs ...any) bool

SeqContainsT asserts that the specified iterator contains a comparable element.

Usage

assertions.SeqContainsT(t, slices.Values([]{"Hello","World"}), "World")

Examples

success: slices.Values([]string{"A","B"}), "A"
failure: slices.Values([]string{"A","B"}), "C"

func SeqNotContainsT added in v2.2.0

func SeqNotContainsT[E comparable](t T, iter iter.Seq[E], element E, msgAndArgs ...any) bool

SeqNotContainsT asserts that the specified iterator does not contain a comparable element.

Usage

assertions.SeqContainsT(t, slices.Values([]{"Hello","World"}), "World")

Examples

success: slices.Values([]string{"A","B"}), "C"
failure: slices.Values([]string{"A","B"}), "A"

func SliceContainsT added in v2.2.0

func SliceContainsT[Slice ~[]E, E comparable](t T, s Slice, element E, msgAndArgs ...any) bool

SliceContainsT asserts that the specified slice contains a comparable element.

Usage

assertions.SliceContainsT(t, []{"Hello","World"}, "World")

Examples

success: []string{"A","B"}, "A"
failure: []string{"A","B"}, "C"

func SliceNotContainsT added in v2.2.0

func SliceNotContainsT[Slice ~[]E, E comparable](t T, s Slice, element E, msgAndArgs ...any) bool

SliceNotContainsT asserts that the specified slice does not contain a comparable element.

Usage

assertions.SliceNotContainsT(t, []{"Hello","World"}, "hi")

Examples

success: []string{"A","B"}, "C"
failure: []string{"A","B"}, "A"

func SliceNotSubsetT added in v2.2.0

func SliceNotSubsetT[Slice ~[]E, E comparable](t T, list, subset Slice, msgAndArgs ...any) (ok bool)

SliceNotSubsetT asserts that a slice of comparable elements does not contain all the elements given in the subset.

Usage

assertions.SliceNotSubsetT(t, []int{1, 2, 3}, []int{1, 4})

Examples

success: []int{1, 2, 3}, []int{4, 5}
failure: []int{1, 2, 3}, []int{1, 2}

func SliceSubsetT added in v2.2.0

func SliceSubsetT[Slice ~[]E, E comparable](t T, list, subset Slice, msgAndArgs ...any) (ok bool)

SliceSubsetT asserts that a slice of comparable elements contains all the elements given in the subset.

Usage

assertions.SliceSubsetT(t, []int{1, 2, 3}, []int{1, 2})

Examples

success: []int{1, 2, 3}, []int{1, 2}
failure: []int{1, 2, 3}, []int{4, 5}

func SortedT added in v2.2.0

func SortedT[OrderedSlice ~[]E, E Ordered](t T, collection OrderedSlice, msgAndArgs ...any) bool

SortedT asserts that the slice of Ordered is sorted (i.e. non-strictly increasing).

Unlike IsIncreasingT, it accepts elements to be equal.

Usage

assertions.SortedT(t, []int{1, 2, 3})
assertions.SortedT(t, []float{1, 2})
assertions.SortedT(t, []string{"a", "b"})

Examples

success: []int{1, 1, 3}
failure: []int{1, 4, 2}

func StringContainsT added in v2.2.0

func StringContainsT[ADoc, EDoc Text](t T, str ADoc, substring EDoc, msgAndArgs ...any) bool

StringContainsT asserts that a string contains the specified substring.

Strings may be go strings or []byte.

Usage

assertions.StringContainsT(t, "Hello World", "World")

Examples

success: "AB", "A"
failure: "AB", "C"

func StringNotContainsT added in v2.2.0

func StringNotContainsT[ADoc, EDoc Text](t T, str ADoc, substring EDoc, msgAndArgs ...any) bool

StringNotContainsT asserts that a string does not contain the specified substring.

Strings may be go strings or []byte.

Usage

assertions.StringNotContainsT(t, "Hello World", "hi")

Examples

success: "AB", "C"
failure: "AB", "A"

func Subset

func Subset(t T, list, subset any, msgAndArgs ...any) (ok bool)

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

Map elements are key-value pairs unless compared with an array or slice where only the map key is evaluated.

Usage

assertions.Subset(t, []int{1, 2, 3}, []int{1, 2})
assertions.Subset(t, []string{"x": 1, "y": 2}, []string{"x": 1})
assertions.Subset(t, []int{1, 2, 3}, map[int]string{1: "one", 2: "two"})
assertions.Subset(t, map[string]int{"x": 1, "y": 2}, []string{"x"})

Examples

success: []int{1, 2, 3}, []int{1, 2}
failure: []int{1, 2, 3}, []int{4, 5}

func True

func True(t T, value bool, msgAndArgs ...any) bool

True asserts that the specified value is true.

Usage

assertions.True(t, myBool)

Examples

success: 1 == 1
failure: 1 == 0

func TrueT added in v2.2.0

func TrueT[B Boolean](t T, value B, msgAndArgs ...any) bool

TrueT asserts that the specified value is true.

Usage

type B bool
var b B = true

assertions.True(t, b)

Examples

success: 1 == 1
failure: 1 == 0

func WithinDuration

func WithinDuration(t T, expected, actual time.Time, delta time.Duration, msgAndArgs ...any) bool

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

Usage

assertions.WithinDuration(t, time.Now(), 10*time.Second)

Examples

success: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC), time.Date(2024, 1, 1, 12, 0, 1, 0, time.UTC), 2*time.Second
failure: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC), time.Date(2024, 1, 1, 12, 0, 10, 0, time.UTC), 1*time.Second

func WithinRange

func WithinRange(t T, actual, start, end time.Time, msgAndArgs ...any) bool

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

Usage

assertions.WithinRange(t, time.Now(), time.Now().Add(-time.Second), time.Now().Add(time.Second))

Examples

success: time.Date(2024, 1, 1, 12, 0, 0, 0, time.UTC), time.Date(2024, 1, 1, 11, 0, 0, 0, time.UTC), time.Date(2024, 1, 1, 13, 0, 0, 0, time.UTC)
failure: time.Date(2024, 1, 1, 14, 0, 0, 0, time.UTC), time.Date(2024, 1, 1, 11, 0, 0, 0, time.UTC), time.Date(2024, 1, 1, 13, 0, 0, 0, time.UTC)

func YAMLEq

func YAMLEq(t T, expected, actual string, msgAndArgs ...any) bool

YAMLEq asserts that two YAML strings are equivalent.

See YAMLEqBytes.

Examples

panic: "key: value", "key: value"
should panic without the yaml feature enabled.

func YAMLEqBytes added in v2.2.0

func YAMLEqBytes(t T, expected, actual []byte, msgAndArgs ...any) bool

YAMLEqBytes asserts that two YAML slices of bytes are equivalent.

Expected and actual must be valid YAML.

Important

By default, this function is disabled and will panic.

To enable it, you should add a blank import like so:

import(
  "github.com/go-openapi/testify/enable/yaml/v2"
)

Usage

expected := `---
key: value
---
key: this is a second document, it is not evaluated
`
actual := `---
key: value
---
key: this is a subsequent document, it is not evaluated
`
assertions.YAMLEq(t, expected, actual)

Examples

panic: []byte("key: value"), []byte("key: value")
should panic without the yaml feature enabled.

func YAMLEqT added in v2.2.0

func YAMLEqT[EDoc, ADoc Text](t T, expected EDoc, actual ADoc, msgAndArgs ...any) bool

YAMLEqT asserts that two YAML documents are equivalent.

The expected and actual arguments may be string or []byte. They do not need to be of the same type.

See YAMLEqBytes.

Examples

panic: "key: value", "key: value"
should panic without the yaml feature enabled.

func Zero

func Zero(t T, i any, msgAndArgs ...any) bool

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

Usage

assertions.Zero(t, obj)

Examples

success: 0
failure: 1

Types

type Assertions

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

Assertions provides assertion methods around the T interface.

func New

func New(t T) *Assertions

New makes a new Assertions object for the specified T.

type BoolAssertionFunc

type BoolAssertionFunc func(T, bool, ...any) bool

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

type Boolean added in v2.2.0

type Boolean interface {
	~bool
}

Boolean is a bool or any type that can be converted to a bool.

type CollectT

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

CollectT implements the T interface and collects all errors.

CollectT is specifically intended to be used with EventuallyWithT and should not be used outside of that context.

func (*CollectT) Errorf

func (c *CollectT) Errorf(format string, args ...any)

Errorf collects the error.

func (*CollectT) FailNow

func (c *CollectT) FailNow()

FailNow records a failure and cancels the parent EventuallyWithT context, before exiting the current go routine with runtime.Goexit.

This causes the assertion to fail immediately without waiting for a timeout.

func (*CollectT) Helper

func (*CollectT) Helper()

Helper is like testing.T.Helper but does nothing.

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(T, any, any, ...any) bool

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

type ErrorAssertionFunc

type ErrorAssertionFunc func(T, error, ...any) bool

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

type H

type H interface {
	Helper()
}

H is an interface for types that implement the Helper method. This allows marking functions as test helpers, e.g. testing.T.Helper.

type Measurable added in v2.2.0

type Measurable interface {
	SignedNumeric | UnsignedNumeric | ~float32 | ~float64
}

Measurable is any number for which we can compute a delta (floats or integers).

This is used by InDeltaT and InEpsilonT.

NOTE: unfortunately complex64 and complex128 are not supported.

type Ordered added in v2.2.0

type Ordered interface {
	cmp.Ordered | []byte | time.Time
}

Ordered is a standard ordered type (i.e. types that support "<": cmp.Ordered) plus []byte and time.Time.

This is used by GreaterT, GreaterOrEqualT, LessT, LessOrEqualT, IsIncreasingT, IsDecreasingT.

NOTE: since time.Time is a struct, custom types which redeclare time.Time are not supported.

type PanicAssertionFunc

type PanicAssertionFunc func(t T, f PanicTestFunc, msgAndArgs ...any) bool

PanicAssertionFunc is a common function prototype when validating a panic 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 RegExp added in v2.2.0

type RegExp interface {
	Text | *regexp.Regexp
}

RegExp is either a text containing a regular expression to compile (string or []byte), or directly the compiled regexp.

This is used by RegexpT and NotRegexpT.

type SignedNumeric added in v2.2.0

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

SignedNumeric is a signed integer or a floating point number or any type that can be converted to one of these.

type T

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

T is an interface wrapper around testing.T.

type Text added in v2.2.0

type Text interface {
	~string | ~[]byte
}

Text is any type of underlying type string or []byte.

This is used by RegexpT, NotRegexpT, JSONEqT, and YAMLEqT.

NOTE: unfortunately, []rune is not supported.

type UnsignedNumeric added in v2.2.0

type UnsignedNumeric interface {
	~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}

UnsignedNumeric is an unsigned integer.

NOTE: there are no unsigned floating point numbers.

type ValueAssertionFunc

type ValueAssertionFunc func(T, any, ...any) bool

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

Directories

Path Synopsis
Package enable allows to register extra features.
Package enable allows to register extra features.
yaml
Package yaml is an indirection to handle YAML deserialization.
Package yaml is an indirection to handle YAML deserialization.
Package unsafetests exists only to isolate tests that reference the unsafe package.
Package unsafetests exists only to isolate tests that reference the unsafe package.

Jump to

Keyboard shortcuts

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