LEFT | RIGHT |
1 package utils_test | 1 package utils_test |
2 | 2 |
3 import ( | 3 import ( |
4 . "launchpad.net/gocheck" | 4 . "launchpad.net/gocheck" |
5 "launchpad.net/juju-core/utils" | 5 "launchpad.net/juju-core/utils" |
6 "time" | 6 "time" |
7 ) | 7 ) |
| 8 |
| 9 func doSomething() (int, error) { return 0, nil } |
| 10 |
| 11 func shouldRetry(error) bool { return false } |
| 12 |
| 13 func doSomethingWith(int) {} |
| 14 |
| 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, |
| 23 } |
| 24 for attempt := attempts.Start(); attempt.Next(); { |
| 25 x, err := doSomething() |
| 26 if shouldRetry(err) && attempt.HasNext() { |
| 27 continue |
| 28 } |
| 29 if err != nil { |
| 30 // return err |
| 31 return |
| 32 } |
| 33 doSomethingWith(x) |
| 34 } |
| 35 // return ErrTimedOut |
| 36 return |
| 37 } |
8 | 38 |
9 func (utilsSuite) TestAttemptTiming(c *C) { | 39 func (utilsSuite) TestAttemptTiming(c *C) { |
10 testAttempt := utils.AttemptStrategy{ | 40 testAttempt := utils.AttemptStrategy{ |
11 Total: 0.25e9, | 41 Total: 0.25e9, |
12 Delay: 0.1e9, | 42 Delay: 0.1e9, |
13 } | 43 } |
14 want := []time.Duration{0, 0.1e9, 0.2e9, 0.2e9} | 44 want := []time.Duration{0, 0.1e9, 0.2e9, 0.2e9} |
15 got := make([]time.Duration, 0, len(want)) // avoid allocation when test
ing timing | 45 got := make([]time.Duration, 0, len(want)) // avoid allocation when test
ing timing |
16 t0 := time.Now() | 46 t0 := time.Now() |
17 for a := testAttempt.Start(); a.Next(); { | 47 for a := testAttempt.Start(); a.Next(); { |
(...skipping 30 matching lines...) Expand all Loading... |
48 c.Assert(a.Next(), Equals, false) | 78 c.Assert(a.Next(), Equals, false) |
49 | 79 |
50 a = utils.AttemptStrategy{Total: 1e8, Min: 2}.Start() | 80 a = utils.AttemptStrategy{Total: 1e8, Min: 2}.Start() |
51 time.Sleep(1e8) | 81 time.Sleep(1e8) |
52 c.Assert(a.Next(), Equals, true) | 82 c.Assert(a.Next(), Equals, true) |
53 c.Assert(a.HasNext(), Equals, true) | 83 c.Assert(a.HasNext(), Equals, true) |
54 c.Assert(a.Next(), Equals, true) | 84 c.Assert(a.Next(), Equals, true) |
55 c.Assert(a.HasNext(), Equals, false) | 85 c.Assert(a.HasNext(), Equals, false) |
56 c.Assert(a.Next(), Equals, false) | 86 c.Assert(a.Next(), Equals, false) |
57 } | 87 } |
LEFT | RIGHT |