From 0d416ccad0f92d4b1e22696fd5e04a64f7712bc9 Mon Sep 17 00:00:00 2001 From: Ryan Bullock Date: Tue, 18 Jun 2024 12:44:31 -0700 Subject: [PATCH] Add test to track how many times a patcher is run. Used to detect if patching phases is erroneously applying the patcher multiple times. --- test/patch/patch_count_test.go | 61 ++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 test/patch/patch_count_test.go diff --git a/test/patch/patch_count_test.go b/test/patch/patch_count_test.go new file mode 100644 index 00000000..e877de4a --- /dev/null +++ b/test/patch/patch_count_test.go @@ -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") +}