pkg/check: NotEqual, DeepEqual, ElementsMatch

This commit is contained in:
djmil 2026-06-11 19:10:08 +00:00
parent 9574c0faad
commit 3915cf2dda

View File

@ -9,6 +9,7 @@
package check package check
import ( import (
"reflect"
"strings" "strings"
"testing" "testing"
@ -71,6 +72,44 @@ func Equal[T comparable](t *testing.T, got, want T) {
} }
} }
// NotEqual fails the test if got == want.
func NotEqual[T comparable](t *testing.T, got, want T) {
t.Helper()
if got == want {
t.Errorf("expected values to differ, got %v", got)
}
}
// DeepEqual fails the test if got and want are not deeply equal.
// Use instead of Equal for maps, slices, and structs with slice fields.
func DeepEqual(t *testing.T, got, want any) {
t.Helper()
if !reflect.DeepEqual(got, want) {
t.Errorf("got %v, want %v", got, want)
}
}
// ElementsMatch fails the test if got and want do not contain the same
// elements regardless of order, including duplicates. T must be comparable —
// for slices or maps as elements, use DeepEqual after sorting manually.
func ElementsMatch[T comparable](t *testing.T, got, want []T) {
t.Helper()
if len(got) != len(want) {
t.Errorf("length mismatch: got %d elements, want %d", len(got), len(want))
return
}
freq := make(map[T]int, len(want))
for _, v := range want {
freq[v]++
}
for _, v := range got {
if freq[v]--; freq[v] < 0 {
t.Errorf("unexpected element: %v", v)
return
}
}
}
// Ok fails the test if r holds an error, then returns the value. // Ok fails the test if r holds an error, then returns the value.
func Ok[T any](t *testing.T, r result.Expect[T]) T { func Ok[T any](t *testing.T, r result.Expect[T]) T {
t.Helper() t.Helper()