Skip to content

Commit

Permalink
Add AND logical operator support (#1539)
Browse files Browse the repository at this point in the history
Signed-off-by: Max Goncharenko <kacejot@fex.net>
  • Loading branch information
kacejot committed Feb 6, 2021
1 parent b91022d commit 536f364
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
20 changes: 16 additions & 4 deletions pkg/engine/validate/pattern.go
Original file line number Diff line number Diff line change
Expand Up @@ -154,17 +154,29 @@ func validateValueWithNilPattern(log logr.Logger, value interface{}) bool {

// Handler for pattern values during validation process
func validateValueWithStringPatterns(log logr.Logger, value interface{}, pattern string) bool {
statements := strings.Split(pattern, "|")
for _, statement := range statements {
statement = strings.Trim(statement, " ")
if validateValueWithStringPattern(log, value, statement) {
conditions := strings.Split(pattern, "|")
for _, condition := range conditions {
condition = strings.Trim(condition, " ")
if checkForAndConditionsAndValidate(log, value, condition) {
return true
}
}

return false
}

func checkForAndConditionsAndValidate(log logr.Logger, value interface{}, pattern string) bool {
conditions := strings.Split(pattern, "&")
for _, condition := range conditions {
condition = strings.Trim(condition, " ")
if !validateValueWithStringPattern(log, value, condition) {
return false
}
}

return true
}

// Handler for single pattern value during validation process
// Detects if pattern has a number
func validateValueWithStringPattern(log logr.Logger, value interface{}, pattern string) bool {
Expand Down
16 changes: 16 additions & 0 deletions pkg/engine/validate/pattern_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,22 @@ func TestValidateValueWithPattern_StringsLogicalOr(t *testing.T) {
assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern))
}

func TestValidateValueWithPattern_StringsLogicalAnd(t *testing.T) {
pattern := ">1 & <20"
value := "10"
assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern))
}

func TestValidateValueWithPattern_StringsAllLogicalOperators(t *testing.T) {
pattern := ">1 & <20 | >31 & <33"
value := "10"
assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern))
value = "32"
assert.Assert(t, ValidateValueWithPattern(log.Log, value, pattern))
value = "21"
assert.Assert(t, !ValidateValueWithPattern(log.Log, value, pattern))
}

func TestValidateValueWithPattern_EqualTwoFloats(t *testing.T) {
assert.Assert(t, ValidateValueWithPattern(log.Log, 7.0, 7.000))
}
Expand Down

0 comments on commit 536f364

Please sign in to comment.