Skip to content

Commit

Permalink
check: Add Zero*
Browse files Browse the repository at this point in the history
  • Loading branch information
thatguystone committed Nov 5, 2024
1 parent ef242f2 commit bd5799c
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 0 deletions.
12 changes: 12 additions & 0 deletions check/check.cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,18 @@ var funcs = []Func{
Check: "checkNotNil(v)",
Doc: "Check that v is not nil. This is a strict equality check.",
},
{
Name: "Zero",
Args: "v any",
Check: "checkZero(v)",
Doc: "Check that v is the zero value for its type.",
},
{
Name: "NotZero",
Args: "v any",
Check: "checkNotZero(v)",
Doc: "Check that v is not the zero value for its type.",
},
{
Name: "ErrIs",
Args: "err, target error",
Expand Down
18 changes: 18 additions & 0 deletions check/check.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,24 @@ func checkNotNil(v any) (string, bool) {
return "Expected something, got nil", false
}

func checkZero(v any) (string, bool) {
rv := reflect.ValueOf(v)
if !rv.IsValid() || rv.IsZero() {
return "", true
}

return equalMsg(v, reflect.Zero(rv.Type()).Interface()), false
}

func checkNotZero(v any) (string, bool) {
rv := reflect.ValueOf(v)
if rv.IsValid() && !rv.IsZero() {
return "", true
}

return "Expected something, got {}", false
}

func checkErrIs(err, target error) (string, bool) {
if errors.Is(err, target) {
return "", true
Expand Down
76 changes: 76 additions & 0 deletions check/check.out.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 16 additions & 0 deletions check/check_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ func TestCheckNotNil(t *testing.T) {
testCheck(checkNotNil(nil))(t, false)
}

func TestCheckZero(t *testing.T) {
testCheck(checkZero(nil))(t, true)
testCheck(checkZero(0))(t, true)
testCheck(checkZero((*int)(nil)))(t, true)
testCheck(checkZero(1))(t, false)
testCheck(checkZero(new(int)))(t, false)
}

func TestCheckNotZero(t *testing.T) {
testCheck(checkNotZero(1))(t, true)
testCheck(checkNotZero(new(int)))(t, true)
testCheck(checkNotZero(nil))(t, false)
testCheck(checkNotZero(0))(t, false)
testCheck(checkNotZero((*int)(nil)))(t, false)
}

func TestCheckErrIs(t *testing.T) {
err := &os.PathError{
Op: "test",
Expand Down

0 comments on commit bd5799c

Please sign in to comment.