github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/pkg/caveats/types/encoded_test.go (about)

     1  package types
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/require"
     7  
     8  	core "github.com/authzed/spicedb/pkg/proto/core/v1"
     9  )
    10  
    11  type testCase struct {
    12  	vtype VariableType
    13  }
    14  
    15  func TestEncodeDecodeTypes(t *testing.T) {
    16  	tcs := []testCase{
    17  		{
    18  			vtype: IntType,
    19  		},
    20  		{
    21  			vtype: MustListType(IntType),
    22  		},
    23  		{
    24  			vtype: MustListType(StringType),
    25  		},
    26  		{
    27  			vtype: MustMapType(AnyType),
    28  		},
    29  		{
    30  			vtype: MustMapType(UIntType),
    31  		},
    32  		{
    33  			vtype: IPAddressType,
    34  		},
    35  	}
    36  
    37  	for _, def := range definitions {
    38  		if def.childTypeCount == 0 {
    39  			v, err := def.asVariableType(nil)
    40  			require.NoError(t, err)
    41  			tcs = append(tcs, testCase{
    42  				vtype: *v,
    43  			})
    44  		}
    45  	}
    46  
    47  	for _, tc := range tcs {
    48  		tc := tc
    49  		t.Run(tc.vtype.String(), func(t *testing.T) {
    50  			encoded := EncodeParameterType(tc.vtype)
    51  			decoded, err := DecodeParameterType(encoded)
    52  			require.NoError(t, err)
    53  			require.Equal(t, tc.vtype.String(), decoded.String())
    54  		})
    55  	}
    56  }
    57  
    58  func TestDecodeUnknownType(t *testing.T) {
    59  	_, err := DecodeParameterType(&core.CaveatTypeReference{
    60  		TypeName: "unknown",
    61  	})
    62  	require.NotNil(t, err)
    63  	require.Equal(t, err.Error(), "unknown caveat parameter type `unknown`")
    64  }
    65  
    66  func TestDecodeWrongChildTypeCount(t *testing.T) {
    67  	_, err := DecodeParameterType(&core.CaveatTypeReference{
    68  		TypeName: "list",
    69  	})
    70  	require.NotNil(t, err)
    71  	require.Equal(t, err.Error(), "caveat parameter type `list` requires 0 child types; found 1")
    72  }