Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

empty datetime shouldn't be converted to epoch time #47

Merged
merged 1 commit into from
Feb 11, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion format.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ package strfmt

import (
"encoding"
"fmt"
"reflect"
"strings"
"sync"
Expand Down Expand Up @@ -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 {
Expand Down
37 changes: 37 additions & 0 deletions format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
})
}
}