From 603bd57b45008810b80ab824e864e8718397b690 Mon Sep 17 00:00:00 2001 From: Julian Kornberger Date: Mon, 21 Mar 2016 10:12:45 +0100 Subject: [PATCH] Fix jsontime and extend tests --- jsontime/jsontime.go | 26 ++++++++++++++++++++------ jsontime/jsontime_test.go | 15 ++++++++++++--- 2 files changed, 32 insertions(+), 9 deletions(-) diff --git a/jsontime/jsontime.go b/jsontime/jsontime.go index 51aa8a3..e8b6ea6 100644 --- a/jsontime/jsontime.go +++ b/jsontime/jsontime.go @@ -1,25 +1,39 @@ package jsontime import ( + "errors" "time" ) const TimeFormat = "2006-01-02T15:04:05" -type Time time.Time +type Time struct { + time time.Time +} func Now() Time { - return Time(time.Now()) + return Time{time.Now()} } func (t Time) MarshalJSON() ([]byte, error) { - stamp := `"` + time.Time(t).Format(TimeFormat) + `"` + stamp := `"` + t.time.Format(TimeFormat) + `"` return []byte(stamp), nil } -func (t Time) UnmarshalJSON(data []byte) (err error) { - if nativeTime, err := time.Parse(TimeFormat, string(data)); err == nil { - t = Time(nativeTime) +func (t *Time) UnmarshalJSON(data []byte) (err error) { + if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' { + return errors.New("invalid jsontime") + } + if nativeTime, err := time.Parse(TimeFormat, string(data[1:len(data)-1])); err == nil { + t.time = nativeTime } return } + +func (t Time) Unix() int64 { + return t.time.Unix() +} + +func (t Time) IsZero() bool { + return t.time.IsZero() +} diff --git a/jsontime/jsontime_test.go b/jsontime/jsontime_test.go index 040089d..c3bcb30 100644 --- a/jsontime/jsontime_test.go +++ b/jsontime/jsontime_test.go @@ -1,20 +1,28 @@ package jsontime import ( - "encoding/json" "testing" "time" "github.com/stretchr/testify/assert" ) +func TestNow(t *testing.T) { + assert := assert.New(t) + + t1 := time.Now() + t2 := Now() + + assert.InDelta(t1.Unix(), t2.Unix(), 1) +} + func TestMarshalTime(t *testing.T) { assert := assert.New(t) nativeTime, err := time.Parse(time.RFC3339, "2012-11-01T22:08:41+00:00") assert.Nil(err) - json, err := Time(nativeTime).MarshalJSON() + json, err := Time{nativeTime}.MarshalJSON() assert.Nil(err) assert.Equal(`"2012-11-01T22:08:41"`, string(json)) @@ -24,6 +32,7 @@ func TestUnmarshalTime(t *testing.T) { assert := assert.New(t) jsonTime := Time{} - err := json.Unmarshal([]byte(`"2012-11-01T22:08:41"`), &jsonTime) + err := jsonTime.UnmarshalJSON([]byte(`"2012-11-01T22:08:41"`)) assert.Nil(err) + assert.False(jsonTime.IsZero()) }