forked from sosodev/duration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
duration_test.go
141 lines (135 loc) · 2.49 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package duration
import (
"encoding/json"
"reflect"
"testing"
"time"
)
func TestParse(t *testing.T) {
type args struct {
d string
}
tests := []struct {
name string
args args
want *Duration
wantErr bool
}{
{
name: "period-only",
args: args{d: "P4Y"},
want: &Duration{
Years: 4,
},
wantErr: false,
},
{
name: "time-only-decimal",
args: args{d: "T2.5S"},
want: &Duration{
Seconds: 2.5,
},
wantErr: false,
},
{
name: "full",
args: args{d: "P3Y6M4DT12H30M5.5S"},
want: &Duration{
Years: 3,
Months: 6,
Days: 4,
Hours: 12,
Minutes: 30,
Seconds: 5.5,
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Parse(tt.args.d)
if (err != nil) != tt.wantErr {
t.Errorf("Parse() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Parse() got = %v, want %v", got, tt.want)
}
})
}
}
func TestDuration_ToTimeDuration(t *testing.T) {
type fields struct {
Years float64
Months float64
Weeks float64
Days float64
Hours float64
Minutes float64
Seconds float64
}
tests := []struct {
name string
fields fields
want time.Duration
}{
{
name: "seconds",
fields: fields{
Seconds: 33.3,
},
want: time.Second*33 + time.Millisecond*300,
},
{
name: "hours, minutes, and seconds",
fields: fields{
Hours: 2,
Minutes: 33,
Seconds: 17,
},
want: time.Hour*2 + time.Minute*33 + time.Second*17,
},
{
name: "days",
fields: fields{
Days: 2,
},
want: time.Hour * 24 * 2,
},
{
name: "weeks",
fields: fields{
Weeks: 1,
},
want: time.Hour * 24 * 7,
},
{
name: "fractional weeks",
fields: fields{
Weeks: 12.5,
},
want: time.Hour*24*7*12 + time.Hour*84,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
duration := &Duration{
Years: tt.fields.Years,
Months: tt.fields.Months,
Weeks: tt.fields.Weeks,
Days: tt.fields.Days,
Hours: tt.fields.Hours,
Minutes: tt.fields.Minutes,
Seconds: tt.fields.Seconds,
}
if got := duration.ToTimeDuration(); got != tt.want {
t.Errorf("ToTimeDuration() = %v, want %v", got, tt.want)
}
})
}
}
func TestUnmarshallJSON(t *testing.T) {
if err := json.Unmarshal([]byte(`"PT13.85S"`), &Duration{}); err != nil {
t.Errorf("Error unmarshalling duration from JSON: %v", err)
}
}