mirror of
https://github.com/kyverno/kyverno.git
synced 2025-03-30 19:35:06 +00:00
fix: jp divide quantities (#6229)
Signed-off-by: Charles-Edouard Brétéché <charles.edouard@nirmata.com>
This commit is contained in:
parent
04cd2a2cfb
commit
83c188dd5e
2 changed files with 29 additions and 7 deletions
|
@ -5,7 +5,6 @@ import (
|
|||
"fmt"
|
||||
"math"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"gopkg.in/inf.v0"
|
||||
|
@ -197,13 +196,12 @@ 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 {
|
||||
divisor := v.AsApproximateFloat64()
|
||||
if divisor == 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)
|
||||
dividend := op1.AsApproximateFloat64()
|
||||
return dividend / divisor, nil
|
||||
case Scalar:
|
||||
if v.float64 == 0 {
|
||||
return nil, fmt.Errorf(zeroDivisionError, divide)
|
||||
|
|
|
@ -844,6 +844,30 @@ func Test_Divide(t *testing.T) {
|
|||
retFloat bool
|
||||
}{
|
||||
// Quantity
|
||||
{
|
||||
name: "Quantity / Quantity -> Scalar",
|
||||
test: "divide('256M', '256M')",
|
||||
expectedResult: 1.0,
|
||||
retFloat: true,
|
||||
},
|
||||
{
|
||||
name: "Quantity / Quantity -> Scalar",
|
||||
test: "divide('512M', '256M')",
|
||||
expectedResult: 2.0,
|
||||
retFloat: true,
|
||||
},
|
||||
{
|
||||
name: "Quantity / Quantity -> Scalar",
|
||||
test: "divide('8', '3')",
|
||||
expectedResult: 8.0 / 3.0,
|
||||
retFloat: true,
|
||||
},
|
||||
{
|
||||
name: "Quantity / Quantity -> Scalar",
|
||||
test: "divide('128M', '256M')",
|
||||
expectedResult: 0.5,
|
||||
retFloat: true,
|
||||
},
|
||||
{
|
||||
name: "Quantity / Scalar -> Quantity",
|
||||
test: "divide('12Ki', `3`)",
|
||||
|
@ -858,7 +882,7 @@ func Test_Divide(t *testing.T) {
|
|||
{
|
||||
name: "Quantity / Quantity -> Scalar",
|
||||
test: "divide('12Ki', '200')",
|
||||
expectedResult: 61.0,
|
||||
expectedResult: 61.44,
|
||||
retFloat: true,
|
||||
},
|
||||
{
|
||||
|
|
Loading…
Add table
Reference in a new issue