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

Function TestCustomMacro

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

Source from the content-addressed store, hash-verified

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