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

Function TestCustomInterpreterDecorator

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

Source from the content-addressed store, hash-verified

1747}
1748
1749func TestCustomInterpreterDecorator(t *testing.T) {
1750 var lastInstruction interpreter.Interpretable
1751 optimizeArith := func(i interpreter.Interpretable) (interpreter.Interpretable, error) {
1752 lastInstruction = i
1753 // Only optimize the instruction if it is a call.
1754 call, ok := i.(interpreter.InterpretableCall)
1755 if !ok {
1756 return i, nil
1757 }
1758 // Only optimize the math functions when they have constant arguments.
1759 switch call.Function() {
1760 case operators.Add,
1761 operators.Subtract,
1762 operators.Multiply,
1763 operators.Divide:
1764 // These are all binary operators so they should have to arguments
1765 args := call.Args()
1766 _, lhsIsConst := args[0].(interpreter.InterpretableConst)
1767 _, rhsIsConst := args[1].(interpreter.InterpretableConst)
1768 // When the values are constant then the call can be evaluated with
1769 // an empty activation and the value returns as a constant.
1770 if !lhsIsConst || !rhsIsConst {
1771 return i, nil
1772 }
1773 val := call.Eval(interpreter.EmptyActivation())
1774 if types.IsError(val) {
1775 return nil, val.(*types.Err)
1776 }
1777 return interpreter.NewConstValue(call.ID(), val), nil
1778 default:
1779 return i, nil
1780 }
1781 }
1782
1783 env := testEnv(t, Variable("foo", IntType))
1784 ast, iss := env.Compile(`foo == -1 + 2 * 3 / 3`)
1785 if iss.Err() != nil {
1786 t.Fatalf("env.Compile() failed: %v", iss.Err())
1787 }
1788 _, err := env.Program(ast,
1789 EvalOptions(OptPartialEval),
1790 CustomDecorator(optimizeArith))
1791 if err != nil {
1792 t.Fatalf("env.Program() failed: %v", err)
1793 }
1794 call, ok := lastInstruction.(interpreter.InterpretableCall)
1795 if !ok {
1796 t.Errorf("got %v, expected call", lastInstruction)
1797 }
1798 args := call.Args()
1799 lhs := args[0]
1800 lastAttr, ok := lhs.(interpreter.InterpretableAttribute)
1801 if !ok {
1802 t.Errorf("got %v, wanted attribute", lhs)
1803 }
1804 absAttr := lastAttr.Attr().(interpreter.NamespacedAttribute)
1805 varNames := absAttr.CandidateVariableNames()
1806 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
CustomDecoratorFunction · 0.70
FunctionMethod · 0.65
ArgsMethod · 0.65
EvalMethod · 0.65

Tested by

no test coverage detected