Documentation
¶
Overview ¶
Package assert provides minimal test assertions with excellent diff output.
This package offers a focused set of assertion functions for Go tests, built on google/go-cmp for deep comparisons. When assertions fail, you get colored unified diffs that clearly show what changed, making test failures easy to debug.
Features ¶
- Deep equality with go-cmp: Compares structs, slices, maps, and nested types
- Colored diffs: Red for expected (-want), green for actual (+got)
- Fatal assertions: All assertions fail immediately via t.Fatalf()
- Unexported field support: Compares unexported fields by default
- Optional messages: All assertions accept optional message formatting
Basic Usage ¶
func TestUser(t *testing.T) {
user := fetchUser()
assert.Equal(t, user.Name, "Alice")
assert.NoError(t, err)
assert.True(t, user.Active, "user should be active")
}
Equality Assertions ¶
Equal and NotEqual use go-cmp for deep comparison:
assert.Equal(t, got, want) // Deep equality assert.EqualOpts(t, got, want, cmpOpts...) // With custom cmp options assert.NotEqual(t, got, want) // Values should differ
Error Assertions ¶
Test error conditions with various matchers:
assert.NoError(t, err) // err must be nil assert.Error(t, err) // err must not be nil assert.ErrorIs(t, err, target) // errors.Is match assert.ErrorAs(t, err, &target) // errors.As match assert.ErrorContains(t, err, "not found") // Substring match
Nil and Boolean Assertions ¶
assert.Nil(t, ptr) // Value must be nil assert.NotNil(t, ptr) // Value must not be nil assert.True(t, condition) // Boolean must be true assert.False(t, condition) // Boolean must be false
Collection Assertions ¶
assert.Contains(t, haystack, needle) // String/slice/map contains assert.NotContains(t, haystack, needle) // Does not contain assert.Len(t, collection, 5) // Length check assert.Empty(t, collection) // Nil, zero-length, or zero value assert.NotEmpty(t, collection) // Has content
Comparison Assertions ¶
Generic comparison functions work with any ordered type:
assert.Greater(t, a, b) // a > b assert.GreaterOrEqual(t, a, b) // a >= b assert.Less(t, a, b) // a < b assert.LessOrEqual(t, a, b) // a <= b assert.InDelta(t, 3.14, 3.15, 0.01) // Float comparison with delta
Pattern and Panic Assertions ¶
assert.Regexp(t, `\d+`, str) // String matches regex
assert.Panics(t, func() { ... }) // Function must panic
assert.NotPanics(t, func() { ... }) // Function must not panic
Optional Messages ¶
All assertions accept optional message arguments for context:
assert.Equal(t, got, want, "processing user ID %d", userID) assert.NoError(t, err, "failed to open file")
The first msgAndArgs argument can be a format string with additional arguments, or a single value that will be formatted with %v.
Example ¶
Example demonstrates basic assertion usage.
// In a real test, you would use t *testing.T
// This example uses a mock for demonstration
// Equal compares values deeply
type User struct {
Name string
Age int
}
user := User{Name: "Alice", Age: 30}
_ = user // In real test: assert.Equal(t, user.Name, "Alice")
// NoError checks for nil errors
var err error = nil
_ = err // In real test: assert.NoError(t, err)
// True/False check boolean conditions
active := true
_ = active // In real test: assert.True(t, active)
Index ¶
- func Contains(t testing.TB, haystack, needle any, msgAndArgs ...any)
- func Empty(t testing.TB, v any, msgAndArgs ...any)
- func Equal(t testing.TB, got, want any, msgAndArgs ...any)
- func EqualOpts(t testing.TB, got, want any, opts ...gocmp.Option)
- func Error(t testing.TB, err error, msgAndArgs ...any)
- func ErrorAs(t testing.TB, err error, target any, msgAndArgs ...any)
- func ErrorContains(t testing.TB, err error, substr string, msgAndArgs ...any)
- func ErrorIs(t testing.TB, err, target error, msgAndArgs ...any)
- func False(t testing.TB, v bool, msgAndArgs ...any)
- func Greater[T cmp.Ordered](t testing.TB, a, b T, msgAndArgs ...any)
- func GreaterOrEqual[T cmp.Ordered](t testing.TB, a, b T, msgAndArgs ...any)
- func InDelta(t testing.TB, expected, actual, delta float64, msgAndArgs ...any)
- func Len(t testing.TB, v any, want int, msgAndArgs ...any)
- func Less[T cmp.Ordered](t testing.TB, a, b T, msgAndArgs ...any)
- func LessOrEqual[T cmp.Ordered](t testing.TB, a, b T, msgAndArgs ...any)
- func Nil(t testing.TB, v any, msgAndArgs ...any)
- func NoError(t testing.TB, err error, msgAndArgs ...any)
- func NotContains(t testing.TB, haystack, needle any, msgAndArgs ...any)
- func NotEmpty(t testing.TB, v any, msgAndArgs ...any)
- func NotEqual(t testing.TB, got, want any, msgAndArgs ...any)
- func NotNil(t testing.TB, v any, msgAndArgs ...any)
- func NotPanics(t testing.TB, f func(), msgAndArgs ...any)
- func Panics(t testing.TB, f func(), msgAndArgs ...any)
- func Regexp(t testing.TB, pattern any, str string, msgAndArgs ...any)
- func SetColorEnabled(enabled bool)
- func True(t testing.TB, v bool, msgAndArgs ...any)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Contains ¶
Contains asserts that haystack contains needle.
Behavior depends on haystack type:
- string: substring check
- slice/array: checks if any element equals needle
- map: checks if needle is a key in the map
Example:
assert.Contains(t, "hello world", "world")
assert.Contains(t, []int{1, 2, 3}, 2)
assert.Contains(t, map[string]int{"a": 1}, "a")
Example ¶
ExampleContains demonstrates containment checks.
t := &mockT{}
// String contains substring
Contains(t, "hello world", "world")
// Slice contains element
Contains(t, []int{1, 2, 3}, 2)
// Map contains key
Contains(t, map[string]int{"foo": 1}, "foo")
func Empty ¶
Empty asserts that v is empty (nil, zero length, or zero value).
Checks for emptiness based on type:
- nil values: always empty
- strings, slices, maps, channels: empty if length is 0
- pointers: empty if nil or pointing to empty value
- other types: empty if zero value (via reflect.Value.IsZero)
Example:
assert.Empty(t, "")
assert.Empty(t, []int{})
assert.Empty(t, nil)
Example ¶
ExampleEmpty demonstrates empty value checking.
t := &mockT{}
// Empty slice
Empty(t, []int{})
// Empty string
Empty(t, "")
// Nil value
Empty(t, nil)
func Equal ¶
Equal asserts that got and want are deeply equal.
This function performs deep comparison of any Go values including structs, slices, maps, and nested types. Unexported fields are compared by default. On failure, it displays a colored unified diff showing exactly what differs.
Optional msgAndArgs provide additional context:
- Single string: used as-is
- Format string + args: passed to fmt.Sprintf
Example:
user := User{Name: "Alice", Age: 30}
assert.Equal(t, user.Name, "Alice")
assert.Equal(t, user, want, "fetching user %d", userID)
Example ¶
ExampleEqual demonstrates deep equality assertions.
// Mock for demonstration - use *testing.T in real tests
t := &mockT{}
// Compare simple values
Equal(t, 42, 42)
// Compare structs
type Point struct {
X, Y int
}
Equal(t, Point{X: 1, Y: 2}, Point{X: 1, Y: 2})
// With optional message
Equal(t, "hello", "hello", "greeting should match")
func EqualOpts ¶ added in v0.0.2
EqualOpts asserts equality with custom cmp.Options.
Use this when you need to customize comparison behavior beyond the defaults. Useful for ignoring fields, custom comparers, or transforming values.
Example:
opts := cmp.Options{
cmpopts.IgnoreFields(User{}, "LastLogin"),
cmpopts.EquateApprox(0.01, 0),
}
assert.EqualOpts(t, got, want, opts...)
func ErrorAs ¶
ErrorAs asserts that errors.As(err, target) is true.
This checks if any error in err's chain matches target's type, and if so, assigns it to target. The target must be a pointer to an error type.
Example:
var pathErr *os.PathError assert.ErrorAs(t, err, &pathErr) // Now pathErr is populated with the matched error
Example ¶
ExampleErrorAs demonstrates error type checking.
t := &mockT{}
// Create a PathError
err := &os.PathError{
Op: "open",
Path: "/tmp/missing",
Err: errors.New("no such file"),
}
// Check if error is of a specific type
var pathErr *os.PathError
ErrorAs(t, err, &pathErr)
// Now pathErr is populated and can be used
_ = pathErr.Path // "/tmp/missing"
func ErrorContains ¶
ErrorContains asserts that err's Error() string contains the substring.
This performs a simple substring check on the error message. Fails if err is nil.
Example:
err := processFile("/tmp/missing")
assert.ErrorContains(t, err, "no such file")
func ErrorIs ¶
ErrorIs asserts that errors.Is(err, target) is true.
This checks if target appears anywhere in err's error chain, following the standard library's errors.Is semantics. Useful for wrapped errors.
Example:
var ErrNotFound = errors.New("not found")
err := fmt.Errorf("user: %w", ErrNotFound)
assert.ErrorIs(t, err, ErrNotFound)
Example ¶
ExampleErrorIs demonstrates error chain checking.
t := &mockT{}
// Define a sentinel error
var ErrNotFound = errors.New("not found")
// Create a wrapped error
err := fmt.Errorf("user database: %w", ErrNotFound)
// Check if ErrNotFound is in the error chain
ErrorIs(t, err, ErrNotFound)
func Greater ¶
Greater asserts that a > b.
Example ¶
ExampleGreater demonstrates comparison assertions.
t := &mockT{}
// Compare integers
Greater(t, 10, 5)
// Compare floats
Greater(t, 3.14, 2.71)
// Compare strings (lexicographic)
Greater(t, "banana", "apple")
func GreaterOrEqual ¶
GreaterOrEqual asserts that a >= b.
func InDelta ¶
InDelta asserts that two numbers are within delta of each other.
This is the preferred way to compare floating-point numbers, since direct equality comparison is unreliable due to rounding errors.
Example:
result := math.Pi * 2 assert.InDelta(t, result, 6.283, 0.001)
Example ¶
ExampleInDelta demonstrates floating-point comparison.
t := &mockT{}
// Compare floats with tolerance
result := 3.14159
InDelta(t, result, 3.14, 0.01)
// Useful for calculations that might have rounding errors
calculated := 1.0 / 3.0 * 3.0
InDelta(t, calculated, 1.0, 0.000001)
func Len ¶
Len asserts that v has the expected length.
Works with any type that has a length: strings, slices, arrays, maps, channels.
Example:
assert.Len(t, []int{1, 2, 3}, 3)
assert.Len(t, "hello", 5)
assert.Len(t, map[string]int{"a": 1, "b": 2}, 2)
Example ¶
ExampleLen demonstrates length assertions.
t := &mockT{}
// Check slice length
Len(t, []int{1, 2, 3}, 3)
// Check string length
Len(t, "hello", 5)
// Check map length
Len(t, map[string]int{"a": 1, "b": 2}, 2)
func LessOrEqual ¶
LessOrEqual asserts that a <= b.
func NoError ¶
NoError asserts that err is nil.
Example ¶
ExampleNoError demonstrates error assertions.
t := &mockT{}
// Assert that operation succeeded
err := performOperation()
NoError(t, err)
// With custom message
NoError(t, err, "operation should succeed")
func NotContains ¶
NotContains asserts that haystack does not contain needle.
func Panics ¶
Panics asserts that f panics.
Example ¶
ExamplePanics demonstrates panic assertions.
t := &mockT{}
// Assert that function panics
Panics(t, func() {
panic("oops!")
})
// Assert that function doesn't panic
NotPanics(t, func() {
// Normal execution
})
func Regexp ¶
Regexp asserts that str matches the regular expression pattern.
The pattern can be either a string (which will be compiled) or a pre-compiled *regexp.Regexp. Uses regexp.MatchString for matching.
Example:
assert.Regexp(t, `^\d{3}-\d{4}$`, phoneNumber)
assert.Regexp(t, regexp.MustCompile(`[A-Z][a-z]+`), "Hello")
Example ¶
ExampleRegexp demonstrates pattern matching.
t := &mockT{}
// Match with string pattern
Regexp(t, `^\d{3}-\d{4}$`, "555-1234")
// Match with compiled pattern
pattern := regexp.MustCompile(`[A-Z][a-z]+`)
Regexp(t, pattern, "Hello")
func SetColorEnabled ¶
func SetColorEnabled(enabled bool)
SetColorEnabled enables or disables colored output in diff messages.
Color is automatically enabled if stderr is a terminal. Use this function to explicitly control color output, for example to disable it in CI environments or when capturing test output to files.
Types ¶
This section is empty.