add get currrent attempt method with test (closes #2)

This commit is contained in:
Jaime Pillora 2016-04-14 15:52:04 +10:00
parent 8dc7c27404
commit 0496a6c14d
2 changed files with 32 additions and 7 deletions

View File

@ -16,7 +16,7 @@ import (
// are set on the Backoff shared among threads. // are set on the Backoff shared among threads.
type Backoff struct { type Backoff struct {
//Factor is the multiplying factor for each increment step //Factor is the multiplying factor for each increment step
attempts, Factor float64 attempt, Factor float64
//Jitter eases contention by randomizing backoff steps //Jitter eases contention by randomizing backoff steps
Jitter bool Jitter bool
//Min and Max are the minimum and maximum values of the counter //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 //Returns the current value of the counter and then
//multiplies it Factor //multiplies it Factor
func (b *Backoff) Duration() time.Duration { func (b *Backoff) Duration() time.Duration {
d := b.ForAttempt(b.attempts) d := b.ForAttempt(b.attempt)
b.attempts++ b.attempt++
return d return d
} }
@ -65,5 +65,10 @@ func (b *Backoff) ForAttempt(attempt float64) time.Duration {
//Resets the current value of the counter back to Min //Resets the current value of the counter back to Min
func (b *Backoff) Reset() { func (b *Backoff) Reset() {
b.attempts = 0 b.attempt = 0
}
//Get the current backoff attempt
func (b *Backoff) Attempt() float64 {
return b.attempt
} }

View File

@ -1,6 +1,7 @@
package backoff package backoff
import ( import (
"reflect"
"testing" "testing"
"time" "time"
) )
@ -65,6 +66,25 @@ func Test3(t *testing.T) {
equals(t, b.Duration(), 100*time.Nanosecond) 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) { func TestJitter(t *testing.T) {
b := &Backoff{ b := &Backoff{
Min: 100 * time.Millisecond, 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) { func equals(t *testing.T, v1, v2 interface{}) {
if d1 != d2 { if !reflect.DeepEqual(v1, v2) {
t.Fatalf("Got %s, Expecting %s", d1, d2) t.Fatalf("Got %v, Expecting %v", v1, v2)
} }
} }