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

Function TestCustomMacro

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

Source from the content-addressed store, hash-verified

829}
830
831func TestCustomMacro(t *testing.T) {
832 joinMacro := NewReceiverMacro("join", 1,
833 func(meh MacroExprHelper, iterRange *exprpb.Expr, args []*exprpb.Expr) (*exprpb.Expr, *Error) {
834 delim := args[0]
835 iterIdent := meh.Ident("__iter__")
836 accuIdent := meh.AccuIdent()
837 accuInit := meh.LiteralString("")
838 condition := meh.LiteralBool(true)
839 step := meh.GlobalCall(
840 // __result__.size() > 0 ? __result__ + delim + __iter__ : __iter__
841 operators.Conditional,
842 meh.GlobalCall(operators.Greater, meh.ReceiverCall("size", accuIdent), meh.LiteralInt(0)),
843 meh.GlobalCall(operators.Add, meh.GlobalCall(operators.Add, accuIdent, delim), iterIdent),
844 iterIdent)
845 return meh.Fold(
846 "__iter__",
847 iterRange,
848 accuIdent.GetIdentExpr().GetName(),
849 accuInit,
850 condition,
851 step,
852 accuIdent), nil
853 })
854 env := testEnv(t, Macros(joinMacro))
855 ast, iss := env.Compile(`['hello', 'cel', 'friend'].join(',')`)
856 if iss.Err() != nil {
857 t.Fatal(iss.Err())
858 }
859 prg, err := env.Program(ast, EvalOptions(OptExhaustiveEval))
860 if err != nil {
861 t.Fatalf("program creation error: %s\n", err)
862 }
863 out, _, err := prg.Eval(NoVars())
864 if err != nil {
865 t.Fatal(err)
866 }
867 if out.Equal(types.String("hello,cel,friend")) != types.True {
868 t.Errorf("got %v, wanted 'hello,cel,friend'", out)
869 }
870}
871
872func TestMacroInterop(t *testing.T) {
873 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