assert

package
v0.0.26 Latest Latest
Warning

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

Go to latest
Published: Feb 6, 2026 License: Apache-2.0 Imports: 11 Imported by: 0

README

assert

Test assertions with excellent diff output for Go tests. Built on go-cmp with colored unified diffs on failure.

Summary

The assert package provides minimal, fatal test assertions optimized for readability. All assertions fail immediately (t.Fatal) and show clear, colored diffs when values don't match. Built on google/go-cmp for comparisons, it compares unexported fields by default and provides specialized assertions for errors, nil checks, collections, and numeric comparisons.

Usage Examples

Basic Equality
package mypackage

import (
    "testing"
    "github.com/deepnoodle-ai/wonton/assert"
)

func TestUser(t *testing.T) {
    got := User{Name: "Alice", Age: 30}
    want := User{Name: "Alice", Age: 30}
    assert.Equal(t, got, want)
}

func TestNotEqual(t *testing.T) {
    got := fetchData()
    forbidden := corruptedData()
    assert.NotEqual(t, got, forbidden)
}
Error Assertions
func TestErrors(t *testing.T) {
    // Assert no error occurred
    err := DoSomething()
    assert.NoError(t, err)

    // Assert an error occurred
    err = DoInvalidThing()
    assert.Error(t, err)

    // Assert error contains specific error in chain
    err = wrapped.Error()
    assert.ErrorIs(t, err, io.EOF)

    // Assert error is of specific type
    var pathErr *os.PathError
    assert.ErrorAs(t, err, &pathErr)

    // Assert error message contains substring
    err = DoThing()
    assert.ErrorContains(t, err, "connection refused")
}
Nil Checks
func TestNil(t *testing.T) {
    var ptr *User
    assert.Nil(t, ptr)

    user := &User{}
    assert.NotNil(t, user)
}
Boolean Assertions
func TestBooleans(t *testing.T) {
    assert.True(t, isValid())
    assert.False(t, isEmpty())
}
Collections
func TestCollections(t *testing.T) {
    slice := []string{"apple", "banana", "cherry"}

    // Check length
    assert.Len(t, slice, 3)

    // Check contains
    assert.Contains(t, slice, "banana")
    assert.NotContains(t, slice, "grape")

    // Check empty/non-empty
    assert.NotEmpty(t, slice)
    assert.Empty(t, []string{})
}
Numeric Comparisons
func TestNumeric(t *testing.T) {
    assert.Greater(t, 10, 5)
    assert.GreaterOrEqual(t, 10, 10)
    assert.Less(t, 5, 10)
    assert.LessOrEqual(t, 5, 5)

    // Floating point comparison with delta
    assert.InDelta(t, 3.14159, 3.14, 0.01)
}
Pattern Matching
func TestPatterns(t *testing.T) {
    email := "[email protected]"
    assert.Regexp(t, `^[\w.]+@[\w.]+$`, email)

    // Can also use compiled regex
    pattern := regexp.MustCompile(`\d{3}-\d{4}`)
    assert.Regexp(t, pattern, "555-1234")
}
Panic Assertions
func TestPanics(t *testing.T) {
    assert.Panics(t, func() {
        panic("boom")
    })

    assert.NotPanics(t, func() {
        DoSafeThing()
    })
}
Custom Options
func TestCustomComparison(t *testing.T) {
    got := []User{{Name: "Alice", Age: 30}}
    want := []User{{Name: "Alice", Age: 31}}

    // Use custom cmp.Options for specialized comparisons
    assert.EqualOpts(t, got, want,
        cmpopts.IgnoreFields(User{}, "Age"))
}
Custom Messages
func TestWithMessages(t *testing.T) {
    assert.Equal(t, got, want, "user data mismatch")
    assert.Equal(t, got, want, "expected %d users, got %d", 5, len(got))
}
Disabling Colors
func TestMain(m *testing.M) {
    // Disable colors for CI environments
    assert.SetColorEnabled(false)
    os.Exit(m.Run())
}

API Reference

