-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrate_test.go
77 lines (69 loc) · 1.77 KB
/
rate_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
package human
import (
"encoding/json"
"fmt"
"testing"
yaml "gopkg.in/yaml.v3"
)
func TestRateParse(t *testing.T) {
for _, test := range []struct {
in string
out Rate
}{
{in: "0", out: 0},
{in: "0/s", out: 0},
{in: "1234/s", out: 1234},
{in: "10.2K/s", out: 10200},
} {
t.Run(test.in, func(t *testing.T) {
r, err := ParseRate(test.in)
if err != nil {
t.Fatal(err)
}
if r != test.out {
t.Error("parsed rate mismatch:", r, "!=", test.out)
}
})
}
}
func TestRateFormat(t *testing.T) {
for _, test := range []struct {
in Rate
fmt string
out string
unit Duration
}{
{in: 0, fmt: "%v", out: "0/s", unit: Second},
{in: 1234, fmt: "%v", out: "1234/s", unit: Second},
{in: 10234, fmt: "%v", out: "10.2K/s", unit: Second},
{in: 0.1, fmt: "%v", out: "100/ms", unit: Millisecond},
{in: 604800, fmt: "%v", out: "1/w", unit: Week},
{in: 1512000, fmt: "%v", out: "2.5/w", unit: Week},
{in: 25, fmt: "%s", out: "25/s", unit: Second},
{in: 25, fmt: "%#v", out: "human.Rate(25)", unit: Second},
} {
t.Run(test.out, func(t *testing.T) {
if s := fmt.Sprintf(test.fmt, test.in.Formatter(test.unit)); s != test.out {
t.Error("formatted rate mismatch:", s, "!=", test.out)
}
})
}
}
func TestRateJSON(t *testing.T) {
testRateEncoding(t, Rate(1.234), json.Marshal, json.Unmarshal)
}
func TestRateYAML(t *testing.T) {
testRateEncoding(t, Rate(1.234), yaml.Marshal, yaml.Unmarshal)
}
func testRateEncoding(t *testing.T, x Rate, marshal func(any) ([]byte, error), unmarshal func([]byte, any) error) {
b, err := marshal(x)
if err != nil {
t.Fatal("marshal error:", err)
}
v := Rate(0)
if err := unmarshal(b, &v); err != nil {
t.Error("unmarshal error:", err)
} else if v != x {
t.Error("value mismatch:", v, "!=", x)
}
}