expect

package module
v1.0.8 Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2026 License: MIT Imports: 12 Imported by: 1

README

expect

GoDoc Go Report Card Build Coverage Issues

Simple easy-to-use assertions to use in Go tests.

  • Fluent API
  • Clear error messages
  • Works with Go testing API
  • Also works independently
  • Type safety thanks to Go generics
  • No dependencies other than github.com/google/go-cmp

Assertion Categories

There are eight primary categories, each introduce by a function:

expect.Any(actual ...) | expect.Value(actual ...)

This compares equality for values of any type, but is especially useful for structs, maps, arrays, and slices. It only provides equality tests; the other seven categories below provide a much wider range.

  • If the value under test is of a type with a method a.Equal(b) (a and b having the same type), then the Equal method will be used. So this compares types such as time.Time correctly.

  • Otherwise it behaves like reflect.DeepEqual.

The Any function is an alias of Value; use whichever you prefer.

expect.String(actual ...)

This compares string and any subclass. It is more informative than Any, highlighting where the differences start.

expect.Number(actual ...)

This compares int and all the signed/unsigned int and float length variants, plus all their subtypes. This provides inequality comparisons. It also supports string because that is also is an ordered type.

However, for near-equality testing of float32 or float64, use Any instead because the tolerance can be specified.

expect.Bool(actual ...)

This compares bool and any subclass.

expect.Map(actual ...)

This compares map[K]V where the map key K is a comparable type.

Map provides more methods than Any, but is otherwise very similar.

expect.Slice(actual ...)

This compares []T where T is any type.

Slice provides more methods than Any, but is otherwise very similar.

expect.Error(... actual)

This compares error only.

expect.Func(func)

This runs some function and checks whether it panicked.

Application

The eight primary functions above all take the actual value under test as their input.

Other parameters can also be passed in. If any of these other parameters is a non-nil error, the assertion will fail and give a corresponding error message. Any other parameters are ignored; this includes any nil error.

Error is slightly different - it considers the last non-nil error as its actual input. Any other parameters are ignored; this includes any nil error.

In particular, this allows the input to be a function with a multi-value return.

Assertions

The assertions are all infinitive verbs, i.e. methods such as ToBe. Typical use is of the form

    expect.Value(myValue).ToBe(t, expectedValue)
expect.String(myValue).ToBe(t, expectedValue)
expect.Number(myValue).ToBe(t, expectedValue)
expect.Bool(myValue).ToBe(t, expectedValue)
expect.Map(myValue).ToBe(t, expectedValue)
expect.Slice(myValue).ToBe(t, expectedValue)
expect.Error(myValue).ToBeNil(t)
expect.Func(myFunc).ToPanic(t)

All of the assertions require a t Tester parameter (see Tester). Normally this will be *testing.T but you can use your own type if you need to embed this API in other assertion logic.

The assertions available are intended to be obvious to use because they relate to the type being tested. They are as follows.

Value String Number Bool Map Slice Error Func
ToBe Yes Yes Yes Yes Yes Yes - -
ToEqual Yes Yes Yes Yes - - - -
ToBeNil Yes - - - Yes Yes Yes -
ToBeEmpty - Yes - - Yes Yes - -
ToHaveLength - Yes - - Yes Yes - -
ToContain - Yes - - Yes Yes Yes -
ToContainAll - - - - Yes Yes - -
ToContainAny - - - - Yes Yes - -
ToMatch - Yes - - - - Yes -
ToBeTrue - - - Yes - - - -
ToBeFalse - - - Yes - - - -
ToBeGreaterThan - - Yes - - - - -
ToBeGreaterThanOrEqual - - Yes - - - - -
ToBeLessThan - - Yes - - - - -
ToBeLessThanOrEqual - - Yes - - - - -
ToBeBetween - - Yes - - - - -
ToBeBetweenOrEqual - - Yes - - - - -
ToHaveOccurred - - - - - - Yes -
ToPanic - - - - - - - Yes
ToPanicWithMessage - - - - - - - Yes

Many categories have

  • ToBe(t, expected) tests for equality, whereas
  • ToEqual(t, expected) tests for equality ignoring whether the concrete types match or not - ToBe should be preferred but ToEqual is sometimes more convenient

