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

Function TestCustomInterpreterDecoratorV2

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

Source from the content-addressed store, hash-verified

1714}
1715
1716func TestCustomInterpreterDecoratorV2(t *testing.T) {
1717 var lastInstruction interpreter.InterpretableV2
1718 optimizeArith := func(i interpreter.InterpretableV2) (interpreter.InterpretableV2, error) {
1719 lastInstruction = i
1720 // Only optimize the instruction if it is a call.
1721 call, ok := i.(interpreter.InterpretableCall)
1722 if !ok {
1723 return i, nil
1724 }
1725 // Only optimize the math functions when they have constant arguments.
1726 switch call.Function() {
1727 case operators.Add,
1728 operators.Subtract,
1729 operators.Multiply,
1730 operators.Divide:
1731 // These are all binary operators so they should have two arguments
1732 args := call.Args()
1733 _, lhsIsConst := args[0].(interpreter.InterpretableConst)
1734 _, rhsIsConst := args[1].(interpreter.InterpretableConst)
1735 // When the values are constant then the call can be evaluated with
1736 // an empty activation and the value returns as a constant.
1737 if !lhsIsConst || !rhsIsConst {
1738 return i, nil
1739 }
1740 val := call.Eval(interpreter.EmptyActivation())
1741 if types.IsError(val) {
1742 return nil, val.(*types.Err)
1743 }
1744 return interpreter.NewConstValue(call.ID(), val), nil
1745 default:
1746 return i, nil
1747 }
1748 }
1749
1750 env := testEnv(t, Variable("foo", IntType))
1751 ast, iss := env.Compile(`foo == -1 + 2 * 3 / 3`)
1752 if iss.Err() != nil {
1753 t.Fatalf("env.Compile() failed: %v", iss.Err())
1754 }
1755 _, err := env.Program(ast,
1756 EvalOptions(OptPartialEval),
1757 CustomDecoratorV2(optimizeArith))
1758 if err != nil {
1759 t.Fatalf("env.Program() failed: %v", err)
1760 }
1761 call, ok := lastInstruction.(interpreter.InterpretableCall)
1762 if !ok {
1763 t.Errorf("got %v, expected call", lastInstruction)
1764 }
1765 args := call.Args()
1766 lhs := args[0]
1767 lastAttr, ok := lhs.(interpreter.InterpretableAttribute)
1768 if !ok {
1769 t.Errorf("got %v, wanted attribute", lhs)
1770 }
1771 absAttr := lastAttr.Attr().(interpreter.NamespacedAttribute)
1772 varNames := absAttr.CandidateVariableNames()
1773 if len(varNames) != 1 || varNames[0] != "foo" {

Callers

nothing calls this directly

Calls 15

EmptyActivationFunction · 0.92
IsErrorFunction · 0.92
NewConstValueFunction · 0.92
EvalOptionsFunction · 0.85
ErrMethod · 0.80
ProgramMethod · 0.80
testEnvFunction · 0.70
VariableFunction · 0.70
CustomDecoratorV2Function · 0.70
FunctionMethod · 0.65
ArgsMethod · 0.65
EvalMethod · 0.65

Tested by

no test coverage detected