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

Function TestCustomInterpreterDecorator

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

Source from the content-addressed store, hash-verified

1643}
1644
1645func TestCustomInterpreterDecorator(t *testing.T) {
1646 var lastInstruction interpreter.Interpretable
1647 optimizeArith := func(i interpreter.Interpretable) (interpreter.Interpretable, error) {
1648 lastInstruction = i
1649 // Only optimize the instruction if it is a call.
1650 call, ok := i.(interpreter.InterpretableCall)
1651 if !ok {
1652 return i, nil
1653 }
1654 // Only optimize the math functions when they have constant arguments.
1655 switch call.Function() {
1656 case operators.Add,
1657 operators.Subtract,
1658 operators.Multiply,
1659 operators.Divide:
1660 // These are all binary operators so they should have to arguments
1661 args := call.Args()
1662 _, lhsIsConst := args[0].(interpreter.InterpretableConst)
1663 _, rhsIsConst := args[1].(interpreter.InterpretableConst)
1664 // When the values are constant then the call can be evaluated with
1665 // an empty activation and the value returns as a constant.
1666 if !lhsIsConst || !rhsIsConst {
1667 return i, nil
1668 }
1669 val := call.Eval(interpreter.EmptyActivation())
1670 if types.IsError(val) {
1671 return nil, val.(*types.Err)
1672 }
1673 return interpreter.NewConstValue(call.ID(), val), nil
1674 default:
1675 return i, nil
1676 }
1677 }
1678
1679 env := testEnv(t, Variable("foo", IntType))
1680 ast, iss := env.Compile(`foo == -1 + 2 * 3 / 3`)
1681 if iss.Err() != nil {
1682 t.Fatalf("env.Compile() failed: %v", iss.Err())
1683 }
1684 _, err := env.Program(ast,
1685 EvalOptions(OptPartialEval),
1686 CustomDecorator(optimizeArith))
1687 if err != nil {
1688 t.Fatalf("env.Program() failed: %v", err)
1689 }
1690 call, ok := lastInstruction.(interpreter.InterpretableCall)
1691 if !ok {
1692 t.Errorf("got %v, expected call", lastInstruction)
1693 }
1694 args := call.Args()
1695 lhs := args[0]
1696 lastAttr, ok := lhs.(interpreter.InterpretableAttribute)
1697 if !ok {
1698 t.Errorf("got %v, wanted attribute", lhs)
1699 }
1700 absAttr := lastAttr.Attr().(interpreter.NamespacedAttribute)
1701 varNames := absAttr.CandidateVariableNames()
1702 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