github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/genutil/ensure_test.go (about)

     1  package genutil
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  	"github.com/stretchr/testify/require"
     8  )
     9  
    10  func TestEnsureUInt32(t *testing.T) {
    11  	tcs := []struct {
    12  		name  string
    13  		value int
    14  		want  uint32
    15  		err   bool
    16  	}{
    17  		{
    18  			name:  "zero",
    19  			value: 0,
    20  			want:  0,
    21  		},
    22  		{
    23  			name:  "max",
    24  			value: int(^uint32(0)),
    25  			want:  ^uint32(0),
    26  		},
    27  		{
    28  			name:  "overflow",
    29  			value: int(^uint32(0)) + 1,
    30  			err:   true,
    31  		},
    32  	}
    33  
    34  	for _, tc := range tcs {
    35  		t.Run(tc.name, func(t *testing.T) {
    36  			if tc.err {
    37  				assert.Panics(t, func() {
    38  					_, _ = EnsureUInt32(tc.value)
    39  				}, "The code did not panic")
    40  				return
    41  			}
    42  
    43  			got, err := EnsureUInt32(tc.value)
    44  			require.NoError(t, err)
    45  			require.Equal(t, tc.want, got)
    46  		})
    47  	}
    48  }
    49  
    50  func TestEnsureUInt8(t *testing.T) {
    51  	tcs := []struct {
    52  		name  string
    53  		value int
    54  		want  uint8
    55  		err   bool
    56  	}{
    57  		{
    58  			name:  "zero",
    59  			value: 0,
    60  			want:  0,
    61  		},
    62  		{
    63  			name:  "max",
    64  			value: int(^uint8(0)),
    65  			want:  ^uint8(0),
    66  		},
    67  		{
    68  			name:  "overflow",
    69  			value: int(^uint8(0)) + 1,
    70  			err:   true,
    71  		},
    72  	}
    73  
    74  	for _, tc := range tcs {
    75  		t.Run(tc.name, func(t *testing.T) {
    76  			if tc.err {
    77  				assert.Panics(t, func() {
    78  					_, _ = EnsureUInt8(tc.value)
    79  				}, "The code did not panic")
    80  				return
    81  			}
    82  
    83  			got, err := EnsureUInt8(tc.value)
    84  			require.NoError(t, err)
    85  			require.Equal(t, tc.want, got)
    86  		})
    87  	}
    88  }