Skip to content

Commit 0d416cc

Browse files
committed
Add test to track how many times a patcher is run. Used to detect if patching phases is erroneously applying the patcher multiple times.
1 parent 3e8d788 commit 0d416cc

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

test/patch/patch_count_test.go

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
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

Comments
 (0)