Another group of related assertions is

  • ToBeNil(t) verifies that the actual value is a nil pointer
  • ToBeEmpty(t) verifies that the actual value has zero size
  • ToHaveLength(t, length) verifies that the length of the actual value is as specified.

Containment tests are achieved using

  • ToContain(t, substring) verifies that the substring is included within the actual string or error message. Maps are special: they can have an optional value, so ToContain(t, key, [value]) tests that the key is present and that the the value, if present, must match what is held in the map.
  • ToContainAll(t, ...) verifies that all the values are present, in any order
  • ToContainAny(t, ...) verifies that any of the values is present
  • ToMatch(t, ...) verifies that the string matches a regular expression

Boolean shorthands are

  • ToBeTrue(t) is the same as ToBe(t, true)
  • ToBeFalse(t) is the same as ToBe(t, false)

Numeric inequalities are

  • ToBeGreaterThan(t, threshold) i.e. actual > threshold
  • ToBeGreaterThanOrEqual(t, threshold) i.e. actual >= threshold
  • ToBeLessThan(t, threshold) i.e. actual < threshold
  • ToBeLessThanOrEqual(t, threshold) i.e. actual <= threshold
  • ToBeBetween(t, min, max) i.e. min < actual < max
  • ToBeBetweenOrEqual(t, min, max) i.e. min <= actual <= max

Note that these inequality assertions actually apply to all ordered types, which includes all int/uint types, float32/float64 and also string. All subtypes of ordered types are also included.

Errors are handled with ToHaveOccurred(t), or more typically Not().ToHaveOccurred(t) (Not() is described below). These are equivalent to Not().ToBeNil(t) and ToBeNil(t), respectively.

Functions that panic can be tested with a zero-argument function that calls the code under test and then uses ToPanic(). If panic(value) value is a string, ToPanicWithMessage(t, substring) can check the actual message.

Synonyms

For Map, ToHaveSize(t, expected) is a synonym for ToHaveLength(t, expected).

Negation Method

All categories include the general method Not(). This inverts the assertion defined by the ToXxxx method that follows it.

    // `Not()` simply negates what follows.
expect.Number(v).Not().ToBe(t, 321)

Conjunction Method

Number and String have Or() that allows multiple alternatives to be accepted.

  • If any of them succeed, the test will pass.
  • If all of them fail, the error message will list all the possibilities in the expected outcome.

There is no need for 'and' conjunctions because you simply add more assertions.

Extra Information Methods

All categories include these general methods

  • Info(...) provides information in the failure message, if there is one.
  • I(...) is a terse synonym for Info(...).
    // The `Info` method can be helpful when testing inside a loop, for example.
// If `Not()` is also used, the natural order is to put `Not()` directly before the assertion:
var i int // some loop counter
expect.Number(v).Info("loop %d", i).Not().ToBe(t, 321)

String also has Trim(n) that truncates message strings if they exceed the specified length. When an expectation fails, the actual and expected strings are chopped at the front and/or back so that the difference is visible in the failure message and the visible parts are not longer than the trim value.

    expect.String(s).Trim(100).ToContain(t, " a very very long string ")

Both the actual and expected strings are truncated if their length is too long. If there is a mis-match, the error message scrolls the truncated string to ensure that the first difference is in view.

Options for Controlling How The Comparisons Work

Any, Map, and Slice use cmp.Equal under the hood. This is flexible, allowing for options to control how the comparison proceeds - for example when considering how close floating point numbers need to be to be considered equal. There is a Using(...) method to specify what options it should use.

By default, the three options used are

  • All fields in structs are compared, regardless of whether they exported or unexported; all structs in maps and slices are treated likewise.
  • Floating point numbers are compared within the tolerance set by ApproximateFloatFraction.
  • Maps/slices that are empty are treated the same as those that are nil.

Status

This has been quite stable for some time and is available as a beta release.

Origins

This API was mostly inspired by these

  • Gomega had some great ideas but is overly complex to use.
  • Testify was essentially simple to use but lacked flexibility, possibly because the API is not fluent, and had various gotchas.

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ApproximateFloatFraction = 1e-6

