MCPcopy Create free account
hub / github.com/cel-expr/cel-go / TestFunctionSingletonBinding

Function TestFunctionSingletonBinding

common/decls/decls_test.go:206–254  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

204}
205
206func TestFunctionSingletonBinding(t *testing.T) {
207 size, err := NewFunction("size",
208 // Since the singleton requires that the operand is a traits.Sizer, the type guards can be
209 // disabled for a minor boost in performance, and because the argument type-checking
210 // doesn't actually give much additional benefit. The drawback is that invalid signatures
211 // at type-check might be valid at runtime.
212 DisableTypeGuards(true),
213 Overload("size_map",
214 []*types.Type{types.NewMapType(types.NewTypeParamType("K"), types.NewTypeParamType("V"))}, types.IntType),
215 Overload("size_list",
216 []*types.Type{types.NewListType(types.NewTypeParamType("V"))}, types.IntType),
217 Overload("size_string",
218 []*types.Type{types.StringType}, types.IntType),
219 MemberOverload("map_size",
220 []*types.Type{types.NewMapType(types.NewTypeParamType("K"), types.NewTypeParamType("V"))}, types.IntType),
221 MemberOverload("list_size",
222 []*types.Type{types.NewListType(types.NewTypeParamType("V"))}, types.IntType),
223 MemberOverload("string_size",
224 []*types.Type{types.StringType}, types.IntType),
225 SingletonUnaryBinding(func(arg ref.Val) ref.Val {
226 return arg.(traits.Sizer).Size()
227 }, traits.SizerType),
228 )
229 if err != nil {
230 t.Fatalf("NewFunction() failed: %v", err)
231 }
232 if !size.HasSingletonBinding() {
233 t.Error("size.HasSingletonBinding() got false, wanted true")
234 }
235 bindings, err := size.Bindings()
236 if err != nil {
237 t.Fatalf("size.Bindings() failed: %v", err)
238 }
239 if len(bindings) != 1 {
240 t.Errorf("size.Bindings() got %d bindings, wanted 1", len(bindings))
241 }
242 if bindings[0].Unary == nil {
243 t.Fatalf("size.Bindings() missing singleton unary binding")
244 }
245 result := bindings[0].Unary(types.String("hello"))
246 if result.Equal(types.Int(5)) != types.True {
247 t.Errorf("size('hello') got %v, wanted 5", result)
248 }
249 // Invalid at type-check, but valid since type guard checks have been disabled
250 result = bindings[0].Unary(types.Bytes("hello"))
251 if result.Equal(types.Int(5)) != types.True {
252 t.Errorf("size(b'hello') got %v, wanted 5", result)
253 }
254}
255
256func TestVariableDocumentation(t *testing.T) {
257 v := NewVariableWithDoc("var", types.StringType, "string variable")

Callers

nothing calls this directly

Calls 15

NewMapTypeFunction · 0.92
NewTypeParamTypeFunction · 0.92
NewListTypeFunction · 0.92
StringTypeAlias · 0.92
IntTypeAlias · 0.92
BytesTypeAlias · 0.92
DisableTypeGuardsFunction · 0.85
HasSingletonBindingMethod · 0.80
BindingsMethod · 0.80
NewFunctionFunction · 0.70
OverloadFunction · 0.70
MemberOverloadFunction · 0.70

Tested by

no test coverage detected