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

Function TestCustomInterpreterDecorator

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

Source from the content-addressed store, hash-verified

1805}
1806
1807func TestCustomInterpreterDecorator(t *testing.T) {
1808 var lastInstruction interpreter.Interpretable
1809 optimizeArith := func(i interpreter.Interpretable) (interpreter.Interpretable, error) {
1810 lastInstruction = i
1811 // Only optimize the instruction if it is a call.
1812 call, ok := i.(interpreter.InterpretableCall)
1813 if !ok {
1814 return i, nil
1815 }
1816 // Only optimize the math functions when they have constant arguments.
1817 switch call.Function() {
1818 case operators.Add,
1819 operators.Subtract,
1820 operators.Multiply,
1821 operators.Divide:
1822 // These are all binary operators so they should have to arguments
1823 args := call.Args()
1824 _, lhsIsConst := args[0].(interpreter.InterpretableConst)
1825 _, rhsIsConst := args[1].(interpreter.InterpretableConst)
1826 // When the values are constant then the call can be evaluated with
1827 // an empty activation and the value returns as a constant.
1828 if !lhsIsConst || !rhsIsConst {
1829 return i, nil
1830 }
1831 val := call.Eval(interpreter.EmptyActivation())
1832 if types.IsError(val) {
1833 return nil, val.(*types.Err)
1834 }
1835 return interpreter.NewConstValue(call.ID(), val), nil
1836 default:
1837 return i, nil
1838 }
1839 }
1840
1841 env := testEnv(t, Variable("foo", IntType))
1842 ast, iss := env.Compile(`foo == -1 + 2 * 3 / 3`)
1843 if iss.Err() != nil {
1844 t.Fatalf("env.Compile() failed: %v", iss.Err())
1845 }
1846 _, err := env.Program(ast,
1847 EvalOptions(OptPartialEval),
1848 CustomDecorator(optimizeArith))
1849 if err != nil {
1850 t.Fatalf("env.Program() failed: %v", err)
1851 }
1852 call, ok := lastInstruction.(interpreter.InterpretableCall)
1853 if !ok {
1854 t.Errorf("got %v, expected call", lastInstruction)
1855 }
1856 args := call.Args()
1857 lhs := args[0]
1858 lastAttr, ok := lhs.(interpreter.InterpretableAttribute)
1859 if !ok {
1860 t.Errorf("got %v, wanted attribute", lhs)
1861 }
1862 absAttr := lastAttr.Attr().(interpreter.NamespacedAttribute)
1863 varNames := absAttr.CandidateVariableNames()
1864 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