Skip to content

Rule validator #41

Open
Open
@thomaspoignant

Description

@thomaspoignant

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
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions