(t *testing.T)
| 7 | ) |
| 8 | |
| 9 | func TestBackoff(t *testing.T) { |
| 10 | stats := Statistics{ |
| 11 | FailuresUntilBlacklist: 7, |
| 12 | } |
| 13 | server := ServerStatistics{ |
| 14 | statistics: &stats, |
| 15 | serverName: "test.com", |
| 16 | } |
| 17 | |
| 18 | // Start by checking that counting successes works. |
| 19 | server.Success() |
| 20 | if successes := server.SuccessCount(); successes != 1 { |
| 21 | t.Fatalf("Expected success count 1, got %d", successes) |
| 22 | } |
| 23 | |
| 24 | // Register a failure. |
| 25 | server.Failure() |
| 26 | |
| 27 | t.Logf("Backoff counter: %d", server.backoffCount.Load()) |
| 28 | |
| 29 | // Now we're going to simulate backing off a few times to see |
| 30 | // what happens. |
| 31 | for i := uint32(1); i <= 10; i++ { |
| 32 | // Register another failure for good measure. This should have no |
| 33 | // side effects since a backoff is already in progress. If it does |
| 34 | // then we'll fail. |
| 35 | until, blacklisted := server.Failure() |
| 36 | |
| 37 | // Get the duration. |
| 38 | _, blacklist := server.BackoffInfo() |
| 39 | duration := time.Until(until).Round(time.Second) |
| 40 | |
| 41 | // Unset the backoff, or otherwise our next call will think that |
| 42 | // there's a backoff in progress and return the same result. |
| 43 | server.cancel() |
| 44 | server.backoffStarted.Store(false) |
| 45 | |
| 46 | // Check if we should be blacklisted by now. |
| 47 | if i >= stats.FailuresUntilBlacklist { |
| 48 | if !blacklist { |
| 49 | t.Fatalf("Backoff %d should have resulted in blacklist but didn't", i) |
| 50 | } else if blacklist != blacklisted { |
| 51 | t.Fatalf("BackoffInfo and Failure returned different blacklist values") |
| 52 | } else { |
| 53 | t.Logf("Backoff %d is blacklisted as expected", i) |
| 54 | continue |
| 55 | } |
| 56 | } |
| 57 | |
| 58 | // Check if the duration is what we expect. |
| 59 | t.Logf("Backoff %d is for %s", i, duration) |
| 60 | if wanted := time.Second * time.Duration(math.Exp2(float64(i))); !blacklist && duration != wanted { |
| 61 | t.Fatalf("Backoff %d should have been %s but was %s", i, wanted, duration) |
| 62 | } |
| 63 | } |
| 64 | } |
nothing calls this directly
no test coverage detected