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

Function TestCustomMacro

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

Source from the content-addressed store, hash-verified

849}
850
851func TestCustomMacro(t *testing.T) {
852 joinMacro := NewReceiverMacro("join", 1,
853 func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
854 delim := args[0]
855 iterIdent := meh.Ident("__iter__")
856 accuIdent := meh.AccuIdent()
857 accuInit := meh.LiteralString("")
858 condition := meh.LiteralBool(true)
859 step := meh.GlobalCall(
860 // __result__.size() > 0 ? __result__ + delim + __iter__ : __iter__
861 operators.Conditional,
862 meh.GlobalCall(operators.Greater, meh.ReceiverCall("size", accuIdent), meh.LiteralInt(0)),
863 meh.GlobalCall(operators.Add, meh.GlobalCall(operators.Add, accuIdent, delim), iterIdent),
864 iterIdent)
865 return meh.Fold(
866 "__iter__",
867 iterRange,
868 accuIdent.GetIdentExpr().GetName(),
869 accuInit,
870 condition,
871 step,
872 accuIdent), nil
873 })
874 env := testEnv(t, Macros(joinMacro))
875 ast, iss := env.Compile(`['hello', 'cel', 'friend'].join(',')`)
876 if iss.Err() != nil {
877 t.Fatal(iss.Err())
878 }
879 prg, err := env.Program(ast, EvalOptions(OptExhaustiveEval))
880 if err != nil {
881 t.Fatalf("program creation error: %s\n", err)
882 }
883 out, _, err := prg.Eval(NoVars())
884 if err != nil {
885 t.Fatal(err)
886 }
887 if out.Equal(types.String("hello,cel,friend")) != types.True {
888 t.Errorf("got %v, wanted 'hello,cel,friend'", out)
889 }
890}
891
892func TestMacroInterop(t *testing.T) {
893 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