From 78a940a0d803f966b14a42977efbdac623c539c9 Mon Sep 17 00:00:00 2001 From: Jason Lee Date: Sun, 24 Jul 2022 21:29:56 +0800 Subject: [PATCH] Add assert.Len, assert.NotNil, assert.Empty --- assert.go | 34 ++++++++++++++++++++++++++++++++++ assert_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/assert.go b/assert.go index 77895ca..1cc385f 100644 --- a/assert.go +++ b/assert.go @@ -232,3 +232,37 @@ func Nil(t TestingT, object any, msgAndArgs ...any) bool { } return testifyAssert.Nil(t, object, msgAndArgs...) } + +// NotNil asserts that the specified object is not nil. +// +// assert.NotNil(t, "hello") +// +func NotNil(t TestingT, object any, msgAndArgs ...any) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return testifyAssert.NotNil(t, object, msgAndArgs...) +} + +// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either +// a slice or a channel with len == 0. +// +// assert.Empty(t, "") +// +func Empty(t TestingT, object any, msgAndArgs ...any) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return testifyAssert.Empty(t, object, msgAndArgs...) +} + +// Len asserts that the specified object has specific length. +// Len also fails if the object has a type that len() not accept. +// +// assert.Len(t, mySlice, 3) +func Len(t TestingT, object any, length int, msgAndArgs ...any) bool { + if h, ok := t.(tHelper); ok { + h.Helper() + } + return testifyAssert.Len(t, object, length, msgAndArgs...) +} diff --git a/assert_test.go b/assert_test.go index df310c0..db2208b 100644 --- a/assert_test.go +++ b/assert_test.go @@ -175,4 +175,40 @@ func Test_AssertNil(t *testing.T) { testAssert(t, false, func(t *testing.T) bool { return Nil(t, []any{"hello"}) }) + + testAssert(t, true, func(t *testing.T) bool { + return NotNil(t, []any{"hello"}) + }) + + testAssert(t, false, func(t *testing.T) bool { + return NotNil(t, nil) + }) + + testAssert(t, true, func(t *testing.T) bool { + return Empty(t, nil) + }) + + testAssert(t, true, func(t *testing.T) bool { + return Empty(t, "") + }) + + testAssert(t, true, func(t *testing.T) bool { + return Empty(t, []any{}) + }) + + testAssert(t, false, func(t *testing.T) bool { + return Empty(t, []any{"a"}) + }) + + testAssert(t, false, func(t *testing.T) bool { + return Empty(t, "1") + }) + + testAssert(t, true, func(t *testing.T) bool { + return Len(t, []any{"a", "b"}, 2) + }) + + testAssert(t, false, func(t *testing.T) bool { + return Len(t, []any{"a", "b"}, 3) + }) }