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

Function TestCustomInterpreterDecoratorV2

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

Source from the content-addressed store, hash-verified

1876}
1877
1878func TestCustomInterpreterDecoratorV2(t *testing.T) {
1879 var lastInstruction interpreter.InterpretableV2
1880 optimizeArith := func(i interpreter.InterpretableV2) (interpreter.InterpretableV2, error) {
1881 lastInstruction = i
1882 // Only optimize the instruction if it is a call.
1883 call, ok := i.(interpreter.InterpretableCall)
1884 if !ok {
1885 return i, nil
1886 }
1887 // Only optimize the math functions when they have constant arguments.
1888 switch call.Function() {
1889 case operators.Add,
1890 operators.Subtract,
1891 operators.Multiply,
1892 operators.Divide:
1893 // These are all binary operators so they should have two arguments
1894 args := call.Args()
1895 _, lhsIsConst := args[0].(interpreter.InterpretableConst)
1896 _, rhsIsConst := args[1].(interpreter.InterpretableConst)
1897 // When the values are constant then the call can be evaluated with
1898 // an empty activation and the value returns as a constant.
1899 if !lhsIsConst || !rhsIsConst {
1900 return i, nil
1901 }
1902 val := call.Eval(interpreter.EmptyActivation())
1903 if types.IsError(val) {
1904 return nil, val.(*types.Err)
1905 }
1906 return interpreter.NewConstValue(call.ID(), val), nil
1907 default:
1908 return i, nil
1909 }
1910 }
1911
1912 env := testEnv(t, Variable("foo", IntType))
1913 ast, iss := env.Compile(`foo == -1 + 2 * 3 / 3`)
1914 if iss.Err() != nil {
1915 t.Fatalf("env.Compile() failed: %v", iss.Err())
1916 }
1917 _, err := env.Program(ast,
1918 EvalOptions(OptPartialEval),
1919 CustomDecoratorV2(optimizeArith))
1920 if err != nil {
1921 t.Fatalf("env.Program() failed: %v", err)
1922 }
1923 call, ok := lastInstruction.(interpreter.InterpretableCall)
1924 if !ok {
1925 t.Errorf("got %v, expected call", lastInstruction)
1926 }
1927 args := call.Args()
1928 lhs := args[0]
1929 lastAttr, ok := lhs.(interpreter.InterpretableAttribute)
1930 if !ok {
1931 t.Errorf("got %v, wanted attribute", lhs)
1932 }
1933 absAttr := lastAttr.Attr().(interpreter.NamespacedAttribute)
1934 varNames := absAttr.CandidateVariableNames()
1935 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