From 3d7c589f051f30d75fcb3d46e99b3c9a353f7c67 Mon Sep 17 00:00:00 2001 From: Maciej Szulik Date: Thu, 16 Aug 2018 11:26:16 +0200 Subject: [PATCH] Return error on input in GetValueFromIntOrPercent --- .../src/k8s.io/apimachinery/pkg/util/intstr/intstr.go | 11 +++++++++++ .../apimachinery/pkg/util/intstr/intstr_test.go | 7 +++++++ 2 files changed, 18 insertions(+) diff --git a/staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go b/staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go index 231498ca032..642b83cec21 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr.go @@ -18,6 +18,7 @@ package intstr import ( "encoding/json" + "errors" "fmt" "math" "runtime/debug" @@ -142,7 +143,17 @@ func (intstr *IntOrString) Fuzz(c fuzz.Continue) { } } +func ValueOrDefault(intOrPercent *IntOrString, defaultValue IntOrString) *IntOrString { + if intOrPercent == nil { + return &defaultValue + } + return intOrPercent +} + func GetValueFromIntOrPercent(intOrPercent *IntOrString, total int, roundUp bool) (int, error) { + if intOrPercent == nil { + return 0, errors.New("nil value for IntOrString") + } value, isPercent, err := getIntOrPercentValue(intOrPercent) if err != nil { return 0, fmt.Errorf("invalid value for IntOrString: %v", err) diff --git a/staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr_test.go b/staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr_test.go index 4faba46f8d0..690fe2d5331 100644 --- a/staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/util/intstr/intstr_test.go @@ -174,3 +174,10 @@ func TestGetValueFromIntOrPercent(t *testing.T) { } } } + +func TestGetValueFromIntOrPercentNil(t *testing.T) { + _, err := GetValueFromIntOrPercent(nil, 0, false) + if err == nil { + t.Errorf("expected error got none") + } +}