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