ApproximateFloatFraction provides an option that compares any (a, b float32) or (a, b float64) pair. This is initialised to 1e-6, which means that a pair of floats are considered effectively equal if their fractional difference is less than one part in a million. Change this if needed. See cmpopts.EquateApprox and DefaultOptions.

If more than one argument is passed, all subsequent arguments will be required to be nil/zero. This is convenient if you want to make an assertion on a method/function that returns a value and an error, a common pattern in Go.

DefaultOptions returns options used by gocmp.Equal for comparing values. The default options

  • sets the threshold for float comparison to ApproximateFloatFraction
  • sets empty and nil maps or slices to be treated the same

You can also use AnyType.Using, MapType.Using and SliceType.Using instead.

JustLogIt is a tester that calls log.Fatalf on all test errors and failures.

Functions

This section is empty.

Types

type AnyType

type AnyType[T any] struct {
	// contains filtered or unexported fields
}

AnyType is used for equality assertions for any type.

func Any

func Any[T any](value T, other ...any) AnyType[T]

Any is an alias for Value, returning an AnyType matcher.

func Value added in v1.0.0

func Value[T any](value T, other ...any) AnyType[T]

Value creates an assertion for deep value comparison of any type. This is very flexible but only provides methods to determine whether a value is equal (or not equal) to what's expected (see AnyType.ToBe, AnyType.ToBeNil and AnyType.ToEqual).

For alternative comparisons, see the more-specialized String, Number, Bool, Slice, Map, Error and Func functions.

AnyType uses gocmp.Equal so the manner of comparison can be tweaked using that API (see AnyType.Using)

  • If the values have an Equal method of the form "(T) Equal(T) bool" or "(T) Equal(I) bool" where T is assignable to I, then it uses the result of x.Equal(y) even if x or y is nil.

  • Lastly, it tries to compare x and y based on their basic kinds. Simple kinds like booleans, integers, floats, complex numbers, strings, and channels are compared using the equivalent of the == operator in Go. Functions are only equal if they are both nil, otherwise they are unequal.

Structs are equal if recursively calling Equal on all fields report equal. All struct fields are compared and this is repeated recursively. Unless the compare options are changed, it does not matter whether fields exported on unexported.

Slices are equal if they are both nil or both non-nil, where recursively calling Equal on all non-ignored slice or array elements report equal. Unless the compare options are changed, empty non-nil slices and nil slices are equal.

Maps are equal if they are both nil or both non-nil, where recursively calling Equal on all non-ignored map entries report equal. Map keys are equal according to the == operator. To use custom comparisons for map keys, consider using github.com/google/go-cmp/cmp/cmpopts.SortMaps. Unless the compare options are changed, empty non-nil maps and nil maps are equal.

Pointers and interfaces are equal if they are both nil or both non-nil, where they have the same underlying concrete type and recursively calling Equal on the underlying values reports equal.

Before recursing into a pointer, slice element, or map, the current path is checked to detect whether the address has already been visited. If there is a cycle, then the pointed at values are considered equal only if both addresses were previously visited in the same path step.

func (AnyType[T]) I

func (a AnyType[T]) I(info any, other ...any) AnyType[T]

I is a synonym for [Info].

func (AnyType[T]) Info

func (a AnyType[T]) Info(info any, other ...any) AnyType[T]

Info adds a description of the assertion to be included in any error message. The first parameter should be some information such as a string or a number or even a struct. If info is a format string, more parameters can follow and will be formatted accordingly (see fmt.Sprintf).

func (AnyType[T]) Not

func (a AnyType[T]) Not() AnyType[T]

Not inverts the assertion.

func (AnyType[T]) ToBe

func (a AnyType[T]) ToBe(t Tester, expected T)

ToBe asserts that the actual and expected data have the same values and types. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	type pair struct {
		a, b int
	}

	// Any matching is most useful for structs (but can test anything)
	v := pair{1, 2}
	expect.Any(v).ToBe(t, pair{1, 2})
	expect.Any(v).Not().ToBe(t, pair{3, 4})

	var i int // some loop counter

	// Info gives more information when the test fails, such as within a loop
	expect.Any(v).Info("loop %d", i).ToBe(t, pair{1, 2})
}

func (AnyType[T]) ToBeNil added in v0.7.0

func (a AnyType[T]) ToBeNil(t Tester)

