Playground
doc.gno
// v0 - Unaudited: This is an initial version that has not yet been formally audited. // A fully audited version will be published as a subsequent release. // Use in production at your own risk. package uassert // import "gno.land/p/nt/uassert/v0"
gnomod.toml
module = "gno.land/p/nt/uassert/v0" gno = "0.9" [addpkg] creator = "g1edq4dugw0sgat4zxcw9xardvuydqf6cgleuc8p"
helpers.gno
package uassert
import "strings"
func fail(t TestingT, customMsgs []string, failureMessage string, args ...any) bool {
customMsg := ""
if len(customMsgs) > 0 {
customMsg = strings.Join(customMsgs, " ")
}
if customMsg != "" {
failureMessage += " - " + customMsg
}
t.Errorf(failureMessage, args...)
return false
}
func checkDidPanic(f any, rlm realm) (didPanic bool, message string) {
didPanic = true
defer func() {
r := recover()
if r == nil {
message = "nil"
return
}
err, ok := r.(error)
if ok {
message = err.Error()
return
}
errStr, ok := r.(string)
if ok {
message = errStr
return
}
message = "recover: unsupported type"
}()
switch f := f.(type) {
case func():
f()
case func(realm):
f(cross(rlm))
default:
panic("f must be of type func() or func(realm)")
}
didPanic = false
return
}
mock_test.gno
package uassert_test
import (
"fmt"
"testing"
"gno.land/p/nt/uassert/v0"
)
type mockTestingT struct {
fmt string
args []any
}
// --- interface mock
var _ uassert.TestingT = (*mockTestingT)(nil)
func (mockT *mockTestingT) Helper() { /* noop */ }
func (mockT *mockTestingT) Skip(args ...any) { /* not implmented */ }
func (mockT *mockTestingT) Fail() { /* not implmented */ }
func (mockT *mockTestingT) FailNow() { /* not implmented */ }
func (mockT *mockTestingT) Logf(fmt string, args ...any) { /* noop */ }
func (mockT *mockTestingT) Fatalf(fmt string, args ...any) {
mockT.fmt = "fatal: " + fmt
mockT.args = args
}
func (mockT *mockTestingT) Errorf(fmt string, args ...any) {
mockT.fmt = "error: " + fmt
mockT.args = args
}
// --- helpers
func (mockT *mockTestingT) actualString() string {
res := fmt.Sprintf(mockT.fmt, mockT.args...)
mockT.reset()
return res
}
func (mockT *mockTestingT) reset() {
mockT.fmt = ""
mockT.args = nil
}
func (mockT *mockTestingT) equals(t *testing.T, expected string) {
actual := mockT.actualString()
if expected != actual {
t.Errorf("mockT differs:\n- expected: %s\n- actual: %s\n", expected, actual)
}
}
func (mockT *mockTestingT) empty(t *testing.T) {
if mockT.fmt != "" || mockT.args != nil {
actual := mockT.actualString()
t.Errorf("mockT should be empty, got %s", actual)
}
}
types.gno
package uassert
type TestingT interface {
Helper()
Skip(args ...any)
Fatalf(fmt string, args ...any)
Errorf(fmt string, args ...any)
Logf(fmt string, args ...any)
Fail()
FailNow()
}
uassert.gno
// uassert is an adapted lighter version of https://github.com/stretchr/testify/assert.
package uassert
import (
"errors"
"strconv"
"strings"
"gno.land/p/nt/ufmt/v0"
"gno.land/p/onbloc/diff/v0"
)
// NoError asserts that a function returned no error (i.e. `nil`).
func NoError(t TestingT, err error, msgs ...string) bool {
t.Helper()
if err != nil {
return fail(t, msgs, "unexpected error: %s", err.Error())
}
return true
}
// Error asserts that a function returned an error (i.e. not `nil`).
func Error(t TestingT, err error, msgs ...string) bool {
t.Helper()
if err == nil {
return fail(t, msgs, "an error is expected but got nil")
}
return true
}
// ErrorContains asserts that a function returned an error (i.e. not `nil`)
// and that the error contains the specified substring.
func ErrorContains(t TestingT, err error, contains string, msgs ...string) bool {
t.Helper()
if !Error(t, err, msgs...) {
return false
}
actual := err.Error()
if !strings.Contains(actual, contains) {
return fail(t, msgs, "error %q does not contain %q", actual, contains)
}
return true
}
// True asserts that the specified value is true.
func True(t TestingT, value bool, msgs ...string) bool {
t.Helper()
if !value {
return fail(t, msgs, "should be true")
}
return true
}
// False asserts that the specified value is false.
func False(t TestingT, value bool, msgs ...string) bool {
t.Helper()
if value {
return fail(t, msgs, "should be false")
}
return true
}
// ErrorIs asserts the given error matches the target error using errors.Is,
// which traverses the error chain looking for a match.
func ErrorIs(t TestingT, err, target error, msgs ...string) bool {
t.Helper()
if !errors.Is(err, target) {
return fail(t, msgs, "error mismatch, expected %s, got %s", target, err)
}
return true
}
// AbortsWithMessage asserts that the code inside the specified func aborts
// (panics when crossing another realm).
// Use PanicsWithMessage for asserting local panics within the same realm.
//
// `rlm` is threaded into the callback via cross(rlm) when f is func(realm).
// It is ignored for func() callbacks. /p/ production code cannot declare
// crossing functions, so rlm is taken as the second (non-first) parameter
// — callers pass `cur` directly.
//
// NOTE: This relies on gno's `revive` mechanism to catch aborts.
func AbortsWithMessage(t TestingT, rlm realm, msg string, f any, msgs ...string) bool {
t.Helper()
var didAbort bool
var abortValue any
var r any
switch f := f.(type) {
case func():
r = revive(f) // revive() captures the value passed to panic()
case func(realm):
r = revive(func() { f(cross(rlm)) })
default:
panic("f must be of type func() or func(realm)")
}
if r != nil {
didAbort = true
abortValue = r
}
if !didAbort {
// If the function didn't abort as expected
return fail(t, msgs, "func should abort")
}
// Check if the abort value matches the expected message string
abortStr := ufmt.Sprintf("%v", abortValue)
if abortStr != msg {
return fail(t, msgs, "func should abort with message:\t%q\n\tActual abort value:\t%q", msg, abortStr)
}
// Success: function aborted with the expected message
return true
}
// AbortsContains asserts that the code inside the specified func aborts
// (panics when crossing another realm) and the abort message contains the specified substring.
// See AbortsWithMessage for `rlm` semantics.
func AbortsContains(t TestingT, rlm realm, substr string, f any, msgs ...string) bool {
t.Helper()
var didAbort bool
var abortValue any
var r any
if fn, ok := f.(func()); ok {
r = revive(fn)
} else if fn, ok := f.(func(realm)); ok {
r = revive(func() { fn(cross(rlm)) })
} else {
panic("f must be of type func() or func(realm)")
}
if r != nil {
didAbort = true
abortValue = r
}
if !didAbort {
return fail(t, msgs, "func should abort")
}
abortStr := ufmt.Sprintf("%v", abortValue)
if !strings.Contains(abortStr, substr) {
return fail(t, msgs, "func should abort with message containing:\t%q\n\tActual abort value:\t%q", substr, abortStr)
}
return true
}
// NotAborts asserts that the code inside the specified func does NOT abort
// when crossing an execution boundary.
// Note: Consider using NotPanics which checks for both panics and aborts.
// See AbortsWithMessage for `rlm` semantics.
func NotAborts(t TestingT, rlm realm, f any, msgs ...string) bool {
t.Helper()
var didAbort bool
var abortValue any
var r any
switch f := f.(type) {
case func():
r = revive(f) // revive() captures the value passed to panic()
case func(realm):
r = revive(func() { f(cross(rlm)) })
default:
panic("f must be of type func() or func(realm)")
}
if r != nil {
didAbort = true
abortValue = r
}
if didAbort {
// Fail if the function aborted when it shouldn't have
// Attempt to format the abort value in the error message
return fail(t, msgs, "func should not abort\\n\\tAbort value:\\t%v", abortValue)
}
// Success: function did not abort
return true
}
// PanicsWithMessage asserts that the code inside the specified func panics
// locally within the same execution realm.
// Use AbortsWithMessage for asserting panics that cross execution boundaries (aborts).
// See AbortsWithMessage for `rlm` semantics.
func PanicsWithMessage(t TestingT, rlm realm, msg string, f any, msgs ...string) bool {
t.Helper()
didPanic, panicValue := checkDidPanic(f, rlm)
if !didPanic {
return fail(t, msgs, "func should panic\n\tPanic value:\t%v", panicValue)
}
// Check if the abort value matches the expected message string
panicStr := ufmt.Sprintf("%v", panicValue)
if panicStr != msg {
return fail(t, msgs, "func should panic with message:\t%q\n\tActual panic value:\t%q", msg, panicStr)
}
return true
}
// PanicsContains asserts that the code inside the specified func panics
// locally within the same execution realm and the panic message contains the specified substring.
// See AbortsWithMessage for `rlm` semantics.
func PanicsContains(t TestingT, rlm realm, substr string, f any, msgs ...string) bool {
t.Helper()
didPanic, panicValue := checkDidPanic(f, rlm)
if !didPanic {
return fail(t, msgs, "func should panic\n\tPanic value:\t%v", panicValue)
}
panicStr := ufmt.Sprintf("%v", panicValue)
if !strings.Contains(panicStr, substr) {
return fail(t, msgs, "func should panic with message containing:\t%q\n\tActual panic value:\t%q", substr, panicStr)
}
return true
}
// NotPanics asserts that the code inside the specified func does NOT panic
// (within the same realm) or abort (due to a cross-realm panic).
// See AbortsWithMessage for `rlm` semantics.
func NotPanics(t TestingT, rlm realm, f any, msgs ...string) bool {
t.Helper()
var panicVal any
var didPanic bool
var abortVal any
// Use revive to catch cross-realm aborts
abortVal = revive(func() {
// Use defer+recover to catch same-realm panics
defer func() {
if r := recover(); r != nil {
didPanic = true
panicVal = r
}
}()
// Execute the function
switch f := f.(type) {
case func():
f()
case func(realm):
f(cross(rlm))
default:
panic("f must be of type func() or func(realm)")
}
})
// Check if revive caught an abort
if abortVal != nil {
return fail(t, msgs, "func should not abort\n\tAbort value:\t%+v", abortVal)
}
// Check if recover caught a panic
if didPanic {
// Format panic value for message
panicMsg := ""
if panicVal == nil {
panicMsg = "nil"
} else if err, ok := panicVal.(error); ok {
panicMsg = err.Error()
} else if str, ok := panicVal.(string); ok {
panicMsg = str
} else {
// Fallback for other types
panicMsg = "panic: unsupported type"
}
return fail(t, msgs, "func should not panic\n\tPanic value:\t%s", panicMsg)
}
return true // No panic or abort occurred
}
// Equal asserts that two objects are equal.
func Equal(t TestingT, expected, actual any, msgs ...string) bool {
t.Helper()
if expected == nil || actual == nil {
return expected == actual
}
// XXX: errors
// XXX: slices
// XXX: pointers
equal := false
ok_ := false
es, as := "unsupported type", "unsupported type"
switch ev := expected.(type) {
case string:
if av, ok := actual.(string); ok {
equal = ev == av
ok_ = true
es, as = ev, av
if !equal {
dif := diff.MyersDiff(ev, av)
return fail(t, msgs, "uassert.Equal: strings are different\n\tDiff: %s", diff.Format(dif))
}
}
case address:
if av, ok := actual.(address); ok {
equal = ev == av
ok_ = true
es, as = string(ev), string(av)
}
case int:
if av, ok := actual.(int); ok {
equal = ev == av
ok_ = true
es, as = strconv.Itoa(ev), strconv.Itoa(av)
}
case int8:
if av, ok := actual.(int8); ok {
equal = ev == av
ok_ = true
es, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))
}
case int16:
if av, ok := actual.(int16); ok {
equal = ev == av
ok_ = true
es, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))
}
case int32:
if av, ok := actual.(int32); ok {
equal = ev == av
ok_ = true
es, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))
}
case int64:
if av, ok := actual.(int64); ok {
equal = ev == av
ok_ = true
es, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))
}
case uint:
if av, ok := actual.(uint); ok {
equal = ev == av
ok_ = true
es, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)
}
case uint8:
if av, ok := actual.(uint8); ok {
equal = ev == av
ok_ = true
es, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)
}
case uint16:
if av, ok := actual.(uint16); ok {
equal = ev == av
ok_ = true
es, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)
}
case uint32:
if av, ok := actual.(uint32); ok {
equal = ev == av
ok_ = true
es, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)
}
case uint64:
if av, ok := actual.(uint64); ok {
equal = ev == av
ok_ = true
es, as = strconv.FormatUint(ev, 10), strconv.FormatUint(av, 10)
}
case bool:
if av, ok := actual.(bool); ok {
equal = ev == av
ok_ = true
if ev {
es, as = "true", "false"
} else {
es, as = "false", "true"
}
}
case float32:
if av, ok := actual.(float32); ok {
equal = ev == av
ok_ = true
}
case float64:
if av, ok := actual.(float64); ok {
equal = ev == av
ok_ = true
}
default:
return fail(t, msgs, "uassert.Equal: unsupported type")
}
/*
// XXX: implement stringer and other well known similar interfaces
type stringer interface{ String() string }
if ev, ok := expected.(stringer); ok {
if av, ok := actual.(stringer); ok {
equal = ev.String() == av.String()
ok_ = true
}
}
*/
if !ok_ {
return fail(t, msgs, "uassert.Equal: different types") // XXX: display the types
}
if !equal {
return fail(t, msgs, "uassert.Equal: same type but different value\n\texpected: %s\n\tactual: %s", es, as)
}
return true
}
// NotEqual asserts that two objects are not equal.
func NotEqual(t TestingT, expected, actual any, msgs ...string) bool {
t.Helper()
if expected == nil || actual == nil {
return expected != actual
}
// XXX: errors
// XXX: slices
// XXX: pointers
notEqual := false
ok_ := false
es, as := "unsupported type", "unsupported type"
switch ev := expected.(type) {
case string:
if av, ok := actual.(string); ok {
notEqual = ev != av
ok_ = true
es, as = ev, av
}
case address:
if av, ok := actual.(address); ok {
notEqual = ev != av
ok_ = true
es, as = string(ev), string(av)
}
case int:
if av, ok := actual.(int); ok {
notEqual = ev != av
ok_ = true
es, as = strconv.Itoa(ev), strconv.Itoa(av)
}
case int8:
if av, ok := actual.(int8); ok {
notEqual = ev != av
ok_ = true
es, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))
}
case int16:
if av, ok := actual.(int16); ok {
notEqual = ev != av
ok_ = true
es, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))
}
case int32:
if av, ok := actual.(int32); ok {
notEqual = ev != av
ok_ = true
es, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))
}
case int64:
if av, ok := actual.(int64); ok {
notEqual = ev != av
ok_ = true
es, as = strconv.Itoa(int(ev)), strconv.Itoa(int(av))
}
case uint:
if av, ok := actual.(uint); ok {
notEqual = ev != av
ok_ = true
es, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)
}
case uint8:
if av, ok := actual.(uint8); ok {
notEqual = ev != av
ok_ = true
es, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)
}
case uint16:
if av, ok := actual.(uint16); ok {
notEqual = ev != av
ok_ = true
es, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)
}
case uint32:
if av, ok := actual.(uint32); ok {
notEqual = ev != av
ok_ = true
es, as = strconv.FormatUint(uint64(ev), 10), strconv.FormatUint(uint64(av), 10)
}
case uint64:
if av, ok := actual.(uint64); ok {
notEqual = ev != av
ok_ = true
es, as = strconv.FormatUint(ev, 10), strconv.FormatUint(av, 10)
}
case bool:
if av, ok := actual.(bool); ok {
notEqual = ev != av
ok_ = true
if ev {
es, as = "true", "false"
} else {
es, as = "false", "true"
}
}
case float32:
if av, ok := actual.(float32); ok {
notEqual = ev != av
ok_ = true
}
case float64:
if av, ok := actual.(float64); ok {
notEqual = ev != av
ok_ = true
}
default:
return fail(t, msgs, "uassert.NotEqual: unsupported type")
}
/*
// XXX: implement stringer and other well known similar interfaces
type stringer interface{ String() string }
if ev, ok := expected.(stringer); ok {
if av, ok := actual.(stringer); ok {
notEqual = ev.String() != av.String()
ok_ = true
}
}
*/
if !ok_ {
return fail(t, msgs, "uassert.NotEqual: different types") // XXX: display the types
}
if !notEqual {
return fail(t, msgs, "uassert.NotEqual: same type and same value\n\texpected: %s\n\tactual: %s", es, as)
}
return true
}
func isNumberEmpty(n any) (isNumber, isEmpty bool) {
switch n := n.(type) {
// NOTE: the cases are split individually, so that n becomes of the
// asserted type; the type of '0' was correctly inferred and converted
// to the corresponding type, int, int8, etc.
case int:
return true, n == 0
case int8:
return true, n == 0
case int16:
return true, n == 0
case int32:
return true, n == 0
case int64:
return true, n == 0
case uint:
return true, n == 0
case uint8:
return true, n == 0
case uint16:
return true, n == 0
case uint32:
return true, n == 0
case uint64:
return true, n == 0
case float32:
return true, n == 0
case float64:
return true, n == 0
}
return false, false
}
func Empty(t TestingT, obj any, msgs ...string) bool {
t.Helper()
isNumber, isEmpty := isNumberEmpty(obj)
if isNumber {
if !isEmpty {
return fail(t, msgs, "uassert.Empty: not empty number: %d", obj)
}
} else {
switch val := obj.(type) {
case string:
if val != "" {
return fail(t, msgs, "uassert.Empty: not empty string: %s", val)
}
case address:
var zeroAddr address
if val != zeroAddr {
return fail(t, msgs, "uassert.Empty: not empty address: %s", string(val))
}
default:
return fail(t, msgs, "uassert.Empty: unsupported type")
}
}
return true
}
func NotEmpty(t TestingT, obj any, msgs ...string) bool {
t.Helper()
isNumber, isEmpty := isNumberEmpty(obj)
if isNumber {
if isEmpty {
return fail(t, msgs, "uassert.NotEmpty: empty number: %d", obj)
}
} else {
switch val := obj.(type) {
case string:
if val == "" {
return fail(t, msgs, "uassert.NotEmpty: empty string: %s", val)
}
case address:
var zeroAddr address
if val == zeroAddr {
return fail(t, msgs, "uassert.NotEmpty: empty address: %s", string(val))
}
default:
return fail(t, msgs, "uassert.NotEmpty: unsupported type")
}
}
return true
}
// Nil asserts that the value is nil.
func Nil(t TestingT, value any, msgs ...string) bool {
t.Helper()
if value != nil {
return fail(t, msgs, "should be nil")
}
return true
}
// NotNil asserts that the value is not nil.
func NotNil(t TestingT, value any, msgs ...string) bool {
t.Helper()
if value == nil {
return fail(t, msgs, "should not be nil")
}
return true
}
// TypedNil asserts that the value is a typed-nil (nil pointer) value.
func TypedNil(t TestingT, value any, msgs ...string) bool {
t.Helper()
if value == nil {
return fail(t, msgs, "should be typed-nil but got nil instead")
}
if !istypednil(value) {
return fail(t, msgs, "should be typed-nil")
}
return true
}
// NotTypedNil asserts that the value is not a typed-nil (nil pointer) value.
func NotTypedNil(t TestingT, value any, msgs ...string) bool {
t.Helper()
if istypednil(value) {
return fail(t, msgs, "should not be typed-nil")
}
return true
}
uassert_test.gno
package uassert_test
import (
"errors"
"fmt"
"testing"
"gno.land/p/nt/uassert/v0"
tests "gno.land/r/tests/vm"
)
// cur is a zero-value realm used as a placeholder when forwarding to
// uassert/urequire dispatch helpers that gained an `rlm realm` param.
// These tests pass `func()` callbacks (no crossing inside the callback),
// so rlm is ignored — a nil realm here is safe.
var cur realm
var _ uassert.TestingT = (*testing.T)(nil)
func TestMock(t *testing.T) {
mockT := new(mockTestingT)
mockT.empty(t)
uassert.NoError(mockT, errors.New("foo"))
mockT.equals(t, "error: unexpected error: foo")
uassert.NoError(mockT, errors.New("foo"), "custom message")
mockT.equals(t, "error: unexpected error: foo - custom message")
uassert.NoError(mockT, errors.New("foo"), "custom", "message")
mockT.equals(t, "error: unexpected error: foo - custom message")
}
func TestNoError(t *testing.T) {
mockT := new(mockTestingT)
uassert.True(t, uassert.NoError(mockT, nil))
mockT.empty(t)
uassert.False(t, uassert.NoError(mockT, errors.New("foo bar")))
mockT.equals(t, "error: unexpected error: foo bar")
}
func TestError(t *testing.T) {
mockT := new(mockTestingT)
uassert.True(t, uassert.Error(mockT, errors.New("foo bar")))
mockT.empty(t)
uassert.False(t, uassert.Error(mockT, nil))
mockT.equals(t, "error: an error is expected but got nil")
}
func TestErrorContains(t *testing.T) {
mockT := new(mockTestingT)
// nil error
var err error
uassert.False(t, uassert.ErrorContains(mockT, err, ""), "ErrorContains should return false for nil arg")
}
func TestTrue(t *testing.T) {
mockT := new(mockTestingT)
if !uassert.True(mockT, true) {
t.Error("True should return true")
}
mockT.empty(t)
if uassert.True(mockT, false) {
t.Error("True should return false")
}
mockT.equals(t, "error: should be true")
}
func TestFalse(t *testing.T) {
mockT := new(mockTestingT)
if !uassert.False(mockT, false) {
t.Error("False should return true")
}
mockT.empty(t)
if uassert.False(mockT, true) {
t.Error("False should return false")
}
mockT.equals(t, "error: should be false")
}
func TestPanicsWithMessage(cur realm, t *testing.T) {
mockT := new(mockTestingT)
if !uassert.PanicsWithMessage(mockT, cur, "panic", func() {
panic(errors.New("panic"))
}) {
t.Error("PanicsWithMessage should return true")
}
mockT.empty(t)
if uassert.PanicsWithMessage(mockT, cur, "Panic!", func() {
// noop
}) {
t.Error("PanicsWithMessage should return false")
}
mockT.equals(t, "error: func should panic\n\tPanic value:\tnil")
if uassert.PanicsWithMessage(mockT, cur, "at the disco", func() {
panic(errors.New("panic"))
}) {
t.Error("PanicsWithMessage should return false")
}
mockT.equals(t, "error: func should panic with message:\t\"at the disco\"\n\tActual panic value:\t\"panic\"")
if uassert.PanicsWithMessage(mockT, cur, "Panic!", func() {
panic("panic")
}) {
t.Error("PanicsWithMessage should return false")
}
mockT.equals(t, "error: func should panic with message:\t\"Panic!\"\n\tActual panic value:\t\"panic\"")
}
func TestPanicsContains(cur realm, t *testing.T) {
mockT := new(mockTestingT)
if !uassert.PanicsContains(mockT, cur, "panic", func() {
panic(errors.New("panic: something happened"))
}) {
t.Error("PanicsContains should return true for substring match")
}
mockT.empty(t)
if uassert.PanicsContains(mockT, cur, "notfound", func() {
panic(errors.New("panic: something happened"))
}) {
t.Error("PanicsContains should return false for missing substring")
}
mockT.equals(t, "error: func should panic with message containing:\t\"notfound\"\n\tActual panic value:\t\"panic: something happened\"")
if uassert.PanicsContains(mockT, cur, "panic", func() {
// noop
}) {
t.Error("PanicsContains should return false when no panic occurs")
}
mockT.equals(t, "error: func should panic\n\tPanic value:\tnil")
}
func TestAbortsWithMessage(cur realm, t *testing.T) {
mockT := new(mockTestingT)
if !uassert.AbortsWithMessage(mockT, cur, "abort message", func() {
tests.ExecSwitch(cross(cur), func() {
panic("abort message")
})
panic("dontcare")
}) {
t.Error("AbortsWithMessage should return true")
}
mockT.empty(t)
if uassert.AbortsWithMessage(mockT, cur, "Abort!", func() {
// noop
}) {
t.Error("AbortsWithMessage should return false")
}
mockT.equals(t, "error: func should abort")
if uassert.AbortsWithMessage(mockT, cur, "at the disco", func() {
tests.ExecSwitch(cross(cur), func() {
panic("abort message")
})
panic("dontcare")
}) {
t.Error("AbortsWithMessage should return false (wrong message)")
}
mockT.equals(t, "error: func should abort with message:\t\"at the disco\"\n\tActual abort value:\t\"abort message\"")
// Test that non-crossing panics don't count as abort.
uassert.PanicsWithMessage(mockT, cur, "non-abort panic", func() {
uassert.AbortsWithMessage(mockT, cur, "dontcare2", func() {
panic("non-abort panic")
})
t.Error("AbortsWithMessage should not have caught non-abort panic")
}, "non-abort panic")
mockT.empty(t)
// Test case where abort value is not a string
if uassert.AbortsWithMessage(mockT, cur, "doesn't matter", func() {
tests.ExecSwitch(cross(cur), func() {
panic(123) // abort with an integer
})
panic("dontcare")
}) {
t.Error("AbortsWithMessage should return false when abort value is not a string")
}
mockT.equals(t, "error: func should abort with message:\t\"doesn't matter\"\n\tActual abort value:\t\"123\"")
// XXX: test with Error
}
func TestAbortsContains(cur realm, t *testing.T) {
mockT := new(mockTestingT)
if !uassert.AbortsContains(mockT, cur, "abort", func() {
tests.ExecSwitch(cross(cur), func() {
panic("abort message: something happened")
})
panic("dontcare")
}) {
t.Error("AbortsContains should return true for substring match")
}
mockT.empty(t)
if uassert.AbortsContains(mockT, cur, "notfound", func() {
tests.ExecSwitch(cross(cur), func() {
panic("abort message: something happened")
})
panic("dontcare")
}) {
t.Error("AbortsContains should return false for missing substring")
}
mockT.equals(t, "error: func should abort with message containing:\t\"notfound\"\n\tActual abort value:\t\"abort message: something happened\"")
if uassert.AbortsContains(mockT, cur, "abort", func() {
// noop
}) {
t.Error("AbortsContains should return false when no abort occurs")
}
mockT.equals(t, "error: func should abort")
}
func TestNotAborts(cur realm, t *testing.T) {
mockT := new(mockTestingT)
if !uassert.NotPanics(mockT, cur, func() {
// noop
}) {
t.Error("NotAborts should return true")
}
mockT.empty(t)
if uassert.NotPanics(mockT, cur, func() {
tests.ExecSwitch(cross(cur), func() {
panic("Abort!")
})
panic("dontcare")
}) {
t.Error("NotAborts should return false")
}
mockT.equals(t, "error: func should not abort\n\tAbort value:\tAbort!")
}
func TestNotPanics(cur realm, t *testing.T) {
mockT := new(mockTestingT)
if !uassert.NotPanics(mockT, cur, func() {
// noop
}) {
t.Error("NotPanics should return true")
}
mockT.empty(t)
if uassert.NotPanics(mockT, cur, func() {
panic("Panic!")
}) {
t.Error("NotPanics should return false")
}
mockT.equals(t, "error: func should not panic\n\tPanic value:\tPanic!")
}
func TestEqual(t *testing.T) {
mockT := new(mockTestingT)
cases := []struct {
expected any
actual any
result bool
remark string
}{
// expected to be equal
{"Hello World", "Hello World", true, ""},
{123, 123, true, ""},
{123.5, 123.5, true, ""},
{nil, nil, true, ""},
{int32(123), int32(123), true, ""},
{uint64(123), uint64(123), true, ""},
{address("g12345"), address("g12345"), true, ""},
// XXX: continue
// not expected to be equal
{"Hello World", 42, false, ""},
{41, 42, false, ""},
{10, uint(10), false, ""},
// XXX: continue
// expected to raise errors
// XXX: todo
}
for _, c := range cases {
name := fmt.Sprintf("Equal(%v, %v)", c.expected, c.actual)
t.Run(name, func(t *testing.T) {
res := uassert.Equal(mockT, c.expected, c.actual)
if res != c.result {
t.Errorf("%s should return %v: %s - %s", name, c.result, c.remark, mockT.actualString())
}
})
}
}
func TestNotEqual(t *testing.T) {
mockT := new(mockTestingT)
cases := []struct {
expected any
actual any
result bool
remark string
}{
// expected to be not equal
{"Hello World", "Hello", true, ""},
{123, 124, true, ""},
{123.5, 123.6, true, ""},
{nil, 123, true, ""},
{int32(123), int32(124), true, ""},
{uint64(123), uint64(124), true, ""},
{address("g12345"), address("g67890"), true, ""},
// XXX: continue
// not expected to be not equal
{"Hello World", "Hello World", false, ""},
{123, 123, false, ""},
{123.5, 123.5, false, ""},
{nil, nil, false, ""},
{int32(123), int32(123), false, ""},
{uint64(123), uint64(123), false, ""},
{address("g12345"), address("g12345"), false, ""},
// XXX: continue
// expected to raise errors
// XXX: todo
}
for _, c := range cases {
name := fmt.Sprintf("NotEqual(%v, %v)", c.expected, c.actual)
t.Run(name, func(t *testing.T) {
res := uassert.NotEqual(mockT, c.expected, c.actual)
if res != c.result {
t.Errorf("%s should return %v: %s - %s", name, c.result, c.remark, mockT.actualString())
}
})
}
}
type myStruct struct {
S string
I int
}
func TestEmpty(t *testing.T) {
mockT := new(mockTestingT)
cases := []struct {
obj any
expectedEmpty bool
}{
// expected to be empty
{"", true},
{0, true},
{int(0), true},
{int32(0), true},
{int64(0), true},
{uint(0), true},
// XXX: continue
// not expected to be empty
{"Hello World", false},
{1, false},
{int32(1), false},
{uint64(1), false},
{address("g12345"), false},
// unsupported
{nil, false},
{myStruct{}, false},
{&myStruct{}, false},
}
for _, c := range cases {
name := fmt.Sprintf("Empty(%v)", c.obj)
t.Run(name, func(t *testing.T) {
res := uassert.Empty(mockT, c.obj)
if res != c.expectedEmpty {
t.Errorf("%s should return %v: %s", name, c.expectedEmpty, mockT.actualString())
}
})
}
}
func TestEqualWithStringDiff(t *testing.T) {
cases := []struct {
name string
expected string
actual string
shouldPass bool
expectedMsg string
}{
{
name: "Identical strings",
expected: "Hello, world!",
actual: "Hello, world!",
shouldPass: true,
expectedMsg: "",
},
{
name: "Different strings - simple",
expected: "Hello, world!",
actual: "Hello, World!",
shouldPass: false,
expectedMsg: "error: uassert.Equal: strings are different\n\tDiff: Hello, [-w][+W]orld!",
},
{
name: "Different strings - complex",
expected: "The quick brown fox jumps over the lazy dog",
actual: "The quick brown cat jumps over the lazy dog",
shouldPass: false,
expectedMsg: "error: uassert.Equal: strings are different\n\tDiff: The quick brown [-fox][+cat] jumps over the lazy dog",
},
{
name: "Different strings - prefix",
expected: "prefix_string",
actual: "string",
shouldPass: false,
expectedMsg: "error: uassert.Equal: strings are different\n\tDiff: [-prefix_]string",
},
{
name: "Different strings - suffix",
expected: "string",
actual: "string_suffix",
shouldPass: false,
expectedMsg: "error: uassert.Equal: strings are different\n\tDiff: string[+_suffix]",
},
{
name: "Empty string vs non-empty string",
expected: "",
actual: "non-empty",
shouldPass: false,
expectedMsg: "error: uassert.Equal: strings are different\n\tDiff: [+non-empty]",
},
{
name: "Non-empty string vs empty string",
expected: "non-empty",
actual: "",
shouldPass: false,
expectedMsg: "error: uassert.Equal: strings are different\n\tDiff: [-non-empty]",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
mockT := &mockTestingT{}
result := uassert.Equal(mockT, tc.expected, tc.actual)
if result != tc.shouldPass {
t.Errorf("Expected Equal to return %v, but got %v", tc.shouldPass, result)
}
if tc.shouldPass {
mockT.empty(t)
} else {
mockT.equals(t, tc.expectedMsg)
}
})
}
}
func TestNotEmpty(t *testing.T) {
mockT := new(mockTestingT)
cases := []struct {
obj any
expectedNotEmpty bool
}{
// expected to be empty
{"", false},
{0, false},
{int(0), false},
{int32(0), false},
{int64(0), false},
{uint(0), false},
{address(""), false},
// not expected to be empty
{"Hello World", true},
{1, true},
{int32(1), true},
{uint64(1), true},
{address("g12345"), true},
// unsupported
{nil, false},
{myStruct{}, false},
{&myStruct{}, false},
}
for _, c := range cases {
name := fmt.Sprintf("NotEmpty(%v)", c.obj)
t.Run(name, func(t *testing.T) {
res := uassert.NotEmpty(mockT, c.obj)
if res != c.expectedNotEmpty {
t.Errorf("%s should return %v: %s", name, c.expectedNotEmpty, mockT.actualString())
}
})
}
}
func TestNil(t *testing.T) {
mockT := new(mockTestingT)
if !uassert.Nil(mockT, nil) {
t.Error("Nil should return true")
}
mockT.empty(t)
if uassert.Nil(mockT, 0) {
t.Error("Nil should return false")
}
mockT.equals(t, "error: should be nil")
if uassert.Nil(mockT, (*int)(nil)) {
t.Error("Nil should return false")
}
mockT.equals(t, "error: should be nil")
}
func TestNotNil(t *testing.T) {
mockT := new(mockTestingT)
if uassert.NotNil(mockT, nil) {
t.Error("NotNil should return false")
}
mockT.equals(t, "error: should not be nil")
if !uassert.NotNil(mockT, 0) {
t.Error("NotNil should return true")
}
mockT.empty(t)
if !uassert.NotNil(mockT, (*int)(nil)) {
t.Error("NotNil should return true")
}
mockT.empty(t)
}
func TestTypedNil(t *testing.T) {
mockT := new(mockTestingT)
if uassert.TypedNil(mockT, nil) {
t.Error("TypedNil should return false")
}
mockT.equals(t, "error: should be typed-nil but got nil instead")
if uassert.TypedNil(mockT, 0) {
t.Error("TypedNil should return false")
}
mockT.equals(t, "error: should be typed-nil")
if !uassert.TypedNil(mockT, (*int)(nil)) {
t.Error("TypedNil should return true")
}
mockT.empty(t)
}
func TestNotTypedNil(t *testing.T) {
mockT := new(mockTestingT)
if !uassert.NotTypedNil(mockT, nil) {
t.Error("NotTypedNil should return true")
}
mockT.empty(t)
if !uassert.NotTypedNil(mockT, 0) {
t.Error("NotTypedNil should return true")
}
mockT.empty(t)
if uassert.NotTypedNil(mockT, (*int)(nil)) {
t.Error("NotTypedNil should return false")
}
mockT.equals(t, "error: should not be typed-nil")
}