-
-
Notifications
You must be signed in to change notification settings - Fork 406
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add test to track how many times a patcher is run. Used to detect if …
…patching phases is erroneously applying the patcher multiple times.
- Loading branch information
Showing
1 changed file
with
61 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
package patch_test | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/expr-lang/expr/internal/testify/require" | ||
|
||
"github.com/expr-lang/expr" | ||
"github.com/expr-lang/expr/ast" | ||
"github.com/expr-lang/expr/test/mock" | ||
) | ||
|
||
// This patcher tracks how many nodes it patches which can | ||
// be used to verify if it was run too many times or not at all | ||
type countingPatcher struct { | ||
PatchCount int | ||
} | ||
|
||
func (c *countingPatcher) Visit(node *ast.Node) { | ||
switch (*node).(type) { | ||
case *ast.IntegerNode: | ||
c.PatchCount++ | ||
} | ||
} | ||
|
||
// Test over a simple expression | ||
func TestPatch_Count(t *testing.T) { | ||
patcher := countingPatcher{} | ||
|
||
_, err := expr.Compile( | ||
`5 + 5`, | ||
expr.Env(mock.Env{}), | ||
expr.Patch(&patcher), | ||
) | ||
require.NoError(t, err) | ||
|
||
require.Equal(t, 2, patcher.PatchCount, "Patcher run an unexpected number of times during compile") | ||
} | ||
|
||
// Test with operator overloading | ||
func TestPatchOperator_Count(t *testing.T) { | ||
patcher := countingPatcher{} | ||
|
||
_, err := expr.Compile( | ||
`5 + 5`, | ||
expr.Env(mock.Env{}), | ||
expr.Patch(&patcher), | ||
expr.Operator("+", "_intAdd"), | ||
expr.Function( | ||
"_intAdd", | ||
func(params ...any) (any, error) { | ||
return params[0].(int) + params[1].(int), nil | ||
}, | ||
new(func(int, int) int), | ||
), | ||
) | ||
|
||
require.NoError(t, err) | ||
|
||
require.Equal(t, 2, patcher.PatchCount, "Patcher run an unexpected number of times during compile") | ||
} |