github.com/abemedia/go-don@v0.2.2-0.20240329015135-be88e32bb73b/nilcheck_test.go (about)

     1  package don_test
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/abemedia/go-don"
     7  )
     8  
     9  func TestNilCheck(t *testing.T) {
    10  	tests := []struct {
    11  		typ      any
    12  		data     any
    13  		message  string
    14  		expected bool
    15  	}{
    16  		{
    17  			message:  "nil interface",
    18  			typ:      nil,
    19  			data:     nil,
    20  			expected: true,
    21  		},
    22  		{
    23  			message:  "empty string",
    24  			typ:      "",
    25  			data:     "",
    26  			expected: true,
    27  		},
    28  		{
    29  			message:  "nil struct",
    30  			typ:      (*struct{})(nil),
    31  			data:     (*struct{})(nil),
    32  			expected: true,
    33  		},
    34  		{
    35  			message:  "zero struct",
    36  			typ:      struct{}{},
    37  			data:     struct{}{},
    38  			expected: false,
    39  		},
    40  		{
    41  			message:  "nil map",
    42  			typ:      (map[string]string)(nil),
    43  			data:     (map[string]string)(nil),
    44  			expected: true,
    45  		},
    46  		{
    47  			message:  "zero map",
    48  			typ:      (map[string]string)(nil),
    49  			data:     map[string]string{},
    50  			expected: false,
    51  		},
    52  		{
    53  			message:  "non-zero map",
    54  			typ:      (map[string]string)(nil),
    55  			data:     map[string]string{"foo": "bar"},
    56  			expected: false,
    57  		},
    58  		{
    59  			message:  "nil slice",
    60  			typ:      ([]string)(nil),
    61  			data:     ([]string)(nil),
    62  			expected: true,
    63  		},
    64  		{
    65  			message:  "zero slice",
    66  			typ:      ([]string)(nil),
    67  			data:     []string{},
    68  			expected: false,
    69  		},
    70  		{
    71  			message:  "non-zero slice",
    72  			typ:      ([]string)(nil),
    73  			data:     []string{"aa"},
    74  			expected: false,
    75  		},
    76  		{
    77  			message:  "boolean",
    78  			typ:      false,
    79  			data:     false,
    80  			expected: false,
    81  		},
    82  		{
    83  			message:  "integer",
    84  			typ:      0,
    85  			data:     0,
    86  			expected: false,
    87  		},
    88  		{
    89  			message: "non-zero slice pointer",
    90  			typ:     (*[]string)(nil),
    91  			data: func() any {
    92  				m := []string{"aa"}
    93  				return &m
    94  			}(),
    95  			expected: false,
    96  		},
    97  	}
    98  
    99  	for _, test := range tests {
   100  		isNil := don.NewNilCheck(test.typ)
   101  		if isNil(test.data) != test.expected {
   102  			t.Errorf("%s should be %t", test.message, test.expected)
   103  		}
   104  	}
   105  }