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

Function TestFunctionSingletonBinding

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

Source from the content-addressed store, hash-verified

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