ToBeNil asserts that the actual value is nil / is not nil. The tester is normally *testing.T.

func (AnyType[T]) ToEqual

func (a AnyType[T]) ToEqual(t Tester, expected any)

ToEqual asserts that the actual and expected data have the same values and similar types. The actual value must be a type that is convertible to the type of the expected value. The tester is normally *testing.T.

func (AnyType[T]) Using

func (a AnyType[T]) Using(opt ...gocmp.Option) AnyType[T]

Using replaces the default comparison options with those specified here. You can also set DefaultOptions instead.

type BoolType

type BoolType[B ~bool] struct {
	// contains filtered or unexported fields
}

BoolType is used for assertions about bools.

func Bool

func Bool[B ~bool](value B, other ...any) BoolType[B]

Bool creates a boolean assertion.

If more than one argument is passed, all subsequent arguments will be required to be nil/zero. This is convenient if you want to make an assertion on a method/function that returns a value and an error, a common pattern in Go.

func (BoolType[B]) I

func (a BoolType[B]) I(info any, other ...any) BoolType[B]

I is a synonym for [Info].

func (BoolType[B]) Info

func (a BoolType[B]) Info(info any, other ...any) BoolType[B]

Info adds a description of the assertion to be included in any error message. The first parameter should be some information such as a string or a number or even a struct. If info is a format string, more parameters can follow and will be formatted accordingly (see fmt.Sprintf).

func (BoolType[B]) Not

func (a BoolType[B]) Not() BoolType[B]

Not inverts the assertion.

func (BoolType[B]) ToBe

func (a BoolType[B]) ToBe(t Tester, expected B)

ToBe asserts that the actual and expected items have the same values and types. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	var v bool
	expect.Bool(v).ToBe(t, false) // or ToBeFalse(t)

	var i int // some loop counter

	// Info gives more information when the test fails, such as within a loop
	expect.Bool(v).Info("loop %d", i).Not().ToBeTrue(t)
}

func (BoolType[B]) ToBeFalse

func (a BoolType[B]) ToBeFalse(t Tester)

ToBeFalse asserts that the actual value is true. The tester is normally *testing.T.

func (BoolType[B]) ToBeTrue

func (a BoolType[B]) ToBeTrue(t Tester)

ToBeTrue asserts that the actual value is true. The tester is normally *testing.T.

func (BoolType[B]) ToEqual

func (a BoolType[B]) ToEqual(t Tester, expected bool)

ToEqual asserts that the actual and expected items have the same values and similar types. The tester is normally *testing.T.

type ErrorType

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

ErrorType is used for assertions about errors.

func Error

func Error(value any, other ...any) ErrorType

Error creates an error assertion. This considers the last error it finds in the supplied parameters. At least one of the parameters must be an error. All other parameters are ignored.

func (ErrorType) I

func (a ErrorType) I(info any, other ...any) ErrorType

I is a synonym for [Info].

func (ErrorType) Info

func (a ErrorType) Info(info any, other ...any) ErrorType

Info adds a description of the assertion to be included in any error message. The first parameter should be some information such as a string or a number or even a struct. If info is a format string, more parameters can follow and will be formatted accordingly (see fmt.Sprintf).

func (ErrorType) Not

func (a ErrorType) Not() ErrorType

Not inverts the assertion.

func (ErrorType) ToBeNil

func (a ErrorType) ToBeNil(t Tester)

ToBeNil asserts that the error did not occur. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	var err error
	// ... something under test goes here
	expect.Error(err).ToBeNil(t)
	expect.Error(err).Not().ToHaveOccurred(t)

	// if there's a function that returns various results and an error...
	thingUnderTest := func() (string, error) { return "", nil }
	// ...the function return parameters can be passed straight in
	expect.Error(thingUnderTest()).Not().ToHaveOccurred(t)
}

func (ErrorType) ToContain

func (a ErrorType) ToContain(t Tester, substring string)

ToContain asserts that the error occurred and its message contains the substring. The tester is normally *testing.T.

func (ErrorType) ToHaveOccurred

func (a ErrorType) ToHaveOccurred(t Tester)

ToHaveOccurred asserts that the error occurred. The tester is normally *testing.T.

func (ErrorType) ToMatch added in v0.20.0

