-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspeed_test.go
120 lines (97 loc) · 2.48 KB
/
speed_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
package units_test
/**
* Copyright (c) 2024, Starboard Maritime Intelligence
* All rights reserved. Use is subject to License terms.
* See LICENSE in the root directory of this source tree.
*/
import (
"fmt"
"math/rand"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/starboard-nz/units"
)
func TestSpeed(t *testing.T) {
t.Run("Knots", func(t *testing.T) {
d := units.Mps(16)
assert.InDelta(t, 31.101511879, float64(d.Knot()), δ)
})
t.Run("km/h", func(t *testing.T) {
d := units.Mps(2)
assert.InDelta(t, 7.2, float64(d.Kph()), δ)
})
t.Run("m/s", func(t *testing.T) {
d := units.Knot(16)
assert.InDelta(t, 8.23111111111, float64(d.Mps()), δ)
})
}
func TestParseSpeed(t *testing.T) {
var testData = map[string]units.Speed{
"-10.4kn": units.Knot(-10.4),
"32 m/s": units.Mps(32),
"120km/h": units.Kph(120),
"23.6 mph": units.Mph(23.6),
"10kn": units.Knot(10),
}
for str, exp := range testData {
s, err := units.ParseSpeed(str)
require.NoError(t, err, str)
assert.InDelta(t, float64(exp.Mps()), float64(s.Mps()), δ)
assert.InDelta(t, float64(exp.Kph()), float64(s.Kph()), δ)
assert.InDelta(t, float64(exp.Mph()), float64(s.Mph()), δ)
assert.InDelta(t, float64(exp.Knot()), float64(s.Knot()), δ)
tExp := fmt.Sprintf("%T", exp)
tUnit := fmt.Sprintf("%T", s)
assert.Equal(t, tExp, tUnit)
}
var errTests = []string{"hello 6' world", "0.1.2m/s", "--123kn", "42"}
for _, str := range errTests {
_, err := units.ParseSpeed(str)
assert.Error(t, err)
}
}
func randomSpeedConversion(d units.Speed) units.Speed {
u := rand.Intn(4)
switch u {
case 0:
return d.Mps()
case 1:
return d.Knot()
case 2:
return d.Kph()
case 3:
return d.Mph()
}
return d.Mps()
}
func randomSpeed() units.Speed {
val := rand.Float64()*200000 - 100000 // nolint:gosec
u := rand.Intn(4)
switch u {
case 0:
return units.Mps(val)
case 1:
return units.Knot(val)
case 2:
return units.Kph(val)
case 3:
return units.Mph(val)
}
return units.Mps(val)
}
func TestSpeedRandom(t *testing.T) {
const N = 10000
for i := 0; i < N; i++ {
s0 := randomSpeed()
s := s0
// do 5 random conversions
for j := 0; j < 5; j++ {
s = randomSpeedConversion(s)
}
assert.InDelta(t, float64(s0.Mps()), float64(s.Mps()), δ)
assert.InDelta(t, float64(s0.Kph()), float64(s.Kph()), δ)
assert.InDelta(t, float64(s0.Mph()), float64(s.Mph()), δ)
assert.InDelta(t, float64(s0.Knot()), float64(s.Knot()), δ)
}
}