From 28d9b3803ea8780370671d1cea9185f308eb2890 Mon Sep 17 00:00:00 2001 From: Mario Morgado Date: Mon, 11 Feb 2019 15:28:57 +0000 Subject: [PATCH] empty datetime shouldn't be converted to epoch time and it shouldn't be accepted as valid * changes error message * fixes scopelint issue Signed-off-by: Mario Morgado --- format.go | 7 ++++++- format_test.go | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/format.go b/format.go index 8afccbd..266cff5 100644 --- a/format.go +++ b/format.go @@ -16,6 +16,7 @@ package strfmt import ( "encoding" + "fmt" "reflect" "strings" "sync" @@ -108,7 +109,11 @@ func (f *defaultFormats) MapStructureHookFunc() mapstructure.DecodeHookFunc { } return Date(d), nil case "datetime": - return ParseDateTime(data.(string)) + input := data.(string) + if len(input) == 0 { + return nil, fmt.Errorf("empty string is an invalid datetime format") + } + return ParseDateTime(input) case "duration": dur, err := ParseDuration(data.(string)) if err != nil { diff --git a/format_test.go b/format_test.go index 096eaf8..5caf30f 100644 --- a/format_test.go +++ b/format_test.go @@ -221,3 +221,40 @@ func TestDecodeHook(t *testing.T) { assert.Nil(t, err) assert.Equal(t, exp, test) } + +func TestDecodeDateTimeHook(t *testing.T) { + testCases := []struct { + Name string + Input string + }{ + { + "empty datetime", + "", + }, + { + "invalid non empty datetime", + "2019-01-01", + }, + } + registry := NewFormats() + type layout struct { + DateTime *DateTime `json:"datetime,omitempty"` + } + for i := range testCases { + tc := testCases[i] + t.Run(tc.Name, func(t *testing.T) { + test := new(layout) + cfg := &mapstructure.DecoderConfig{ + DecodeHook: registry.MapStructureHookFunc(), + WeaklyTypedInput: false, + Result: test, + } + d, err := mapstructure.NewDecoder(cfg) + assert.Nil(t, err) + input := make(map[string]interface{}) + input["datetime"] = tc.Input + err = d.Decode(input) + assert.Error(t, err, "error expected got none") + }) + } +}