diff --git a/pkg/engine/jmespath/arithmetic.go b/pkg/engine/jmespath/arithmetic.go index 4eacf58c6a..34b754b584 100644 --- a/pkg/engine/jmespath/arithmetic.go +++ b/pkg/engine/jmespath/arithmetic.go @@ -227,11 +227,17 @@ func (op1 Scalar) Multiply(op2 interface{}) (interface{}, error) { func (op1 Quantity) Divide(op2 interface{}) (interface{}, error) { switch v := op2.(type) { case Quantity: + if v.ToDec().AsApproximateFloat64() == 0 { + return nil, fmt.Errorf(zeroDivisionError, divide) + } var quo inf.Dec scale := inf.Scale(math.Max(float64(op1.AsDec().Scale()), float64(v.AsDec().Scale()))) quo.QuoRound(op1.AsDec(), v.AsDec(), scale, inf.RoundDown) return strconv.ParseFloat(quo.String(), 64) case Scalar: + if v.float64 == 0 { + return nil, fmt.Errorf(zeroDivisionError, divide) + } q, err := resource.ParseQuantity(fmt.Sprintf("%v", v.float64)) if err != nil { return nil, err @@ -283,6 +289,9 @@ func (op1 Scalar) Divide(op2 interface{}) (interface{}, error) { return op1.float64 / v.float64, nil case Quantity: + if v.ToDec().AsApproximateFloat64() == 0 { + return nil, fmt.Errorf(zeroDivisionError, divide) + } q, err := resource.ParseQuantity(fmt.Sprintf("%v", op1.float64)) if err != nil { return nil, err diff --git a/pkg/engine/jmespath/functions_test.go b/pkg/engine/jmespath/functions_test.go index 1684f3c14a..0f745290f3 100644 --- a/pkg/engine/jmespath/functions_test.go +++ b/pkg/engine/jmespath/functions_test.go @@ -804,6 +804,50 @@ func Test_Divide(t *testing.T) { test: "divide('12s', `0`)", err: true, }, + { + test: "divide('12s', '0s')", + err: true, + }, + { + test: "divide(`12`, '0s')", + err: true, + }, + { + test: "divide('12M', '0Mi')", + err: true, + }, + { + test: "divide('12K', `0`)", + err: true, + }, + { + test: "divide('12K', '0m')", + err: true, + }, + { + test: "divide('12Ki', '0G')", + err: true, + }, + { + test: "divide('12Mi', '0Gi')", + err: true, + }, + { + test: "divide('12Mi', `0`)", + err: true, + }, + { + test: "divide(`12`, '0Gi')", + err: true, + }, + { + test: "divide(`12`, '0K')", + err: true, + }, + { + test: "divide(`12`, `0`)", + err: true, + }, { test: "divide(`25`, `2`)", expectedResult: 12.5, @@ -890,6 +934,50 @@ func Test_Modulo(t *testing.T) { test: "modulo('12s', `0`)", err: true, }, + { + test: "modulo('12s', '0s')", + err: true, + }, + { + test: "modulo(`12`, '0s')", + err: true, + }, + { + test: "modulo('12M', '0Mi')", + err: true, + }, + { + test: "modulo('12K', `0`)", + err: true, + }, + { + test: "modulo('12K', '0m')", + err: true, + }, + { + test: "modulo('12Ki', '0G')", + err: true, + }, + { + test: "modulo('12Mi', '0Gi')", + err: true, + }, + { + test: "modulo('12Mi', `0`)", + err: true, + }, + { + test: "modulo(`12`, '0Gi')", + err: true, + }, + { + test: "modulo(`12`, '0K')", + err: true, + }, + { + test: "modulo(`12`, `0`)", + err: true, + }, { test: "modulo(`25`, `2`)", expectedResult: 1.0,