func (a ErrorType) ToMatch(t Tester, pattern *regexp.Regexp)

ToMatch asserts that the error occurred and its message matches a regular expression. The tester is normally *testing.T.

type FuncType added in v0.5.0

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

FuncType is used for assertions about functions.

func Func added in v0.5.0

func Func(value func()) FuncType

Func wraps a function that can test for panics etc.

func (FuncType) I added in v0.5.0

func (a FuncType) I(info any, other ...any) FuncType

I is a synonym for [Info].

func (FuncType) Info added in v0.5.0

func (a FuncType) Info(info any, other ...any) FuncType

Info adds a description of the assertion to be included in any error message. The first parameter should be some information such as a string or a number or even a struct. If info is a format string, more parameters can follow and will be formatted accordingly (see fmt.Sprintf).

func (FuncType) Not added in v0.5.0

func (a FuncType) Not() FuncType

Not inverts the assertion.

func (FuncType) ToPanic added in v0.5.0

func (a FuncType) ToPanic(t Tester)

ToPanic asserts that the function did / did not panic. The tester is normally *testing.B.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	expect.Func(func() { panic(101) }).ToPanic(t)

	expect.Func(func() {}).Not().ToPanic(t)
}

func (FuncType) ToPanicWithMessage added in v0.5.0

func (a FuncType) ToPanicWithMessage(t Tester, substring string)

ToPanicWithMessage asserts that the function did panic. It is not useful to use FuncType.Not with this. The substring is used to check that the panic passed a string containing that value. The tester is normally *testing.B.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	expect.Func(func() { panic("boo") }).ToPanicWithMessage(t, "boo")
}

type MapType

type MapType[K comparable, V any] struct {
	// contains filtered or unexported fields
}

MapType is used for assertions about maps.

func Map

func Map[K comparable, V any](value map[K]V, other ...any) MapType[K, V]

Map creates an assertion for deep value comparison of maps of any type.

This uses gocmp.Equal so the manner of comparison can be tweaked using that API - see also MapType.Using

func (MapType[K, V]) I

func (a MapType[K, V]) I(info any, other ...any) MapType[K, V]

I is a synonym for [Info].

func (MapType[K, V]) Info

func (a MapType[K, V]) Info(info any, other ...any) MapType[K, V]

Info adds a description of the assertion to be included in any error message. The first parameter should be some information such as a string or a number or even a struct. If info is a format string, more parameters can follow and will be formatted accordingly (see fmt.Sprintf).

func (MapType[K, V]) Not

func (a MapType[K, V]) Not() MapType[K, V]

Not inverts the assertion.

func (MapType[K, V]) ToBe

func (a MapType[K, V]) ToBe(t Tester, expected map[K]V)

ToBe asserts that the actual and expected maps have the same values and types. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	m := map[string]int{"a": 1, "b": 2, "c": 3}
	// ToBe verifies all the keys and values match
	expect.Map(m).ToBe(t, map[string]int{"a": 1, "b": 2, "c": 3})
}

func (MapType[K, V]) ToBeEmpty added in v0.8.0

func (a MapType[K, V]) ToBeEmpty(t Tester)

ToBeEmpty asserts that the map has zero length. The tester is normally *testing.T.

func (MapType[K, V]) ToBeNil added in v0.10.0

func (a MapType[K, V]) ToBeNil(t Tester)

ToBeNil asserts that the actual value is nil / is not nil. The tester is normally *testing.T.

func (MapType[K, V]) ToContain

func (a MapType[K, V]) ToContain(t Tester, expectedKey K, expectedValue ...V)

ToContain asserts that the map contains a particular key. If present, the expected value must also match. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	m := map[string]int{"a": 1, "b": 2, "c": 3}

	// verify one key is present
	expect.Map(m).ToContain(t, "b")

	// verify one key and its value match
	expect.Map(m).ToContain(t, "b", 2)
}

func (MapType[K, V]) ToContainAll added in v0.11.0

func (a MapType[K, V]) ToContainAll(t Tester, expectedKey ...K)

ToContainAll asserts that the map contains all the expected keys. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	m := map[string]int{"a": 1, "b": 2, "c": 3}

	expect.Map(m).ToContainAll(t, "a", "b")
}

