/
date_test.go
81 lines (66 loc) · 1.85 KB
/
date_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright (c) 2018, Bruno M V Souza <github@b.bmvs.io>. All rights reserved.
// Use of this source code is governed by a BSD-2-Clause license that can be
// found in the LICENSE file.
package api_test
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"go.bmvs.io/ynab/api"
)
func TestDate_UnmarshalJSON(t *testing.T) {
t.Run("success", func(t *testing.T) {
wrapper := struct {
Name string
Date *api.Date
}{}
err := json.Unmarshal([]byte(`{"Name": "YNAB", "Date": "2009-01-29"}`), &wrapper)
assert.NoError(t, err)
assert.Equal(t, "2009-01-29 00:00:00 +0000 UTC", wrapper.Date.String())
})
t.Run("json string without Date field", func(t *testing.T) {
wrapper := struct {
Name string
Date *api.Date
}{}
err := json.Unmarshal([]byte(`{"Name": "YNAB"}`), &wrapper)
assert.NoError(t, err)
assert.Nil(t, wrapper.Date)
})
t.Run("json string with null Date field", func(t *testing.T) {
wrapper := struct {
Name string
Date *api.Date
}{}
err := json.Unmarshal([]byte(`{"Name": "YNAB", "Date": null}`), &wrapper)
assert.NoError(t, err)
assert.Nil(t, wrapper.Date)
})
}
func TestDate_MarshalJSON(t *testing.T) {
date, err := api.DateFromString("2020-01-20")
assert.NoError(t, err)
wrapper := struct {
Date api.Date
}{
date,
}
buf, err := json.Marshal(&wrapper)
assert.NoError(t, err)
assert.Equal(t, `{"Date":"2020-01-20"}`, string(buf))
}
func TestNewDateFromString(t *testing.T) {
table := []struct {
InputDate string
OutputDateToString string
OutputError bool
}{
{"2018-02-01", "2018-02-01 00:00:00 +0000 UTC", false},
{"2018-13-01", "0001-01-01 00:00:00 +0000 UTC", true},
}
for _, test := range table {
date, err := api.DateFromString(test.InputDate)
assert.Equal(t, test.OutputError, err != nil)
assert.Equal(t, test.OutputDateToString, date.String())
}
}