1
// Copyright 2011, 2012, 2013 Canonical Ltd.
2
// Licensed under the LGPLv3, see LICENCE file for details.
11
"github.com/juju/utils"
14
func doSomething() (int, error) { return 0, nil }
16
func shouldRetry(error) bool { return false }
18
func doSomethingWith(int) {}
20
func ExampleAttempt_HasNext() {
21
// This example shows how Attempt.HasNext can be used to help
22
// structure an attempt loop. If the godoc example code allowed
23
// us to make the example return an error, we would uncomment
24
// the commented return statements.
25
attempts := utils.AttemptStrategy{
26
Total: 1 * time.Second,
27
Delay: 250 * time.Millisecond,
29
for attempt := attempts.Start(); attempt.Next(); {
30
x, err := doSomething()
31
if shouldRetry(err) && attempt.HasNext() {
44
func (*utilsSuite) TestAttemptTiming(c *gc.C) {
45
testAttempt := utils.AttemptStrategy{
49
want := []time.Duration{0, 0.1e9, 0.2e9, 0.2e9}
50
got := make([]time.Duration, 0, len(want)) // avoid allocation when testing timing
52
for a := testAttempt.Start(); a.Next(); {
53
got = append(got, time.Now().Sub(t0))
55
got = append(got, time.Now().Sub(t0))
56
c.Assert(got, gc.HasLen, len(want))
58
for i, got := range want {
59
lo := want[i] - margin
60
hi := want[i] + margin
61
if got < lo || got > hi {
62
c.Errorf("attempt %d want %g got %g", i, want[i].Seconds(), got.Seconds())
67
func (*utilsSuite) TestAttemptNextHasNext(c *gc.C) {
68
a := utils.AttemptStrategy{}.Start()
69
c.Assert(a.Next(), gc.Equals, true)
70
c.Assert(a.Next(), gc.Equals, false)
72
a = utils.AttemptStrategy{}.Start()
73
c.Assert(a.Next(), gc.Equals, true)
74
c.Assert(a.HasNext(), gc.Equals, false)
75
c.Assert(a.Next(), gc.Equals, false)
77
a = utils.AttemptStrategy{Total: 2e8}.Start()
78
c.Assert(a.Next(), gc.Equals, true)
79
c.Assert(a.HasNext(), gc.Equals, true)
81
c.Assert(a.HasNext(), gc.Equals, true)
82
c.Assert(a.Next(), gc.Equals, true)
83
c.Assert(a.Next(), gc.Equals, false)
85
a = utils.AttemptStrategy{Total: 1e8, Min: 2}.Start()
87
c.Assert(a.Next(), gc.Equals, true)
88
c.Assert(a.HasNext(), gc.Equals, true)
89
c.Assert(a.Next(), gc.Equals, true)
90
c.Assert(a.HasNext(), gc.Equals, false)
91
c.Assert(a.Next(), gc.Equals, false)