forked from mirror/backoff
add get currrent attempt method with test (closes #2)
This commit is contained in:
parent
8dc7c27404
commit
0496a6c14d
13
backoff.go
13
backoff.go
|
@ -16,7 +16,7 @@ import (
|
|||
// are set on the Backoff shared among threads.
|
||||
type Backoff struct {
|
||||
//Factor is the multiplying factor for each increment step
|
||||
attempts, Factor float64
|
||||
attempt, Factor float64
|
||||
//Jitter eases contention by randomizing backoff steps
|
||||
Jitter bool
|
||||
//Min and Max are the minimum and maximum values of the counter
|
||||
|
@ -26,8 +26,8 @@ type Backoff struct {
|
|||
//Returns the current value of the counter and then
|
||||
//multiplies it Factor
|
||||
func (b *Backoff) Duration() time.Duration {
|
||||
d := b.ForAttempt(b.attempts)
|
||||
b.attempts++
|
||||
d := b.ForAttempt(b.attempt)
|
||||
b.attempt++
|
||||
return d
|
||||
}
|
||||
|
||||
|
@ -65,5 +65,10 @@ func (b *Backoff) ForAttempt(attempt float64) time.Duration {
|
|||
|
||||
//Resets the current value of the counter back to Min
|
||||
func (b *Backoff) Reset() {
|
||||
b.attempts = 0
|
||||
b.attempt = 0
|
||||
}
|
||||
|
||||
//Get the current backoff attempt
|
||||
func (b *Backoff) Attempt() float64 {
|
||||
return b.attempt
|
||||
}
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
package backoff
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
@ -65,6 +66,25 @@ func Test3(t *testing.T) {
|
|||
equals(t, b.Duration(), 100*time.Nanosecond)
|
||||
}
|
||||
|
||||
func TestGetAttempt(t *testing.T) {
|
||||
b := &Backoff{
|
||||
Min: 100 * time.Millisecond,
|
||||
Max: 10 * time.Second,
|
||||
Factor: 2,
|
||||
}
|
||||
equals(t, b.Attempt(), float64(0))
|
||||
equals(t, b.Duration(), 100*time.Millisecond)
|
||||
equals(t, b.Attempt(), float64(1))
|
||||
equals(t, b.Duration(), 200*time.Millisecond)
|
||||
equals(t, b.Attempt(), float64(2))
|
||||
equals(t, b.Duration(), 400*time.Millisecond)
|
||||
equals(t, b.Attempt(), float64(3))
|
||||
b.Reset()
|
||||
equals(t, b.Attempt(), float64(0))
|
||||
equals(t, b.Duration(), 100*time.Millisecond)
|
||||
equals(t, b.Attempt(), float64(1))
|
||||
}
|
||||
|
||||
func TestJitter(t *testing.T) {
|
||||
b := &Backoff{
|
||||
Min: 100 * time.Millisecond,
|
||||
|
@ -89,8 +109,8 @@ func between(t *testing.T, actual, low, high time.Duration) {
|
|||
}
|
||||
}
|
||||
|
||||
func equals(t *testing.T, d1, d2 time.Duration) {
|
||||
if d1 != d2 {
|
||||
t.Fatalf("Got %s, Expecting %s", d1, d2)
|
||||
func equals(t *testing.T, v1, v2 interface{}) {
|
||||
if !reflect.DeepEqual(v1, v2) {
|
||||
t.Fatalf("Got %v, Expecting %v", v1, v2)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue