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

Function TestGlobalVars

cel/cel_test.go:822–909  ·  view source on GitHub ↗
(t *testing.T)

Source from the content-addressed store, hash-verified

820}
821
822func TestGlobalVars(t *testing.T) {
823 env := testEnv(t,
824 Variable("attrs", MapType(StringType, DynType)),
825 Variable("default", DynType),
826 Function("get",
827 MemberOverload("get_map", []*Type{MapType(StringType, DynType), StringType, DynType}, DynType,
828 FunctionBinding(func(args ...ref.Val) ref.Val {
829 attrs, ok := args[0].(traits.Mapper)
830 if !ok {
831 return types.NewErr(
832 "invalid operand of type '%v' to obj.get(key, def)",
833 args[0].Type())
834 }
835 key := args[1]
836 defVal := args[2]
837 if attrs.Contains(key) == types.True {
838 return attrs.Get(key)
839 }
840 return defVal
841 }),
842 ),
843 ),
844 )
845 ast, iss := env.Compile(`attrs.get("first", attrs.get("second", default))`)
846 if iss.Err() != nil {
847 t.Fatalf("e.Parse() failed: %v", iss.Err())
848 }
849
850 // Global variables can be configured as a ProgramOption and optionally overridden on Eval.
851 // Add a previous globals map to confirm the order of shadowing and a final empty global
852 // map to show that globals are not clobbered.
853 prg, err := env.Program(ast,
854 Globals(map[string]any{
855 "default": "shadow me",
856 }),
857 Globals(map[string]any{
858 "default": "third",
859 }),
860 Globals(map[string]any{}),
861 )
862 if err != nil {
863 t.Fatalf("e.Program() failed: %v", err)
864 }
865
866 t.Run("bad_attrs", func(t *testing.T) {
867 out, _, err := prg.Eval(map[string]any{
868 "attrs": []string{"one", "two"},
869 })
870 if err == nil {
871 t.Errorf("prg.Eval() of incorrect arg type invoked function, wanted error, got %v", out)
872 }
873 })
874
875 t.Run("global_default", func(t *testing.T) {
876 vars := map[string]any{
877 "attrs": map[string]any{},
878 }
879 out, _, err := prg.Eval(vars)

Callers

nothing calls this directly

Calls 15

NewErrFunction · 0.92
StringTypeAlias · 0.92
GlobalsFunction · 0.85
ErrMethod · 0.80
ProgramMethod · 0.80
testEnvFunction · 0.70
VariableFunction · 0.70
FunctionFunction · 0.70
MemberOverloadFunction · 0.70
FunctionBindingFunction · 0.70
TypeMethod · 0.65
ContainsMethod · 0.65

Tested by

no test coverage detected