func (MapType[K, V]) ToContainAny added in v0.11.0

func (a MapType[K, V]) ToContainAny(t Tester, expectedKey ...K)

ToContainAny asserts that the map contains any the expected keys. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	m := map[string]int{"a": 1, "b": 2, "c": 3}

	expect.Map(m).ToContainAny(t, "z", "b")
}

func (MapType[K, V]) ToHaveLength

func (a MapType[K, V]) ToHaveLength(t Tester, expected int)

ToHaveLength asserts that the map has the expected length. The tester is normally *testing.T.

func (MapType[K, V]) ToHaveSize

func (a MapType[K, V]) ToHaveSize(t Tester, expected int)

ToHaveSize is a synonym for ToHaveLength. The tester is normally *testing.T.

func (MapType[K, V]) Using

func (a MapType[K, V]) Using(opt ...gocmp.Option) MapType[K, V]

Using replaces the default comparison options with those specified here. You can also set DefaultOptions instead.

type OrderedOr added in v0.16.0

type OrderedOr[O cmp.Ordered] struct {
	// contains filtered or unexported fields
}

OrderedOr is only used for conjunction concatenation (see OrderedOr.Or).

func (*OrderedOr[O]) Or added in v0.16.0

func (or *OrderedOr[O]) Or() *OrderedType[O]

type OrderedType

type OrderedType[O cmp.Ordered] struct {
	// contains filtered or unexported fields
}

OrderedType is used for assertions about numbers and other ordered types.

func Number

func Number[O cmp.Ordered](value O, other ...any) *OrderedType[O]

Number creates an ordering assertion. It accepts all numbers, and also coincidentally accepts strings. Its methods are the full set of ordering comparisons, i.e. >, >=, <, <=, ==, and !=.

If more than one argument is passed, all subsequent arguments will be required to be nil/zero. This is convenient if you want to make an assertion on a method/function that returns a value and an error, a common pattern in Go.

func (*OrderedType[O]) I

func (a *OrderedType[O]) I(info any, other ...any) *OrderedType[O]

I is a synonym for [Info].

func (*OrderedType[O]) Info

func (a *OrderedType[O]) Info(info any, other ...any) *OrderedType[O]

Info adds a description of the assertion to be included in any error message. The first parameter should be some information such as a string or a number or even a struct. If info is a format string, more parameters can follow and will be formatted accordingly (see fmt.Sprintf).

func (*OrderedType[O]) Not

func (a *OrderedType[O]) Not() *OrderedType[O]

Not inverts the assertion.

func (*OrderedType[O]) ToBe

func (a *OrderedType[O]) ToBe(t Tester, expected O) *OrderedOr[O]

ToBe asserts that the actual and expected numbers have the same values and types. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	// Number matching can use any size of int or uint or float, or subtype of any of them.
	// This example allows either of the two expected values.
	v := 123
	expect.Number(v).ToBe(nil, 123).Or().ToBe(t, 125)

	// The `Info` method can be helpful when testing inside a loop, for example.
	var i int // some loop counter
	expect.Number(v).Info("loop %d", i).Not().ToBe(t, 321)
}

func (*OrderedType[O]) ToBeBetween added in v0.12.0

func (a *OrderedType[O]) ToBeBetween(t Tester, minimum, maximum O) *OrderedOr[O]

ToBeBetween asserts that the actual values is between two threshold values. The assertion succeeds if minimum < value < maximum. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	// number matching can use any size of int or uint or float, or subtype of any of them
	v := 123
	expect.Number(v).ToBeBetween(t, 100, 200)

	var i int // some loop counter
	expect.Number(v).Info("loop %d", i).Not().ToBeBetween(t, 1, 10)
}

func (*OrderedType[O]) ToBeBetweenOrEqual added in v0.12.0

func (a *OrderedType[O]) ToBeBetweenOrEqual(t Tester, minimum, maximum O) *OrderedOr[O]

ToBeBetweenOrEqual asserts that the actual values is between two threshold values. The assertion succeeds if minimum <= value <= maximum. The tester is normally *testing.T.

func (*OrderedType[O]) ToBeGreaterThan

func (a *OrderedType[O]) ToBeGreaterThan(t Tester, threshold O) *OrderedOr[O]

