-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathregistry_test.go
More file actions
345 lines (302 loc) · 11.6 KB
/
registry_test.go
File metadata and controls
345 lines (302 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Copyright 2023-2026 Buf Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package protovalidate
import (
"fmt"
"sync"
"testing"
pvcel "buf.build/go/protovalidate/cel"
"github.com/google/cel-go/cel"
"github.com/google/cel-go/common/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/dynamicpb"
)
// newTestEnv creates a new CEL environment with the protovalidate library
// and registry attached, similar to how the validator creates its env.
func newTestEnv(t testing.TB) *cel.Env {
t.Helper()
reg, err := newRegistry()
require.NoError(t, err)
env, err := cel.NewEnv(
cel.CustomTypeProvider(reg),
cel.CustomTypeAdapter(reg),
cel.Lib(pvcel.NewLibrary()),
)
require.NoError(t, err)
return env
}
func TestRegistryTypeShadowing(t *testing.T) {
t.Parallel()
// Create base environment with protovalidate library and registry
baseEnv := newTestEnv(t)
// Extend with first dynamic message (id: string)
env1, err := extendEnv(baseEnv,
cel.Types(newRegistryTestMessageType(t, descriptorpb.FieldDescriptorProto_TYPE_STRING).New().Interface()),
)
require.NoError(t, err)
// Compile and run expression with string value
ast, issues := env1.Compile(`test.Duplicate{id: "abc"}`)
require.NoError(t, issues.Err())
prog, err := env1.Program(ast)
require.NoError(t, err)
_, _, err = prog.Eval(cel.NoVars())
require.NoError(t, err)
// Extend base (not env1) with second dynamic message (id: int32)
env2, err := extendEnv(baseEnv,
cel.Types(newRegistryTestMessageType(t, descriptorpb.FieldDescriptorProto_TYPE_INT32).New().Interface()),
)
require.NoError(t, err)
// Compile expression with string value - should fail because env2 expects int32
_, issues = env2.Compile(`test.Duplicate{id: "abc"}`)
require.Error(t, issues.Err(), "env2 should expect int32, not string")
// Verify env2 can compile with int32 value
ast, issues = env2.Compile(`test.Duplicate{id: 123}`)
require.NoError(t, issues.Err())
prog, err = env2.Program(ast)
require.NoError(t, err)
_, _, err = prog.Eval(cel.NoVars())
require.NoError(t, err)
}
func TestRegistryDeepChain(t *testing.T) {
t.Parallel()
const depth = 10
baseEnv := newTestEnv(t)
// Create a chain of extended environments, each registering a unique type
envs := make([]*cel.Env, depth)
envs[0] = baseEnv
for i := 1; i < depth; i++ {
msgType := newRegistryTestMessageTypeWithName(t, fmt.Sprintf("test.Level%d", i), "Message",
descriptorpb.FieldDescriptorProto_TYPE_INT32)
var err error
envs[i], err = extendEnv(envs[i-1], cel.Types(msgType.New().Interface()))
require.NoError(t, err)
}
// The deepest environment should be able to see all types from the chain
deepestEnv := envs[depth-1]
for i := 1; i < depth; i++ {
expr := fmt.Sprintf(`test.Level%d.Message{value: %d}`, i, i)
ast, issues := deepestEnv.Compile(expr)
require.NoError(t, issues.Err(), "level %d", i)
prog, err := deepestEnv.Program(ast)
require.NoError(t, err, "level %d", i)
_, _, err = prog.Eval(cel.NoVars())
require.NoError(t, err, "level %d", i)
}
// Middle environment should only see types from its ancestors
middleEnv := envs[depth/2]
for i := 1; i <= depth/2; i++ {
expr := fmt.Sprintf(`test.Level%d.Message{value: %d}`, i, i)
_, issues := middleEnv.Compile(expr)
require.NoError(t, issues.Err(), "middle env should see level %d", i)
}
for i := depth/2 + 1; i < depth; i++ {
expr := fmt.Sprintf(`test.Level%d.Message{value: %d}`, i, i)
_, issues := middleEnv.Compile(expr)
require.Error(t, issues.Err(), "middle env should NOT see level %d", i)
}
}
func TestRegistryConcurrentAccess(t *testing.T) {
t.Parallel()
baseEnv := newTestEnv(t)
const numGoroutines = 50
const numOpsPerGoroutine = 100
// Create all message types and environments before spawning goroutines
// to avoid require assertions in goroutines
envs := make([]*cel.Env, numGoroutines)
for i := range numGoroutines {
msgType := newRegistryTestMessageTypeWithName(t, fmt.Sprintf("test.Concurrent%d", i), "Message",
descriptorpb.FieldDescriptorProto_TYPE_STRING)
var err error
envs[i], err = extendEnv(baseEnv, cel.Types(msgType.New().Interface()))
require.NoError(t, err)
}
var wg sync.WaitGroup
for i := range numGoroutines {
wg.Add(1)
go func() {
defer wg.Done()
env := envs[i]
// Repeatedly compile and evaluate expressions
for range numOpsPerGoroutine {
expr := fmt.Sprintf(`test.Concurrent%d.Message{value: "test"}`, i)
ast, issues := env.Compile(expr)
assert.NoError(t, issues.Err())
if issues.Err() != nil {
continue
}
prog, err := env.Program(ast)
assert.NoError(t, err)
if err != nil {
continue
}
_, _, err = prog.Eval(cel.NoVars())
assert.NoError(t, err)
}
}()
}
wg.Wait()
}
func TestRegistryCoreTypeIdents(t *testing.T) {
t.Parallel()
// Verify that a root registry exposes core CEL type identifiers
// (string, int, bool, etc.) so that expressions like
// type(x) == string can compile. See #304.
env := newTestEnv(t)
ast, issues := env.Compile(`type("hello") == string`)
require.NoError(t, issues.Err())
prog, err := env.Program(ast)
require.NoError(t, err)
out, _, err := prog.Eval(cel.NoVars())
require.NoError(t, err)
require.Equal(t, true, out.Value())
}
func TestRegistryNativeToValueDelegation(t *testing.T) {
t.Parallel()
// Create a chain: root -> child -> grandchild
root, err := newRegistry()
require.NoError(t, err)
child := root.Copy()
grandchild := child.Copy()
// Register a message type only in child
msgType := newRegistryTestMessageTypeWithName(t, "test.delegation", "Message",
descriptorpb.FieldDescriptorProto_TYPE_STRING)
require.NoError(t, child.RegisterMessage(msgType.New().Interface()))
// Create a message instance
msg := msgType.New()
msg.Set(msgType.Descriptor().Fields().ByName("value"), protoreflect.ValueOfString("hello"))
// Grandchild should be able to convert via delegation to child
result := grandchild.NativeToValue(msg.Interface())
require.False(t, types.IsError(result), "grandchild should delegate to child")
// Root should NOT be able to convert (type not registered there)
result = root.NativeToValue(msg.Interface())
require.True(t, types.IsError(result), "root should not know about the type")
}
func TestRegistryMessageFirstRegistrationWins(t *testing.T) {
t.Parallel()
root, err := newRegistry()
require.NoError(t, err)
child := root.Copy()
// Register a message with certain fields in root
rootMsgType := newRegistryTestMessageTypeWithFields(t, "test.fields", "Message", map[string]descriptorpb.FieldDescriptorProto_Type{
"field_a": descriptorpb.FieldDescriptorProto_TYPE_STRING,
"field_b": descriptorpb.FieldDescriptorProto_TYPE_INT32,
})
require.NoError(t, root.RegisterMessage(rootMsgType.New().Interface()))
// Attempt to register a different version with different fields in child.
// First-registration-wins semantics: child's registration is skipped
// because the message is already visible through the parent.
childMsgType := newRegistryTestMessageTypeWithFields(t, "test.fields", "Message", map[string]descriptorpb.FieldDescriptorProto_Type{
"field_x": descriptorpb.FieldDescriptorProto_TYPE_BOOL,
"field_y": descriptorpb.FieldDescriptorProto_TYPE_DOUBLE,
"field_z": descriptorpb.FieldDescriptorProto_TYPE_BYTES,
})
require.NoError(t, child.RegisterMessage(childMsgType.New().Interface()))
// Child sees root's fields (first registration wins, no shadowing for RegisterMessage)
childFields, found := child.FindStructFieldNames("test.fields.Message")
require.True(t, found)
require.ElementsMatch(t, []string{"field_a", "field_b"}, childFields)
// Root should see original field names
rootFields, found := root.FindStructFieldNames("test.fields.Message")
require.True(t, found)
require.ElementsMatch(t, []string{"field_a", "field_b"}, rootFields)
}
func newRegistryTestMessageType(t testing.TB, fieldType descriptorpb.FieldDescriptorProto_Type) protoreflect.MessageType {
t.Helper()
files, err := protodesc.NewFiles(&descriptorpb.FileDescriptorSet{
File: []*descriptorpb.FileDescriptorProto{{
Name: proto.String("test.proto"),
Package: proto.String("test"),
Syntax: proto.String("proto3"),
MessageType: []*descriptorpb.DescriptorProto{{
Name: proto.String("Duplicate"),
Field: []*descriptorpb.FieldDescriptorProto{{
Name: proto.String("id"),
Number: proto.Int32(1),
Type: fieldType.Enum(),
JsonName: proto.String("id"),
Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
}},
}},
}},
})
require.NoError(t, err)
desc, err := files.FindDescriptorByName("test.Duplicate")
require.NoError(t, err)
msgDesc, ok := desc.(protoreflect.MessageDescriptor)
require.True(t, ok)
return dynamicpb.NewMessageType(msgDesc)
}
func newRegistryTestMessageTypeWithName(t testing.TB, pkg, name string, fieldType descriptorpb.FieldDescriptorProto_Type) protoreflect.MessageType {
t.Helper()
files, err := protodesc.NewFiles(&descriptorpb.FileDescriptorSet{
File: []*descriptorpb.FileDescriptorProto{{
Name: proto.String(fmt.Sprintf("%s.%s.proto", pkg, name)),
Package: proto.String(pkg),
Syntax: proto.String("proto3"),
MessageType: []*descriptorpb.DescriptorProto{{
Name: proto.String(name),
Field: []*descriptorpb.FieldDescriptorProto{{
Name: proto.String("value"),
Number: proto.Int32(1),
Type: fieldType.Enum(),
JsonName: proto.String("value"),
Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
}},
}},
}},
})
require.NoError(t, err)
desc, err := files.FindDescriptorByName(protoreflect.FullName(pkg + "." + name))
require.NoError(t, err)
msgDesc, ok := desc.(protoreflect.MessageDescriptor)
require.True(t, ok)
return dynamicpb.NewMessageType(msgDesc)
}
func newRegistryTestMessageTypeWithFields(t testing.TB, pkg, name string, fields map[string]descriptorpb.FieldDescriptorProto_Type) protoreflect.MessageType {
t.Helper()
fieldDescs := make([]*descriptorpb.FieldDescriptorProto, 0, len(fields))
fieldNum := int32(1)
for fieldName, fieldType := range fields {
fieldDescs = append(fieldDescs, &descriptorpb.FieldDescriptorProto{
Name: proto.String(fieldName),
Number: proto.Int32(fieldNum),
Type: fieldType.Enum(),
JsonName: proto.String(fieldName),
Label: descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum(),
})
fieldNum++
}
files, err := protodesc.NewFiles(&descriptorpb.FileDescriptorSet{
File: []*descriptorpb.FileDescriptorProto{{
Name: proto.String(fmt.Sprintf("%s.%s.proto", pkg, name)),
Package: proto.String(pkg),
Syntax: proto.String("proto3"),
MessageType: []*descriptorpb.DescriptorProto{{
Name: proto.String(name),
Field: fieldDescs,
}},
}},
})
require.NoError(t, err)
desc, err := files.FindDescriptorByName(protoreflect.FullName(pkg + "." + name))
require.NoError(t, err)
msgDesc, ok := desc.(protoreflect.MessageDescriptor)
require.True(t, ok)
return dynamicpb.NewMessageType(msgDesc)
}