76 lines
1.8 KiB
Go
76 lines
1.8 KiB
Go
// Package testutil provides lightweight test helpers to reduce boilerplate in
|
|
// table-driven tests.
|
|
//
|
|
// Every helper calls t.Helper() so failures are reported at the call site, not
|
|
// inside this package.
|
|
package testutil
|
|
|
|
import (
|
|
"strings"
|
|
"testing"
|
|
|
|
"gitea.djmil.dev/go/template/pkg/result"
|
|
)
|
|
|
|
// NoError fails the test immediately if err is not nil.
|
|
func NoError(t *testing.T, err error) {
|
|
t.Helper()
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
}
|
|
|
|
// Error fails the test if err is nil.
|
|
func Error(t *testing.T, err error) {
|
|
t.Helper()
|
|
if err == nil {
|
|
t.Fatal("expected error, got nil")
|
|
}
|
|
}
|
|
|
|
// ErrorContains fails the test if err is nil or its message does not contain substr.
|
|
func ErrorContains(t *testing.T, err error, substr string) {
|
|
t.Helper()
|
|
Error(t, err)
|
|
if !strings.Contains(err.Error(), substr) {
|
|
t.Errorf("error %q does not contain %q", err.Error(), substr)
|
|
}
|
|
}
|
|
|
|
// Equal fails the test if got != want.
|
|
func Equal[T comparable](t *testing.T, got, want T) {
|
|
t.Helper()
|
|
if got != want {
|
|
t.Errorf("got %v, want %v", got, want)
|
|
}
|
|
}
|
|
|
|
// ResultOk fails the test if r holds an error, then returns the value.
|
|
func ResultOk[T any](t *testing.T, r result.Expect[T]) T {
|
|
t.Helper()
|
|
if r.Err() != nil {
|
|
t.Fatalf("unexpected error: %v", r.Err())
|
|
}
|
|
return r.Value()
|
|
}
|
|
|
|
// ResultOkNotNil fails the test if r holds an error or its value is nil.
|
|
// T must be a pointer type.
|
|
func ResultOkNotNil[T comparable](t *testing.T, r result.Expect[T]) T {
|
|
t.Helper()
|
|
v := ResultOk(t, r)
|
|
var zero T
|
|
if v == zero {
|
|
t.Fatal("expected non-nil value, got nil")
|
|
}
|
|
return v
|
|
}
|
|
|
|
// ResultErr fails the test if r does not hold an error.
|
|
func ResultErr[T any](t *testing.T, r result.Expect[T]) {
|
|
t.Helper()
|
|
if r.Err() == nil {
|
|
t.Fatal("expected error, got nil")
|
|
}
|
|
}
|