-
Notifications
You must be signed in to change notification settings - Fork 14
/
unix.time_test.go
98 lines (76 loc) · 1.87 KB
/
unix.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
95
96
97
98
package gohubspot
import (
"encoding/json"
"fmt"
"strings"
"testing"
"time"
)
var epochStr = "1479298304451"
func TestMillisecondsEpochToDateTime(t *testing.T) {
epoch := []byte(epochStr) // = 2016-11-16 14:11:44.451 +0200 EET
result := &UnixTime{}
if err := result.UnmarshalJSON(epoch); err != nil {
t.Error(err)
}
if err := checkTime(result); err != nil {
t.Error(err)
}
}
func TestCanMarshalUnixTime(t *testing.T) {
ti, err := time.Parse(time.RFC3339, "2016-11-16T14:11:44.451+02:00")
if err != nil {
t.Error(err)
}
unixTime := &UnixTime{Time: ti}
bytes, err := unixTime.MarshalJSON()
if err != nil {
t.Error(err)
}
unixTimeStr := strings.Replace(string(bytes[:]), "\"", "", -1)
if unixTimeStr != epochStr {
t.Errorf("MarshalTime expected %s, but %s", epochStr, unixTimeStr)
}
}
func TestCanUnmarshalUnixTimeJson(t *testing.T) {
model := struct {
Size int `json:"size"`
Time UnixTime `json:"created_at"`
}{}
jsonObj := `
{"size": 34, "created_at":%s}
`
data := fmt.Sprintf(jsonObj, epochStr)
if err := json.Unmarshal([]byte(data), &model); err != nil {
t.Error(err)
}
if err := checkTime(&model.Time); err != nil {
t.Error(err)
}
}
func TestUnmarshalUnitTime(t *testing.T) {
model := struct {
Size int `json:"size"`
Time UnixTime `json:"created_at"`
}{}
jsonObj := `
{"size": 34, "created_at":%s}
`
data := fmt.Sprintf(jsonObj, "1508833601689")
if err := json.Unmarshal([]byte(data), &model); err != nil {
t.Error(err)
}
t.Errorf("time is: %s", model.Time)
}
func checkTime(unixTime *UnixTime) error {
if unixTime.Year() != 2016 {
return fmt.Errorf("Year expected %d, but %d", 2016, unixTime.Year())
}
if unixTime.Month() != 11 {
fmt.Errorf("Month expected %d, but %d", 11, unixTime.Month())
}
if unixTime.Second() != 44 {
fmt.Errorf("Seconds expected %d, but %d", 44, unixTime.Second())
}
return nil
}