github.com/authzed/spicedb@v1.32.1-0.20240520085336-ebda56537386/internal/dispatch/remote/expr_test.go (about) 1 package remote 2 3 import ( 4 "testing" 5 6 "github.com/stretchr/testify/require" 7 8 corev1 "github.com/authzed/spicedb/pkg/proto/core/v1" 9 dispatchv1 "github.com/authzed/spicedb/pkg/proto/dispatch/v1" 10 ) 11 12 func TestParseDispatchExpression(t *testing.T) { 13 tcs := []struct { 14 name string 15 expr string 16 expectedError string 17 }{ 18 { 19 "empty", 20 "", 21 "mismatched input '<EOF>'", 22 }, 23 { 24 "returns string", 25 "'somestring'", 26 "a list[string] value", 27 }, 28 { 29 "invalid expression", 30 "a.b.c!d", 31 "mismatched input '!'", 32 }, 33 { 34 "valid expression", 35 "['prewarm']", 36 "", 37 }, 38 { 39 "valid big expression", 40 "request.resource_relation.namespace == 'foo' ? ['prewarm'] : []", 41 "", 42 }, 43 } 44 45 for _, tc := range tcs { 46 tc := tc 47 t.Run(tc.name, func(t *testing.T) { 48 _, err := ParseDispatchExpression("somemethod", tc.expr) 49 if tc.expectedError != "" { 50 require.ErrorContains(t, err, tc.expectedError) 51 } else { 52 require.NoError(t, err) 53 } 54 }) 55 } 56 } 57 58 func TestRunCheckDispatchExpr(t *testing.T) { 59 tcs := []struct { 60 name string 61 expr string 62 request *dispatchv1.DispatchCheckRequest 63 expectedResult []string 64 expectedError string 65 }{ 66 { 67 "static", 68 "['prewarm']", 69 nil, 70 []string{"prewarm"}, 71 "", 72 }, 73 { 74 "basic", 75 "request.resource_relation.namespace == 'somenamespace' ? ['prewarm'] : ['other']", 76 &dispatchv1.DispatchCheckRequest{ 77 ResourceRelation: &corev1.RelationReference{ 78 Namespace: "somenamespace", 79 Relation: "somerelation", 80 }, 81 }, 82 []string{"prewarm"}, 83 "", 84 }, 85 { 86 "basic other branch", 87 "request.resource_relation.namespace == 'somethingelse' ? ['prewarm'] : ['other']", 88 &dispatchv1.DispatchCheckRequest{ 89 ResourceRelation: &corev1.RelationReference{ 90 Namespace: "somenamespace", 91 Relation: "somerelation", 92 }, 93 }, 94 []string{"other"}, 95 "", 96 }, 97 { 98 "invalid field", 99 "request.resource_relation.invalidfield == 'somethingelse' ? ['prewarm'] : ['other']", 100 &dispatchv1.DispatchCheckRequest{ 101 ResourceRelation: &corev1.RelationReference{ 102 Namespace: "somenamespace", 103 Relation: "somerelation", 104 }, 105 }, 106 nil, 107 "no such field 'invalidfield'", 108 }, 109 } 110 111 for _, tc := range tcs { 112 tc := tc 113 t.Run(tc.name, func(t *testing.T) { 114 parsed, err := ParseDispatchExpression("check", tc.expr) 115 require.NoError(t, err) 116 117 resp, err := RunDispatchExpr(parsed, tc.request) 118 if tc.expectedError != "" { 119 require.ErrorContains(t, err, tc.expectedError) 120 } else { 121 require.Equal(t, tc.expectedResult, resp) 122 } 123 }) 124 } 125 }