expect

package module
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Apr 3, 2025 License: MIT Imports: 12 Imported by: 1

README

expect

GoDoc Go Report Card 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 ...)

This compares any types, but is especially useful for structs, maps, arrays, slices. Although this will compare anything, it only provides equality tests and the error messages may be less informative than the other categories below.

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.

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.

expect.Slice(actual ...)

This compares []T but only where T is a comparable type. Use Any for other slices.

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 non-nil (e.g. a non-nil error), the assertion will fail and give a corresponding error message. This allows, for example, the input to be a function with a multi-value return.

Note that Error is different - it considers the /last/ non-nil argument as its actual input. Any preceding arguments are ignored.

Basic Methods

All categories include these general methods

  • Info(...) provides information in the failure message, if there is one. There is a terse synonym I(...) too.
  • Not() inverts the assertion defined by the ToXxxx method that follows it (these assertions are described below)

String also has Trim(n) that truncates message strings if they exceed the specified length.

Assertions

The assertions are all infinitive verbs, i.e. methods such as ToBe.

All of them 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 as follows.

Any String Number Bool Map Slice Error Func
ToBe Yes Yes Yes Yes Yes Yes - -
ToEqual Yes Yes - Yes - - - -
ToBeNil Yes - - - Yes Yes Yes -
ToBeEmpty - Yes - - Yes Yes - -
ToHaveLength - Yes - - Yes Yes - -
ToContain - Yes - - Yes - Yes -
ToContainAll - - - - Yes Yes - -
ToContainAny - - - - Yes Yes - -
ToMatch - Yes - - - - - -
ToBeTrue - - - Yes - - - -
ToBeFalse - - - Yes - - - -
ToBeGreaterThan - - Yes - - - - -
ToBeGreaterThanOrEqual - - Yes - - - - -
ToBeLessThan - - Yes - - - - -
ToBeLessThanOrEqual - - 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

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 are present, in any order
  • 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

Note that these assertions actually apply to all ordered types, which includes all int/uint types, float32/float64 and also string.

Errors are handled with ToHaveOccurred(t), or more typically Not().ToHaveOccurred(t). 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).

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 is now ready for beta testing.

History

This API was mostly inspired by Gomega, which had some great ideas but is overly complex to use.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ApproximateFloatFraction = 1e-4

ApproximateFloatFraction provides an option that compares any (a, b float32) or (a, b float64) pair. 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 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 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.

Any uses gocmp.Equal so the manner of comparison can be tweaked using that API - see also 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. If this 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.

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 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. If this 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.

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. 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. If this 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.

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.

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. If this 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.

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.

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. If this 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.

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.

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.

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.

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 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. If this 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)

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

func (OrderedType[O]) ToBeGreaterThan

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

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

func (OrderedType[O]) ToBeGreaterThanOrEqualTo

func (a OrderedType[O]) ToBeGreaterThanOrEqualTo(t Tester, threshold O)

ToBeGreaterThanOrEqualTo 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)

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

func (OrderedType[O]) ToBeLessThanOrEqualTo

func (a OrderedType[O]) ToBeLessThanOrEqualTo(t Tester, threshold O)

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

type SliceType

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

SliceType is used for assertions about slices.

func Slice

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

Slice creates an assertion for deep value comparison of slices of any comparable 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. If this 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. 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]) 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 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. If this 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)

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

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

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

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)

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

func (StringType[S]) ToEqual

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

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)

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)

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

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 {
	Errorf(format string, args ...any)
	Fatalf(format string, args ...any)
}

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

func SimpleTester

func SimpleTester(errorf, fatalf func(format string, 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