diff --git a/timezone/timezone.go b/timezone/timezone.go index 51945d8..7626e25 100644 --- a/timezone/timezone.go +++ b/timezone/timezone.go @@ -15,8 +15,10 @@ func (name *Timezone) UnmarshalJSON(data []byte) error { return err } - if _, err := ByNameStrErr(str); err != nil { - return err + if len(str) != 0 { + if _, err := ByNameStrErr(str); err != nil { + return err + } } *name = Timezone(str) diff --git a/timezone/timezone_test.go b/timezone/timezone_test.go index f1a3f6b..4dc2896 100644 --- a/timezone/timezone_test.go +++ b/timezone/timezone_test.go @@ -1,6 +1,10 @@ package timezone -import "testing" +import ( + "encoding/json" + "fmt" + "testing" +) func TestTimezone_MappingIsCorrect(t *testing.T) { for key, timezone := range timezonesByName { @@ -33,7 +37,6 @@ func TestTimezone_Validate(t *testing.T) { } func TestTimezone_Lookup(t *testing.T) { - if _, ok := ByNameStr("a"); ok { t.FailNow() } @@ -50,3 +53,26 @@ func TestTimezone_Lookup(t *testing.T) { t.FailNow() } } + +var testCases = []struct { + value Timezone + expectingUnmarshalError bool +}{ + {value: "", expectingUnmarshalError: false}, + {value: "Europe/Minsk", expectingUnmarshalError: false}, + {value: "a", expectingUnmarshalError: true}, +} + +func Test_UnmarshalJSON(t *testing.T) { + for _, testCase := range testCases { + jsonStr := fmt.Sprintf(`{"timezone":"%s"}`, testCase.value) + var timezoneStruct struct { + Timezone Timezone `json:"timezone"` + } + + actualErr := json.Unmarshal([]byte(jsonStr), &timezoneStruct) + if (actualErr == nil) == testCase.expectingUnmarshalError { + t.Errorf(`JsonUnmarshal: '%s'. expecting error - '%v' but was opposite`, testCase.value, testCase.expectingUnmarshalError) + } + } +}