Skip to content

Commit

Permalink
imporoves nil assertion to properly assert nil of pointers, slices, m…
Browse files Browse the repository at this point in the history
…aps etc. (#22)
  • Loading branch information
ppapapetrou76 authored Apr 23, 2021
1 parent 2e5c7f5 commit eb11bec
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 1 deletion.
24 changes: 24 additions & 0 deletions assert/any_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import (
"testing"
)

type foo struct{}

var f *foo

func TestAssertable_IsNil(t *testing.T) {
tests := []struct {
name string
Expand All @@ -16,6 +20,16 @@ func TestAssertable_IsNil(t *testing.T) {
actual: nil,
shouldFail: false,
},
{
name: "should assert not nil pointer",
actual: new(interface{}),
shouldFail: true,
},
{
name: "should assert nil pointer",
actual: f,
shouldFail: false,
},
{
name: "should assert non-empty string",
actual: "non-nil",
Expand Down Expand Up @@ -47,6 +61,16 @@ func TestAssertable_IsNotNil(t *testing.T) {
actual: "non-nil",
shouldFail: false,
},
{
name: "should assert not nil pointer",
actual: new(interface{}),
shouldFail: false,
},
{
name: "should assert nil pointer",
actual: f,
shouldFail: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down
11 changes: 10 additions & 1 deletion internal/pkg/values/any_value.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,16 @@ func (s AnyValue) IsLessOrEqualTo(expected interface{}) bool {

// IsNil returns true if the value is nil, else false.
func (s AnyValue) IsNil() bool {
return s.value == nil
if s.value == nil {
return true
}
// nolint:exhaustive //covered by default case
switch reflect.TypeOf(s.value).Kind() {
case reflect.Ptr, reflect.Map, reflect.Array, reflect.Chan, reflect.Slice:
return reflect.ValueOf(s.value).IsNil()
default:
return false
}
}

// IsNotNil returns true if the value is not nil, else false.
Expand Down

0 comments on commit eb11bec

Please sign in to comment.