Skip to content

Commit

Permalink
assert: Add Error and ErrorContains
Browse files Browse the repository at this point in the history
  • Loading branch information
nhooyr committed Dec 12, 2019
1 parent 97798d6 commit b54be11
Showing 1 changed file with 29 additions and 4 deletions.
33 changes: 29 additions & 4 deletions sloggers/slogtest/assert/assert.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
// Package assert is a helper package for test assertions.
//
// On failure, every assertion will fatal the test.
//
// The name argument is included in each assertion for easier debugging.
package assert // import "cdr.dev/slog/sloggers/slogtest/assert"

import (
"strings"
"testing"

"cdr.dev/slog"
Expand All @@ -24,8 +29,6 @@ func Equal(t testing.TB, exp, act interface{}, name string) {
}

// Success asserts err == nil.
//
// If err isn't nil, it will fatal the test with the error.
func Success(t testing.TB, err error, name string) {
slog.Helper()
if err != nil {
Expand All @@ -37,9 +40,31 @@ func Success(t testing.TB, err error, name string) {
}

// True asserts act == true.
//
// If act isn't true, it will fatal the test.
func True(t testing.TB, act bool, name string) {
slog.Helper()
Equal(t, true, act, name)
}

// Error asserts err != nil.
func Error(t testing.TB, err error, name string) {
slog.Helper()
if err == nil {
slogtest.Fatal(t, "expected error",
slog.F("name", name),
)
}
}

// ErrorContains asserts err != nil and err.Error() contains sub.
func ErrorContains(t testing.TB, err error, sub, name string) {
slog.Helper()
Error(t, err, name)
errs := err.Error()
if !strings.Contains(errs, sub) {
slogtest.Fatal(t, "unexpected error string",
slog.F("name", name),
slog.F("error_string", errs),
slog.F("expected_substring", sub),
)
}
}

0 comments on commit b54be11

Please sign in to comment.