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

Function TestCustomMacro

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

Source from the content-addressed store, hash-verified

933}
934
935func TestCustomMacro(t *testing.T) {
936 joinMacro := NewReceiverMacro("join", 1,
937 func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
938 delim := args[0]
939 iterIdent := meh.Ident("__iter__")
940 accuIdent := meh.AccuIdent()
941 accuInit := meh.LiteralString("")
942 condition := meh.LiteralBool(true)
943 step := meh.GlobalCall(
944 // __result__.size() > 0 ? __result__ + delim + __iter__ : __iter__
945 operators.Conditional,
946 meh.GlobalCall(operators.Greater, meh.ReceiverCall("size", accuIdent), meh.LiteralInt(0)),
947 meh.GlobalCall(operators.Add, meh.GlobalCall(operators.Add, accuIdent, delim), iterIdent),
948 iterIdent)
949 return meh.Fold(
950 "__iter__",
951 iterRange,
952 accuIdent.GetIdentExpr().GetName(),
953 accuInit,
954 condition,
955 step,
956 accuIdent), nil
957 })
958 env := testEnv(t, Macros(joinMacro))
959 ast, iss := env.Compile(`['hello', 'cel', 'friend'].join(',')`)
960 if iss.Err() != nil {
961 t.Fatal(iss.Err())
962 }
963 prg, err := env.Program(ast, EvalOptions(OptExhaustiveEval))
964 if err != nil {
965 t.Fatalf("program creation error: %s\n", err)
966 }
967 out, _, err := prg.Eval(NoVars())
968 if err != nil {
969 t.Fatal(err)
970 }
971 if out.Equal(types.String("hello,cel,friend")) != types.True {
972 t.Errorf("got %v, wanted 'hello,cel,friend'", out)
973 }
974}
975
976func TestMacroInterop(t *testing.T) {
977 existsOneMacro := NewReceiverMacro("exists_one", 2,

Callers

nothing calls this directly

Calls 15

StringTypeAlias · 0.92
EvalOptionsFunction · 0.85
NoVarsFunction · 0.85
ErrMethod · 0.80
ProgramMethod · 0.80
NewReceiverMacroFunction · 0.70
testEnvFunction · 0.70
MacrosFunction · 0.70
IdentMethod · 0.65
AccuIdentMethod · 0.65
LiteralStringMethod · 0.65
LiteralBoolMethod · 0.65

Tested by

no test coverage detected