...
1
16
17 package timer
18
19 import (
20 "testing"
21 "time"
22
23 "github.com/onsi/gomega"
24 )
25
26 var currentTime time.Time
27
28 func init() {
29 setCurrentTimeSinceEpoch(0)
30 now = func() time.Time { return currentTime }
31 }
32
33 func setCurrentTimeSinceEpoch(duration time.Duration) {
34 currentTime = time.Unix(0, duration.Nanoseconds())
35 }
36
37 func testUsageWithDefer(timer *TestPhaseTimer) {
38 defer timer.StartPhase(33, "two").End()
39 setCurrentTimeSinceEpoch(6*time.Second + 500*time.Millisecond)
40 }
41
42 func TestTimer(t *testing.T) {
43 gomega.RegisterTestingT(t)
44
45 timer := NewTestPhaseTimer()
46 setCurrentTimeSinceEpoch(1 * time.Second)
47 phaseOne := timer.StartPhase(1, "one")
48 setCurrentTimeSinceEpoch(3 * time.Second)
49 testUsageWithDefer(timer)
50
51 gomega.Expect(timer.PrintJSON()).To(gomega.MatchJSON(`{
52 "version": "v1",
53 "dataItems": [
54 {
55 "data": {
56 "001-one": 5.5,
57 "033-two": 3.5
58 },
59 "unit": "s",
60 "labels": {
61 "test": "phases",
62 "ended": "false"
63 }
64 }
65 ]
66 }`))
67 gomega.Expect(timer.PrintHumanReadable()).To(gomega.Equal(`Phase 001-one: 5.5s so far
68 Phase 033-two: 3.5s
69 `))
70
71 setCurrentTimeSinceEpoch(7*time.Second + 500*time.Millisecond)
72 phaseOne.End()
73
74 gomega.Expect(timer.PrintJSON()).To(gomega.MatchJSON(`{
75 "version": "v1",
76 "dataItems": [
77 {
78 "data": {
79 "001-one": 6.5,
80 "033-two": 3.5
81 },
82 "unit": "s",
83 "labels": {
84 "test": "phases"
85 }
86 }
87 ]
88 }`))
89 gomega.Expect(timer.PrintHumanReadable()).To(gomega.Equal(`Phase 001-one: 6.5s
90 Phase 033-two: 3.5s
91 `))
92 }
93
View as plain text