exponential-backoff_test.go (2243B)
1 // This file is part of taler-cashless2ecash. 2 // Copyright (C) 2024 Joel Häberli 3 // 4 // taler-cashless2ecash is free software: you can redistribute it and/or modify it 5 // under the terms of the GNU Affero General Public License as published 6 // by the Free Software Foundation, either version 3 of the License, 7 // or (at your option) any later version. 8 // 9 // taler-cashless2ecash is distributed in the hope that it will be useful, but 10 // WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 // Affero General Public License for more details. 13 // 14 // You should have received a copy of the GNU Affero General Public License 15 // along with this program. If not, see <http://www.gnu.org/licenses/>. 16 // 17 // SPDX-License-Identifier: AGPL3.0-or-later 18 19 package internal_utils 20 21 import ( 22 "fmt" 23 "testing" 24 "time" 25 ) 26 27 func TestShouldRetryYes(t *testing.T) { 28 29 lastExecution := time.Now().Add(-(time.Duration(10 * time.Second))) 30 retries := 4 31 limitMs := 1000 32 33 retry := ShouldStartRetry(lastExecution, retries, limitMs) 34 if !retry { 35 fmt.Println("expected retry = true but was false") 36 t.FailNow() 37 } 38 } 39 40 func TestShouldRetryNo(t *testing.T) { 41 42 lastExecution := time.Now().Add(-(time.Duration(10 * time.Second))) 43 retries := 1 44 limitMs := 1000 45 46 retry := ShouldStartRetry(lastExecution, retries, limitMs) 47 if retry { 48 fmt.Println("expected retry = false but was true") 49 t.FailNow() 50 } 51 } 52 53 func TestBackoff(t *testing.T) { 54 55 expectations := []int{1, 2, 4, 8, 16, 32, 64, 128, 256} 56 for i := range []int{0, 1, 2, 3, 4, 5, 6, 7, 8} { 57 backoff := exponentialBackoffMs(i) 58 if backoff != int64(expectations[i]) { 59 fmt.Printf("expected %d, but got %d", expectations[i], backoff) 60 t.FailNow() 61 } 62 } 63 } 64 65 func TestRandomization(t *testing.T) { 66 67 input := 100 68 lowerBoundary := 80 // -20% 69 upperBoundary := 120 // +20% 70 rounds := 1000 71 currentRound := 0 72 for currentRound < rounds { 73 randomized := randomizeBackoff(int64(input)) 74 if randomized < int64(lowerBoundary) || randomized > int64(upperBoundary) { 75 fmt.Printf("round %d failed. Expected value between %d and %d but got %d", currentRound, lowerBoundary, upperBoundary, randomized) 76 t.FailNow() 77 } 78 currentRound++ 79 } 80 }