This repository has been archived by the owner on Dec 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
time_test.go_
94 lines (82 loc) · 2.35 KB
/
time_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
82
83
84
85
86
87
88
89
90
91
92
93
94
package amino
import (
"fmt"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
type Input struct {
Date time.Time `json:"date"`
}
func TestJSONTimeParse(t *testing.T) {
cases := []struct {
input string
expected time.Time
encoded string
}{
{
"2017-03-31T16:45:15Z",
time.Date(2017, 3, 31, 16, 45, 15, 0, time.UTC),
"2017-03-31T16:45:15.000Z",
},
{
"2017-03-31T16:45:15.972Z",
time.Date(2017, 3, 31, 16, 45, 15, 972000000, time.UTC),
"2017-03-31T16:45:15.972Z",
},
{
"2017-03-31T16:45:15.972167Z",
time.Date(2017, 3, 31, 16, 45, 15, 972167000, time.UTC),
"2017-03-31T16:45:15.972Z",
},
}
for _, tc := range cases {
var err error
var parsed Input
data := []byte(fmt.Sprintf(`{"date":"%s"}`, tc.input))
ReadJSONPtr(&parsed, data, &err)
if assert.Nil(t, err, "%s: %+v", tc.input, err) {
assert.Equal(t, tc.expected, parsed.Date)
out := JSONBytes(parsed)
assert.Equal(t, fmt.Sprintf(`{"date":"%s"}`, tc.encoded), string(out))
}
}
}
func TestTime(t *testing.T) {
// panic trying to encode times before 1970
panicCases := []time.Time{
time.Time{},
time.Unix(-10, 0),
time.Unix(0, -10),
}
for _, c := range panicCases {
assert.Panics(t, func() { amino.MarshalBinary(c) }, "expected MarshalBinary to panic on times before 1970")
}
// ensure we can encode/decode a recent time
now := time.Now()
buf, err := amino.MarshalBinary(now)
var thisTime time.Time
err = amino.UnmarshalBinary(buf, thisTime)
if !thisTime.Truncate(time.Millisecond).Equal(now.Truncate(time.Millisecond)) {
t.Fatalf("times dont match. got %v, expected %v", thisTime, now)
}
// error trying to decode bad times
errorCases := []struct {
thisTime time.Time
err error
}{
{time.Time{}, ErrBinaryReadInvalidTimeNegative},
{time.Unix(-10, 0), ErrBinaryReadInvalidTimeNegative},
{time.Unix(0, -10), ErrBinaryReadInvalidTimeNegative},
{time.Unix(0, 10), ErrBinaryReadInvalidTimeSubMillisecond},
{time.Unix(1, 10), ErrBinaryReadInvalidTimeSubMillisecond},
}
for _, c := range errorCases {
timeNano := c.thisTime.UnixNano()
buf, err := amino.EncodeInt64(timeNano)
var thisTime time.Time
err = amino.UnmarshalBinary(buf, thisTime)
assert.Equal(t, err, c.err, "expected UnmarshalBinary to throw an error")
assert.Equal(t, thisTime, time.Time{}, "expected UnmarshalBinary to return default time")
}
}