go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/retry/exponential_test.go (about) 1 // Copyright 2015 The LUCI Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package retry 16 17 import ( 18 "context" 19 "testing" 20 "time" 21 22 . "github.com/smartystreets/goconvey/convey" 23 "go.chromium.org/luci/common/clock/testclock" 24 ) 25 26 func TestExponentialBackoff(t *testing.T) { 27 t.Parallel() 28 29 Convey(`An ExponentialBackoff Iterator, using an instrumented context`, t, func() { 30 ctx, _ := testclock.UseTime(context.Background(), time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)) 31 l := ExponentialBackoff{} 32 33 Convey(`When empty, will Stop immediately.`, func() { 34 So(l.Next(ctx, nil), ShouldEqual, Stop) 35 }) 36 37 Convey(`Will delay exponentially.`, func() { 38 l.Retries = 4 39 l.Delay = time.Second 40 So(l.Next(ctx, nil), ShouldEqual, 1*time.Second) 41 So(l.Next(ctx, nil), ShouldEqual, 2*time.Second) 42 So(l.Next(ctx, nil), ShouldEqual, 4*time.Second) 43 So(l.Next(ctx, nil), ShouldEqual, 8*time.Second) 44 So(l.Next(ctx, nil), ShouldEqual, Stop) 45 }) 46 47 Convey(`Will bound exponential delay when MaxDelay is set.`, func() { 48 l.Retries = 4 49 l.Delay = time.Second 50 l.MaxDelay = 4 * time.Second 51 So(l.Next(ctx, nil), ShouldEqual, 1*time.Second) 52 So(l.Next(ctx, nil), ShouldEqual, 2*time.Second) 53 So(l.Next(ctx, nil), ShouldEqual, 4*time.Second) 54 So(l.Next(ctx, nil), ShouldEqual, 4*time.Second) 55 So(l.Next(ctx, nil), ShouldEqual, Stop) 56 }) 57 }) 58 }