From 536f36472455d88cda3ae27f638b769ad3a911cd Mon Sep 17 00:00:00 2001 From: Max Goncharenko Date: Sat, 6 Feb 2021 03:52:31 +0200 Subject: [PATCH] Add AND logical operator support (#1539) Signed-off-by: Max Goncharenko --- pkg/engine/validate/pattern.go | 20 ++++++++++++++++---- pkg/engine/validate/pattern_test.go | 16 ++++++++++++++++ 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/pkg/engine/validate/pattern.go b/pkg/engine/validate/pattern.go index a08f7d4e26..46e9c1cf98 100644 --- a/pkg/engine/validate/pattern.go +++ b/pkg/engine/validate/pattern.go @@ -154,10 +154,10 @@ 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 } } @@ -165,6 +165,18 @@ func validateValueWithStringPatterns(log logr.Logger, value interface{}, pattern 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 { diff --git a/pkg/engine/validate/pattern_test.go b/pkg/engine/validate/pattern_test.go index 390c74d506..7b4214dd21 100644 --- a/pkg/engine/validate/pattern_test.go +++ b/pkg/engine/validate/pattern_test.go @@ -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)) }