Debian Codegraph @

util/attempt_test.go

raw symbols SCIP
1 package util
2
3 import (
4 "testing"
5 "time"
6 )
7
8 func TestAttemptTiming(t *testing.T) {
9 testAttempt := AttemptStrategy{
10 Total: 0.25e9,
11 Delay: 0.1e9,
12 }
13 want := []time.Duration{0, 0.1e9, 0.2e9, 0.2e9}
14 got := make([]time.Duration, 0, len(want)) // avoid allocation when testing timing
15 t0 := time.Now()
16 for a := testAttempt.Start(); a.Next(); {
17 got = append(got, time.Now().Sub(t0))
18 }
19 got = append(got, time.Now().Sub(t0))
20 if len(got) != len(want) {
21 t.Fatalf("Failed!")
22 }
23 const margin = 0.01e9
24 for i, got := range want {
25 lo := want[i] - margin
26 hi := want[i] + margin
27 if got < lo || got > hi {
28 t.Errorf("attempt %d want %g got %g", i, want[i].Seconds(), got.Seconds())
29 }
30 }
31 }
32
33 func TestAttemptNextHasNext(t *testing.T) {
34 a := AttemptStrategy{}.Start()
35 if !a.Next() {
36 t.Fatalf("Failed!")
37 }
38 if a.Next() {
39 t.Fatalf("Failed!")
40 }
41
42 a = AttemptStrategy{}.Start()
43 if !a.Next() {
44 t.Fatalf("Failed!")
45 }
46 if a.HasNext() {
47 t.Fatalf("Failed!")
48 }
49 if a.Next() {
50 t.Fatalf("Failed!")
51 }
52 a = AttemptStrategy{Total: 2e8}.Start()
53
54 if !a.Next() {
55 t.Fatalf("Failed!")
56 }
57 if !a.HasNext() {
58 t.Fatalf("Failed!")
59 }
60 time.Sleep(2e8)
61
62 if !a.HasNext() {
63 t.Fatalf("Failed!")
64 }
65 if !a.Next() {
66 t.Fatalf("Failed!")
67 }
68 if a.Next() {
69 t.Fatalf("Failed!")
70 }
71
72 a = AttemptStrategy{Total: 1e8, Min: 2}.Start()
73 time.Sleep(1e8)
74
75 if !a.Next() {
76 t.Fatalf("Failed!")
77 }
78 if !a.HasNext() {
79 t.Fatalf("Failed!")
80 }
81 if !a.Next() {
82 t.Fatalf("Failed!")
83 }
84 if a.HasNext() {
85 t.Fatalf("Failed!")
86 }
87 if a.Next() {
88 t.Fatalf("Failed!")
89 }
90 }