|
| 1 | +package patch_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "testing" |
| 5 | + |
| 6 | + "github.com/expr-lang/expr/internal/testify/require" |
| 7 | + |
| 8 | + "github.com/expr-lang/expr" |
| 9 | + "github.com/expr-lang/expr/ast" |
| 10 | + "github.com/expr-lang/expr/test/mock" |
| 11 | +) |
| 12 | + |
| 13 | +// This patcher tracks how many nodes it patches which can |
| 14 | +// be used to verify if it was run too many times or not at all |
| 15 | +type countingPatcher struct { |
| 16 | + PatchCount int |
| 17 | +} |
| 18 | + |
| 19 | +func (c *countingPatcher) Visit(node *ast.Node) { |
| 20 | + switch (*node).(type) { |
| 21 | + case *ast.IntegerNode: |
| 22 | + c.PatchCount++ |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +// Test over a simple expression |
| 27 | +func TestPatch_Count(t *testing.T) { |
| 28 | + patcher := countingPatcher{} |
| 29 | + |
| 30 | + _, err := expr.Compile( |
| 31 | + `5 + 5`, |
| 32 | + expr.Env(mock.Env{}), |
| 33 | + expr.Patch(&patcher), |
| 34 | + ) |
| 35 | + require.NoError(t, err) |
| 36 | + |
| 37 | + require.Equal(t, 2, patcher.PatchCount, "Patcher run an unexpected number of times during compile") |
| 38 | +} |
| 39 | + |
| 40 | +// Test with operator overloading |
| 41 | +func TestPatchOperator_Count(t *testing.T) { |
| 42 | + patcher := countingPatcher{} |
| 43 | + |
| 44 | + _, err := expr.Compile( |
| 45 | + `5 + 5`, |
| 46 | + expr.Env(mock.Env{}), |
| 47 | + expr.Patch(&patcher), |
| 48 | + expr.Operator("+", "_intAdd"), |
| 49 | + expr.Function( |
| 50 | + "_intAdd", |
| 51 | + func(params ...any) (any, error) { |
| 52 | + return params[0].(int) + params[1].(int), nil |
| 53 | + }, |
| 54 | + new(func(int, int) int), |
| 55 | + ), |
| 56 | + ) |
| 57 | + |
| 58 | + require.NoError(t, err) |
| 59 | + |
| 60 | + require.Equal(t, 2, patcher.PatchCount, "Patcher run an unexpected number of times during compile") |
| 61 | +} |
0 commit comments