Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rule validator #41

Open
thomaspoignant opened this issue Aug 15, 2024 · 0 comments
Open

Rule validator #41

thomaspoignant opened this issue Aug 15, 2024 · 0 comments

Comments

@thomaspoignant
Copy link

thomaspoignant commented Aug 15, 2024

Hello,
Is it possible to validate a rule to check if it has the right format?

I came across in the test to this test

func TestInvalidRule(t *testing.T) {

But the eval function does not trigger errors for rules like:

# where there is a missing )
((env eq "pro") and (company eq "my-company")

# Invalid syntax with multiple eq
env eq "pro" eq "dev"

It may be because the syntax is accepted or the error is not detected.

Step to reproduce

You can find below the test file I am using to try to validate the rules.
As you can see we have 2 of the tests that are saying the rule is valid, when it is not expected, I am curious to have your input on that.

package main_test

import (
	"github.com/nikunjy/rules/parser"
	"github.com/stretchr/testify/assert"
	"testing"
)

func TestRuleValidator(t *testing.T) {
	tests := []struct {
		name  string
		rule  string
		error assert.ErrorAssertionFunc
	}{
		{
			name:  "Should not error with a valid rule",
			rule:  `env eq "pro"`,
			error: assert.NoError,
			// Result: the rule is valid as expected
		},
		{
			name:  "Should error if missing )",
			rule:  `((env eq "pro") and (company eq "my-company")`,
			error: assert.Error,
			// Result: does not error in this case, the rule is considered valid
		},
		{
			name:  "Should error if invalid placed operator",
			rule:  `env eq "pro" eq "dev"`,
			error: assert.Error,
			// Result: does not error in this case, the rule is considered valid
		},
		{
			name:  "Should error if no operator",
			rule:  `invalid`,
			error: assert.Error,
			// Result: the rule is invalid as expected
		},
	}

	for _, test := range tests {
		t.Run(test.name, func(t *testing.T) {
			test.error(t, eval(test.rule))
		})
	}
}

func eval(rule string) error {
	ev, err := parser.NewEvaluator(rule)
	if err != nil {
		return err
	}
	_, err = ev.Process(map[string]interface{}{})
	return err
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant