go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/common/clock/testclock/testclock_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 testclock 16 17 import ( 18 "context" 19 "testing" 20 "time" 21 22 . "github.com/smartystreets/goconvey/convey" 23 "go.chromium.org/luci/common/clock" 24 ) 25 26 func TestTestClock(t *testing.T) { 27 t.Parallel() 28 29 Convey(`A testing clock instance`, t, func() { 30 now := time.Date(2015, 01, 01, 00, 00, 00, 00, time.UTC) 31 ctx, clk := UseTime(context.Background(), now) 32 33 Convey(`Returns the current time.`, func() { 34 So(clk.Now(), ShouldResemble, now) 35 }) 36 37 Convey(`When sleeping with a time of zero, immediately awakens.`, func() { 38 clk.Sleep(ctx, 0) 39 So(clk.Now(), ShouldResemble, now) 40 }) 41 42 Convey(`Will panic if going backwards in time.`, func() { 43 So(func() { clk.Add(-1 * time.Second) }, ShouldPanic) 44 }) 45 46 Convey(`When sleeping for a period of time, awakens when signalled.`, func() { 47 sleepingC := make(chan struct{}) 48 clk.SetTimerCallback(func(_ time.Duration, _ clock.Timer) { 49 close(sleepingC) 50 }) 51 52 awakeC := make(chan time.Time) 53 go func() { 54 clk.Sleep(ctx, 2*time.Second) 55 awakeC <- clk.Now() 56 }() 57 58 <-sleepingC 59 clk.Set(now.Add(1 * time.Second)) 60 clk.Set(now.Add(2 * time.Second)) 61 So(<-awakeC, ShouldResemble, now.Add(2*time.Second)) 62 }) 63 64 Convey(`Awakens after a period of time.`, func() { 65 afterC := clock.After(ctx, 2*time.Second) 66 67 clk.Set(now.Add(1 * time.Second)) 68 clk.Set(now.Add(2 * time.Second)) 69 So(<-afterC, ShouldResemble, clock.TimerResult{now.Add(2 * time.Second), nil}) 70 }) 71 72 Convey(`When sleeping, awakens if canceled.`, func() { 73 ctx, cancelFunc := context.WithCancel(ctx) 74 75 clk.SetTimerCallback(func(_ time.Duration, _ clock.Timer) { 76 cancelFunc() 77 }) 78 79 So(clk.Sleep(ctx, time.Second).Incomplete(), ShouldBeTrue) 80 }) 81 }) 82 }