ToBeGreaterThan asserts that the actual values is greater than the threshold value. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	// number matching can use any size of int or uint or float, or subtype of any of them
	v := 123
	expect.Number(v).ToBeGreaterThan(t, 100)

	var i int // some loop counter
	expect.Number(v).Info("loop %d", i).Not().ToBeGreaterThan(t, 200)
}

func (*OrderedType[O]) ToBeGreaterThanOrEqual added in v0.12.0

func (a *OrderedType[O]) ToBeGreaterThanOrEqual(t Tester, threshold O) *OrderedOr[O]

ToBeGreaterThanOrEqual asserts that the actual values is greater than or equal to the threshold value. The tester is normally *testing.T.

func (*OrderedType[O]) ToBeLessThan

func (a *OrderedType[O]) ToBeLessThan(t Tester, threshold O) *OrderedOr[O]

ToBeLessThan asserts that the actual values is less than the threshold value. The tester is normally *testing.T.

func (*OrderedType[O]) ToBeLessThanOrEqual added in v0.12.0

func (a *OrderedType[O]) ToBeLessThanOrEqual(t Tester, threshold O) *OrderedOr[O]

ToBeLessThanOrEqual asserts that the actual values is less than or equal to the threshold value. The tester is normally *testing.T.

func (*OrderedType[O]) ToEqual added in v0.21.0

func (a *OrderedType[O]) ToEqual(t Tester, expected any) *OrderedOr[O]

ToEqual asserts that the actual and expected numbers have the same values and similar types. The expected value must be some numeric type. The tester is normally *testing.T.

type SliceType

type SliceType[T any] struct {
	// contains filtered or unexported fields
}

SliceType is used for assertions about slices.

func Slice

func Slice[T any](value []T, other ...any) SliceType[T]

Slice creates an assertion for deep value comparison of slices of any type.

This uses gocmp.Equal so the manner of comparison can be tweaked using that API - see also SliceType.Using

func (SliceType[T]) I

func (a SliceType[T]) I(info any, other ...any) SliceType[T]

I is a synonym for [Info].

func (SliceType[T]) Info

func (a SliceType[T]) Info(info any, other ...any) SliceType[T]

Info adds a description of the assertion to be included in any error message. The first parameter should be some information such as a string or a number or even a struct. If info is a format string, more parameters can follow and will be formatted accordingly (see fmt.Sprintf).

func (SliceType[T]) Not

func (a SliceType[T]) Not() SliceType[T]

Not inverts the assertion.

func (SliceType[T]) ToBe

func (a SliceType[T]) ToBe(t Tester, expected ...T)

ToBe asserts that the actual and expected slices have the same values and types. The values must be in the same order. If you pass the expected values in a slice, don't forget the ellipsis. The tester is normally *testing.T.

func (SliceType[T]) ToBeEmpty added in v0.7.0

func (a SliceType[T]) ToBeEmpty(t Tester)

ToBeEmpty asserts that the slice has zero length. The tester is normally *testing.T.

func (SliceType[T]) ToBeNil added in v0.10.0

func (a SliceType[T]) ToBeNil(t Tester)

ToBeNil asserts that the actual value is nil / is not nil. The tester is normally *testing.T.

func (SliceType[T]) ToContain added in v0.18.0

func (a SliceType[T]) ToContain(t Tester, expected T)

ToContain asserts that the slice contains the expected value. The tester is normally *testing.T.

func (SliceType[T]) ToContainAll

func (a SliceType[T]) ToContainAll(t Tester, expected ...T)

ToContainAll asserts that the slice contains all of the values listed. The tester is normally *testing.T.

func (SliceType[T]) ToContainAny

func (a SliceType[T]) ToContainAny(t Tester, expected ...T)

ToContainAny asserts that the slice contains any of the values listed. The tester is normally *testing.T.

func (SliceType[T]) ToHaveLength

func (a SliceType[T]) ToHaveLength(t Tester, expected int)

ToHaveLength asserts that the slice has the expected length. The tester is normally *testing.T.

func (SliceType[T]) Using

func (a SliceType[T]) Using(opt ...gocmp.Option) SliceType[T]

Using replaces the default comparison options with those specified here. You can also set DefaultOptions instead.

