4
. "launchpad.net/gocheck"
5
"launchpad.net/juju-core/utils"
9
func doSomething() (int, error) { return 0, nil }
11
func shouldRetry(error) bool { return false }
13
func doSomethingWith(int) {}
15
func ExampleAttempt_HasNext() {
16
// This example shows how Attempt.HasNext can be used to help
17
// structure an attempt loop. If the godoc example code allowed
18
// us to make the example return an error, we would uncomment
19
// the commented return statements.
20
attempts := utils.AttemptStrategy{
21
Total: 1 * time.Second,
22
Delay: 250 * time.Millisecond,
24
for attempt := attempts.Start(); attempt.Next(); {
25
x, err := doSomething()
26
if shouldRetry(err) && attempt.HasNext() {
39
func (utilsSuite) TestAttemptTiming(c *C) {
40
testAttempt := utils.AttemptStrategy{
44
want := []time.Duration{0, 0.1e9, 0.2e9, 0.2e9}
45
got := make([]time.Duration, 0, len(want)) // avoid allocation when testing timing
47
for a := testAttempt.Start(); a.Next(); {
48
got = append(got, time.Now().Sub(t0))
50
got = append(got, time.Now().Sub(t0))
51
c.Assert(got, HasLen, len(want))
53
for i, got := range want {
54
lo := want[i] - margin
55
hi := want[i] + margin
56
if got < lo || got > hi {
57
c.Errorf("attempt %d want %g got %g", i, want[i].Seconds(), got.Seconds())
62
func (utilsSuite) TestAttemptNextHasNext(c *C) {
63
a := utils.AttemptStrategy{}.Start()
64
c.Assert(a.Next(), Equals, true)
65
c.Assert(a.Next(), Equals, false)
67
a = utils.AttemptStrategy{}.Start()
68
c.Assert(a.Next(), Equals, true)
69
c.Assert(a.HasNext(), Equals, false)
70
c.Assert(a.Next(), Equals, false)
72
a = utils.AttemptStrategy{Total: 2e8}.Start()
73
c.Assert(a.Next(), Equals, true)
74
c.Assert(a.HasNext(), Equals, true)
76
c.Assert(a.HasNext(), Equals, true)
77
c.Assert(a.Next(), Equals, true)
78
c.Assert(a.Next(), Equals, false)
80
a = utils.AttemptStrategy{Total: 1e8, Min: 2}.Start()
82
c.Assert(a.Next(), Equals, true)
83
c.Assert(a.HasNext(), Equals, true)
84
c.Assert(a.Next(), Equals, true)
85
c.Assert(a.HasNext(), Equals, false)
86
c.Assert(a.Next(), Equals, false)