From 653ddbb01ef55d29ee4b752dfe323503c8878aa5 Mon Sep 17 00:00:00 2001 From: Clayton Coleman Date: Mon, 6 Jun 2016 17:14:35 -0400 Subject: [PATCH] Tolerate YAML and JSON numbers Both YAML and JSON can contain numbers --- pkg/api/resource/quantity.go | 5 +---- pkg/api/resource/quantity_test.go | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/pkg/api/resource/quantity.go b/pkg/api/resource/quantity.go index 3522b1e495b..70c68a52322 100644 --- a/pkg/api/resource/quantity.go +++ b/pkg/api/resource/quantity.go @@ -626,10 +626,7 @@ func (q *Quantity) UnmarshalJSON(value []byte) error { q.i = int64Amount{} return nil } - if l < 2 { - return ErrFormatWrong - } - if value[0] == '"' && value[l-1] == '"' { + if l >= 2 && value[0] == '"' && value[l-1] == '"' { value = value[1 : l-1] } diff --git a/pkg/api/resource/quantity_test.go b/pkg/api/resource/quantity_test.go index 038b23ca9a4..5f2e7be0aa8 100644 --- a/pkg/api/resource/quantity_test.go +++ b/pkg/api/resource/quantity_test.go @@ -826,11 +826,24 @@ func TestJSON(t *testing.T) { func TestJSONWhitespace(t *testing.T) { q := Quantity{} - for _, s := range []string{" 1", "1 "} { - if err := json.Unmarshal([]byte(`"`+s+`"`), &q); err != nil { - t.Errorf("%q: %v", s, err) + testCases := []struct { + in string + expect string + }{ + {`" 1"`, "1"}, + {`"1 "`, "1"}, + {`1`, "1"}, + {` 1`, "1"}, + {`1 `, "1"}, + {`10`, "10"}, + {`-1`, "-1"}, + {` -1`, "-1"}, + } + for _, test := range testCases { + if err := json.Unmarshal([]byte(test.in), &q); err != nil { + t.Errorf("%q: %v", test.in, err) } - if q.String() != "1" { + if q.String() != test.expect { t.Errorf("unexpected string: %q", q.String()) } }