Core Assertions
Function Description Parameters
Equal(t, got, want, msg...) Asserts deep equality using go-cmp t testing.TB, values to compare, optional message
EqualOpts(t, got, want, opts...) Asserts equality with custom cmp.Options t testing.TB, values, cmp.Option variadic
NotEqual(t, got, want, msg...) Asserts values are not equal t testing.TB, values, optional message
Error Assertions
Function Description Parameters
NoError(t, err, msg...) Asserts error is nil t testing.TB, error, optional message
Error(t, err, msg...) Asserts error is not nil t testing.TB, error, optional message
ErrorIs(t, err, target, msg...) Asserts errors.Is(err, target) t testing.TB, error, target error, optional message
ErrorAs(t, err, target, msg...) Asserts errors.As(err, target) t testing.TB, error, target pointer, optional message
ErrorContains(t, err, substr, msg...) Asserts error message contains substring t testing.TB, error, string, optional message
Nil Checks
Function Description Parameters
Nil(t, v, msg...) Asserts value is nil t testing.TB, any, optional message
NotNil(t, v, msg...) Asserts value is not nil t testing.TB, any, optional message
Boolean Assertions
Function Description Parameters
True(t, v, msg...) Asserts boolean is true t testing.TB, bool, optional message
False(t, v, msg...) Asserts boolean is false t testing.TB, bool, optional message
Collection Assertions
Function Description Parameters
Contains(t, haystack, needle, msg...) Asserts collection contains value t testing.TB, collection, value, optional message
NotContains(t, haystack, needle, msg...) Asserts collection doesn't contain value t testing.TB, collection, value, optional message
Len(t, v, want, msg...) Asserts length equals expected t testing.TB, collection, int length, optional message
Empty(t, v, msg...) Asserts value is empty t testing.TB, any, optional message
NotEmpty(t, v, msg...) Asserts value is not empty t testing.TB, any, optional message
Panic Assertions
Function Description Parameters
Panics(t, f, msg...) Asserts function panics t testing.TB, func(), optional message
NotPanics(t, f, msg...) Asserts function doesn't panic t testing.TB, func(), optional message
Numeric Comparisons
Function Description Parameters
Greater[T](t, a, b, msg...) Asserts a > b t testing.TB, T (ordered), T, optional message
GreaterOrEqual[T](t, a, b, msg...) Asserts a >= b t testing.TB, T (ordered), T, optional message
Less[T](t, a, b, msg...) Asserts a < b t testing.TB, T (ordered), T, optional message
LessOrEqual[T](t, a, b, msg...) Asserts a <= b t testing.TB, T (ordered), T, optional message
InDelta(t, expected, actual, delta, msg...) Asserts floats are within delta t testing.TB, three float64, optional message
Pattern Matching
Function Description Parameters
Regexp(t, pattern, str, msg...) Asserts string matches regex t testing.TB, pattern (string or *regexp.Regexp), string, optional message
Configuration
Function Description Parameters
SetColorEnabled(enabled) Enables or disables colored output bool
  • tui - Terminal UI library that also uses colored output
  • color - Color utilities used for diff rendering
  • termtest - Terminal output testing with snapshot support

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

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Contains

func Contains(t testing.TB, haystack, needle any, msgAndArgs ...any)

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

func Empty(t testing.TB, v any, msgAndArgs ...any)

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

func Equal(t testing.TB, got, want any, msgAndArgs ...any)

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

func EqualOpts(t testing.TB, got, want any, opts ...gocmp.Option)

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 Error

func Error(t testing.TB, err error, msgAndArgs ...any)

Error asserts that err is not nil.

func ErrorAs

func ErrorAs(t testing.TB, err error, target any, msgAndArgs ...any)

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

func ErrorContains(t testing.TB, err error, substr string, msgAndArgs ...any)

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

func ErrorIs(t testing.TB, err, target error, msgAndArgs ...any)

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 False

func False(t testing.TB, v bool, msgAndArgs ...any)

False asserts that v is false.

func Greater

func Greater[T cmp.Ordered](t testing.TB, a, b T, msgAndArgs ...any)

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

func GreaterOrEqual[T cmp.Ordered](t testing.TB, a, b T, msgAndArgs ...any)

GreaterOrEqual asserts that a >= b.

func InDelta

func InDelta(t testing.TB, expected, actual, delta float64, msgAndArgs ...any)

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

func Len(t testing.TB, v any, want int, msgAndArgs ...any)

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 Less

func Less[T cmp.Ordered](t testing.TB, a, b T, msgAndArgs ...any)

Less asserts that a < b.

func LessOrEqual

func LessOrEqual[T cmp.Ordered](t testing.TB, a, b T, msgAndArgs ...any)

LessOrEqual asserts that a <= b.

func Nil

func Nil(t testing.TB, v any, msgAndArgs ...any)

Nil asserts that v is nil.

func NoError

func NoError(t testing.TB, err error, msgAndArgs ...any)

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

func NotContains(t testing.TB, haystack, needle any, msgAndArgs ...any)

NotContains asserts that haystack does not contain needle.

func NotEmpty

func NotEmpty(t testing.TB, v any, msgAndArgs ...any)

NotEmpty asserts that v is not empty.

func NotEqual

func NotEqual(t testing.TB, got, want any, msgAndArgs ...any)

NotEqual asserts that got and want are not deeply equal.

func NotNil

func NotNil(t testing.TB, v any, msgAndArgs ...any)

NotNil asserts that v is not nil.

func NotPanics

func NotPanics(t testing.TB, f func(), msgAndArgs ...any)

NotPanics asserts that f does not panic.

func Panics

func Panics(t testing.TB, f func(), msgAndArgs ...any)

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

func Regexp(t testing.TB, pattern any, str string, msgAndArgs ...any)

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.

func True

func True(t testing.TB, v bool, msgAndArgs ...any)

True asserts that v is true.

Types

This section is empty.

Jump to

Keyboard shortcuts

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