Skip to content

☑️ Assertions for the standard testing package

License

Notifications You must be signed in to change notification settings

go-simpler/assert

Repository files navigation

assert

checks pkg.go.dev goreportcard codecov

Assertions for the standard testing package.

📌 About

assert is a minimalistic replacement for the stretchr/testify package, providing an alternative API to switch between t.Errorf() and t.Fatalf(): instead of using separate packages (assert/require), it abuses type parameters:

assert.Equal[E](t, 1, 2) // [E] for t.Errorf()
assert.Equal[F](t, 1, 2) // [F] for t.Fatalf()

📦 Install

Go 1.21+

go get go-simpler.org/assert

Tip

When developing a library, you may want to keep go.mod small (or, even better, empty). In such cases, it is recommended to just copy-paste assert, as it is tiny and rarely updated. See the cmd/cp utility to do this automatically.

📋 Usage

The EF subpackage should be dot-imported so that E and F can be used as local types:

"go-simpler.org/assert"
. "go-simpler.org/assert/EF"

Optional format and arguments can be provided to each assertion to customize the error message:

assert.Equal[E](t, 1, 2, "%d != %d", 1, 2) // prints "1 != 2"

Equal

Asserts that two values are equal.

assert.Equal[E](t, 1, 2)

NoErr

Asserts that the error is nil.

assert.NoErr[E](t, err)

IsErr

Asserts that errors.Is(err, target) is true.

assert.IsErr[E](t, err, os.ErrNotExist)

AsErr

Asserts that errors.As(err, target) is true.

assert.AsErr[E](t, err, new(*os.PathError))

Panics

Asserts that the given function panics with the argument v.

assert.Panics[E](t, func() { /* panic? */ }, 42)