1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package time
16
17 import (
18 "encoding/json"
19 "strconv"
20 "testing"
21 "time"
22 )
23
24 func TestTimestamp(t *testing.T) {
25
26 validTimes := []string{
27
28 "null",
29 `"2019-01-02T15:04:05Z"`,
30 `"2019-01-02T15:04:05-08:00"`,
31 `"2019-01-02T15:04:05.0-08:00"`,
32 `"2019-01-02T15:04:05.01-08:00"`,
33 `"2019-01-02T15:04:05.012345678-08:00"`,
34 `"2019-02-28T15:04:59Z"`,
35
36
37
38
39
40
41
42
43
44 `"2019-01-02T15:04:05.01234567890-08:00"`,
45 }
46
47 for _, tc := range validTimes {
48 t.Run(tc, func(t *testing.T) {
49
50 var tm time.Time
51
52 if err := json.Unmarshal([]byte(tc), &tm); err != nil {
53 t.Errorf("unmarshal JSON failed unexpectedly: %v", err)
54 }
55
56 if tc == "null" {
57 return
58 }
59 str, _ := strconv.Unquote(tc)
60
61 if b, err := Time(str); !b || err != nil {
62 t.Errorf("Time failed unexpectedly: %v", err)
63 }
64 if _, err := Parse(RFC3339Nano, str); err != nil {
65 t.Errorf("Parse failed unexpectedly")
66 }
67 })
68 }
69
70 invalidTimes := []string{
71 `"2019-01-02T15:04:05"`,
72 `"2019-01-02T15:04:61Z"`,
73 `"2019-01-02T15:60:00Z"`,
74 `"2019-01-02T24:00:00Z"`,
75 `"2019-01-32T23:00:00Z"`,
76 `"2019-01-00T23:00:00Z"`,
77 `"2019-00-15T23:00:00Z"`,
78 `"2019-13-15T23:00:00Z"`,
79 `"2019-01-02T15:04:05Z+08:00"`,
80 `"2019-01-02T15:04:05+08"`,
81 }
82
83 for _, tc := range invalidTimes {
84 t.Run(tc, func(t *testing.T) {
85
86 var tm time.Time
87
88 if err := json.Unmarshal([]byte(tc), &tm); err == nil {
89 t.Errorf("unmarshal JSON succeeded unexpectedly: %v", err)
90 }
91
92 str, _ := strconv.Unquote(tc)
93
94 if _, err := Time(str); err == nil {
95 t.Errorf("CUE eval succeeded unexpectedly")
96 }
97
98 if _, err := Parse(RFC3339Nano, str); err == nil {
99 t.Errorf("CUE eval succeeded unexpectedly")
100 }
101 })
102 }
103 }
104
105 func TestUnix(t *testing.T) {
106 valid := []struct {
107 sec int64
108 nano int64
109 want string
110 }{
111 {0, 0, "1970-01-01T00:00:00Z"},
112 {1500000000, 123456, "2017-07-14T02:40:00.000123456Z"},
113 }
114
115 for _, tc := range valid {
116 t.Run(tc.want, func(t *testing.T) {
117 got := Unix(tc.sec, tc.nano)
118 if got != tc.want {
119 t.Errorf("got %v; want %s", got, tc.want)
120 }
121 })
122 }
123 }
124
View as plain text