type StringOr added in v0.15.0

type StringOr[S Stringy] struct {
	// contains filtered or unexported fields
}

StringOr is only used for conjunction concatenation (see StringOr.Or).

func (*StringOr[S]) Or added in v0.15.0

func (or *StringOr[S]) Or() *StringType[S]

type StringType

type StringType[S Stringy] struct {
	// contains filtered or unexported fields
}

StringType is used for assertions about strings.

func String

func String[S Stringy](value S, other ...any) *StringType[S]

String creates a string assertion. Strings must contain valid UTF8 encodings.

It accepts all string subtypes and []byte, []rune.

If more than one argument is passed, all subsequent arguments will be required to be nil/zero. This is convenient if you want to make an assertion on a method/function that returns a value and an error, a common pattern in Go.

func (*StringType[S]) I

func (a *StringType[S]) I(info any, other ...any) *StringType[S]

I is a synonym for [Info].

func (*StringType[S]) Info

func (a *StringType[S]) Info(info any, other ...any) *StringType[S]

Info adds a description of the assertion to be included in any error message. The first parameter should be some information such as a string or a number or even a struct. If info is a format string, more parameters can follow and will be formatted accordingly (see fmt.Sprintf).

func (*StringType[S]) Not

func (a *StringType[S]) Not() *StringType[S]

Not inverts the assertion.

func (*StringType[S]) ToBe

func (a *StringType[S]) ToBe(t Tester, expected S) *StringOr[S]

ToBe asserts that the actual and expected strings have the same values and types. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	// string matching can use any string, or subtype of string
	s := "hello"
	expect.String(s).ToBe(t, "hello")

	var i int // some loop counter
	expect.String(s).Info("loop %d", i).Not().ToBe(t, "goodbye")
}

func (*StringType[S]) ToBeEmpty added in v0.8.0

func (a *StringType[S]) ToBeEmpty(t Tester) *StringOr[S]

ToBeEmpty asserts that the string has zero length. The tester is normally *testing.T.

func (*StringType[S]) ToContain

func (a *StringType[S]) ToContain(t Tester, substring S) *StringOr[S]

ToContain asserts that the actual string contains the substring. The tester is normally *testing.T.

Example
package main

import (
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	s := "Once more unto the breach"
	expect.String(s).ToContain(t, "unto")

	var i int // some loop counter
	expect.String(s).Info("loop %d", i).Not().ToContain(t, "foobar")
}

func (*StringType[S]) ToEqual

func (a *StringType[S]) ToEqual(t Tester, expected string) *StringOr[S]

ToEqual asserts that the actual and expected strings have the same values and similar types. Unlike StringType.ToBe, the concrete type may differ. The tester is normally *testing.T.

func (*StringType[S]) ToHaveLength added in v0.8.0

func (a *StringType[S]) ToHaveLength(t Tester, expected int) *StringOr[S]

ToHaveLength asserts that the string has the expected length. The tester is normally *testing.T.

func (*StringType[S]) ToMatch added in v0.11.0

func (a *StringType[S]) ToMatch(t Tester, pattern *regexp.Regexp) *StringOr[S]

ToMatch asserts that the actual string matches a regular expression. The tester is normally *testing.T.

Example
package main

import (
	"regexp"
	"testing"

	"github.com/rickb777/expect"
)

func main() {
	var t *testing.T

	s := "hello"
	expect.String(s).ToMatch(t, regexp.MustCompile("^he"))

	var i int // some loop counter
	expect.String(s).Info("loop %d", i).Not().ToMatch(t, regexp.MustCompile(".*bye$"))
}

func (*StringType[S]) Trim

func (a *StringType[S]) Trim(at int) *StringType[S]

Trim shortens the error message for very long strings. Trimming is disabled by default.

type Stringy

type Stringy interface {
	~string | []byte | []rune
}

type Tester

type Tester interface {
	Error(args ...any)
	Fatal(args ...any)
}

Tester reports test errors and failures. Notably, testing.T implements this interface.

func SimpleTester

func SimpleTester(errorFn, fatalFn func(v ...any)) Tester

SimpleTester is a tester that calls errorf on test errors and fatalf on test failures.

Jump to

Keyboard shortcuts

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