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

Function TestCustomInterpreterDecorator

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

Source from the content-addressed store, hash-verified

1833}
1834
1835func TestCustomInterpreterDecorator(t *testing.T) {
1836 var lastInstruction interpreter.Interpretable
1837 optimizeArith := func(i interpreter.Interpretable) (interpreter.Interpretable, error) {
1838 lastInstruction = i
1839 // Only optimize the instruction if it is a call.
1840 call, ok := i.(interpreter.InterpretableCall)
1841 if !ok {
1842 return i, nil
1843 }
1844 // Only optimize the math functions when they have constant arguments.
1845 switch call.Function() {
1846 case operators.Add,
1847 operators.Subtract,
1848 operators.Multiply,
1849 operators.Divide:
1850 // These are all binary operators so they should have to arguments
1851 args := call.Args()
1852 _, lhsIsConst := args[0].(interpreter.InterpretableConst)
1853 _, rhsIsConst := args[1].(interpreter.InterpretableConst)
1854 // When the values are constant then the call can be evaluated with
1855 // an empty activation and the value returns as a constant.
1856 if !lhsIsConst || !rhsIsConst {
1857 return i, nil
1858 }
1859 val := call.Eval(interpreter.EmptyActivation())
1860 if types.IsError(val) {
1861 return nil, val.(*types.Err)
1862 }
1863 return interpreter.NewConstValue(call.ID(), val), nil
1864 default:
1865 return i, nil
1866 }
1867 }
1868
1869 env := testEnv(t, Variable("foo", IntType))
1870 ast, iss := env.Compile(`foo == -1 + 2 * 3 / 3`)
1871 if iss.Err() != nil {
1872 t.Fatalf("env.Compile() failed: %v", iss.Err())
1873 }
1874 _, err := env.Program(ast,
1875 EvalOptions(OptPartialEval),
1876 CustomDecorator(optimizeArith))
1877 if err != nil {
1878 t.Fatalf("env.Program() failed: %v", err)
1879 }
1880 call, ok := lastInstruction.(interpreter.InterpretableCall)
1881 if !ok {
1882 t.Errorf("got %v, expected call", lastInstruction)
1883 }
1884 args := call.Args()
1885 lhs := args[0]
1886 lastAttr, ok := lhs.(interpreter.InterpretableAttribute)
1887 if !ok {
1888 t.Errorf("got %v, wanted attribute", lhs)
1889 }
1890 absAttr := lastAttr.Attr().(interpreter.NamespacedAttribute)
1891 varNames := absAttr.CandidateVariableNames()
1892 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