forked from ChannelMeter/iso8601duration
-
Notifications
You must be signed in to change notification settings - Fork 1
/
duration_test.go
106 lines (84 loc) · 2.26 KB
/
duration_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
106
package duration
import (
"encoding/json"
"github.com/stretchr/testify/assert"
"testing"
"time"
)
func TestParseString(t *testing.T) {
t.Parallel()
// test with bad format
_, err := ParseString("asdf")
assert.Equal(t, err, ErrBadFormat)
// test with good full string
dur, err := ParseString("P1Y2M3DT4H5M6S")
assert.Nil(t, err)
assert.Equal(t, 1, dur.Years())
assert.Equal(t, 30*2+3, dur.Days())
assert.Equal(t, 4, dur.Hours())
assert.Equal(t, 5, dur.Minutes())
assert.Equal(t, 6, dur.Seconds())
// test with good week string
dur, err = ParseString("P1W")
assert.Nil(t, err)
assert.Equal(t, 1, dur.Weeks())
}
func TestString(t *testing.T) {
t.Parallel()
// test empty
d := Duration{}
assert.Equal(t, d.String(), "P")
// test only larger-than-day
p, _ := time.ParseDuration("10272h")
d = Duration{p}
assert.Equal(t, d.String(), "P1Y63D")
// test only smaller-than-day
p, _ = time.ParseDuration("1h2m3s")
d = Duration{p}
assert.Equal(t, d.String(), "PT1H2M3S")
// test full format
p, _ = time.ParseDuration("10276h5m6s")
d = Duration{p}
assert.Equal(t, d.String(), "P1Y63DT4H5M6S")
// test week format
p, _ = time.ParseDuration("168h")
d = Duration{p}
assert.Equal(t, d.String(), "P1W")
}
func TestToDuration(t *testing.T) {
t.Parallel()
p, _ := time.ParseDuration("8760h")
d := Duration{p}
assert.Equal(t, d.ToDuration(), time.Hour*24*365)
p, _ = time.ParseDuration("720h")
d = Duration{p}
assert.Equal(t, d.ToDuration(), time.Hour*24*30)
p, _ = time.ParseDuration("168h")
d = Duration{p}
assert.Equal(t, d.ToDuration(), time.Hour*24*7)
p, _ = time.ParseDuration("24h")
d = Duration{p}
assert.Equal(t, d.ToDuration(), time.Hour*24)
p, _ = time.ParseDuration("1h")
d = Duration{p}
assert.Equal(t, d.ToDuration(), time.Hour)
p, _ = time.ParseDuration("1m")
d = Duration{p}
assert.Equal(t, d.ToDuration(), time.Minute)
p, _ = time.ParseDuration("1s")
d = Duration{p}
assert.Equal(t, d.ToDuration(), time.Second)
}
func TestJSON(t *testing.T) {
t.Parallel()
// test JSON Marshal
dur, _ := ParseString("P1Y2M3DT4H5M6S")
bytes, err := json.Marshal(dur)
assert.Nil(t, err)
assert.NotNil(t, bytes)
// test JSON Unmarshal
dur = nil
err = json.Unmarshal(bytes, &dur)
assert.Nil(t, err)
assert.Equal(t, "P1Y63DT4H5M6S", dur.String())
}