-
Notifications
You must be signed in to change notification settings - Fork 4
/
time_test.go
105 lines (81 loc) · 2.4 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
95
96
97
98
99
100
101
102
103
104
105
package null
import (
"database/sql"
"encoding/json"
"testing"
"time"
)
type testTime struct {
Value Time `json:"value"`
}
func TestNewTime(t *testing.T) {
value := NewTime(time.Now(), true)
if value.Time.Equal(time.Time{}) || !value.Valid {
t.Fatal("New Time must have value and be valid")
}
}
func TestMarshalTime(t *testing.T) {
now := time.Now()
nowStrBytes, _ := json.Marshal(now)
nowStr := string(nowStrBytes)
value := Time{sql.NullTime{Time: now, Valid: true}}
if data, err := json.Marshal(value); err != nil || string(data) != nowStr {
t.Fatalf("Time must be marshalled to value, but was %v %v", err, string(data))
}
value.Valid = false
if data, err := json.Marshal(value); err != nil || string(data) != "null" {
t.Fatalf("Time must be marshalled to null, but was %v %v", err, string(data))
}
}
func TestUnmarshalTime(t *testing.T) {
now := time.Now()
nowStrBytes, _ := json.Marshal(now)
nowStr := string(nowStrBytes)
str := `{"value": ` + nowStr + `}`
var value testTime
if err := json.Unmarshal([]byte(str), &value); err != nil {
t.Fatalf("Time must be unmarshalled to value, but was %v", err)
}
if !value.Value.Valid || !value.Value.Time.Equal(now) {
t.Fatalf("Unmarshalled null Time must be valid, but was %v", value.Value)
}
str = `{"value": null}`
if err := json.Unmarshal([]byte(str), &value); err != nil {
t.Fatalf("Time must be unmarshalled to null, but was %v", err)
}
if value.Value.Valid {
t.Fatal("Unmarshalled null Time must be invalid")
}
}
func TestScanTime(t *testing.T) {
now := time.Now()
str := "test"
var value Time
if err := value.Scan(&str); err == nil || err.Error() != "unexpected type" {
t.Fatalf("Time must return error, but was: %v", err)
}
if err := value.Scan(now); err != nil {
t.Fatalf("Time must be scanned, but was: %v", err)
}
if !value.Time.Equal(now) {
t.Fatalf("Scanned time must be equal to input, but was: %v == %v", value.Time, now)
}
}
func TestValueTime(t *testing.T) {
value := NewTime(time.Now(), true)
out, err := value.Value()
if err != nil || out == nil {
t.Fatalf("Time must return value, but was: %v", err)
}
}
func TestGettersSettersTime(t *testing.T) {
value := NewTime(time.Now(), true)
value.SetNil()
if !value.Time.Equal(time.Time{}) || value.Valid {
t.Fatal("Time must be nil")
}
value.SetValid(time.Now())
if value.Time.Equal(time.Time{}) || !value.Valid {
t.Fatal("Time must be valid")
}
}