Serge Bazanski | 20312b4 | 2023-04-19 13:49:47 +0200 | [diff] [blame^] | 1 | package bmdb |
| 2 | |
| 3 | import ( |
| 4 | "testing" |
| 5 | "time" |
| 6 | |
| 7 | "github.com/google/go-cmp/cmp" |
| 8 | ) |
| 9 | |
| 10 | // TestBackoffMath exercises the rules of Backoff. |
| 11 | func TestBackoffMath(t *testing.T) { |
| 12 | for _, te := range []struct { |
| 13 | name string |
| 14 | b *Backoff |
| 15 | existing *existingBackoff |
| 16 | wantSecs []int64 |
| 17 | }{ |
| 18 | {"NoBackoffSet", nil, nil, []int64{1, 1, 1}}, |
| 19 | {"EmptyBackoff", &Backoff{}, nil, []int64{1, 1, 1}}, |
| 20 | {"SimpleBackoff", &Backoff{Initial: time.Minute}, nil, []int64{60, 60, 60}}, |
| 21 | {"ExponentialWithMax", |
| 22 | &Backoff{Initial: time.Minute, Exponent: 1.1, Maximum: time.Minute * 2}, |
| 23 | nil, |
| 24 | []int64{60, 66, 73, 81, 90, 99, 109, 120, 120}, |
| 25 | }, |
| 26 | |
| 27 | {"SimpleOverridePrevious", |
| 28 | &Backoff{Initial: time.Minute}, |
| 29 | &existingBackoff{lastInterval: time.Second * 2}, |
| 30 | []int64{60, 60, 60}, |
| 31 | }, |
| 32 | {"ExponentialOverridePrevious", |
| 33 | &Backoff{Initial: time.Minute, Exponent: 2.0, Maximum: time.Minute * 2}, |
| 34 | &existingBackoff{lastInterval: time.Second * 2}, |
| 35 | []int64{4, 8, 16, 32, 64, 120, 120}, |
| 36 | }, |
| 37 | |
| 38 | {"ContinueExisting", nil, &existingBackoff{lastInterval: time.Minute}, []int64{60, 60, 60}}, |
| 39 | {"ContinueExistingInvalid1", nil, &existingBackoff{lastInterval: 0}, []int64{1, 1, 1}}, |
| 40 | {"ContinueExistingInvalid2", nil, &existingBackoff{lastInterval: time.Millisecond}, []int64{1, 1, 1}}, |
| 41 | |
| 42 | {"InvalidBackoff1", &Backoff{Exponent: 0.2}, nil, []int64{1, 1, 1}}, |
| 43 | {"InvalidBackoff2", &Backoff{Maximum: time.Millisecond, Initial: time.Millisecond}, nil, []int64{1, 1, 1}}, |
| 44 | } { |
| 45 | t.Run(te.name, func(t *testing.T) { |
| 46 | existing := te.existing |
| 47 | |
| 48 | gotSecs := make([]int64, len(te.wantSecs)) |
| 49 | for j := 0; j < len(te.wantSecs); j++ { |
| 50 | gotSecs[j] = te.b.next(existing) |
| 51 | existing = &existingBackoff{ |
| 52 | lastInterval: time.Duration(gotSecs[j]) * time.Second, |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | if diff := cmp.Diff(te.wantSecs, gotSecs); diff != "" { |
| 57 | t.Errorf("Difference: %s", diff) |
| 58 | } |
| 59 | }) |
| 60 | } |
| 61 | } |