github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/kbfs/test/clocktest/clock.go (about) 1 // Copyright 2019 Keybase Inc. All rights reserved. 2 // Use of this source code is governed by a BSD 3 // license that can be found in the LICENSE file. 4 5 package clocktest 6 7 import ( 8 "sync" 9 "time" 10 ) 11 12 // TestClock returns a set time as the current time. 13 type TestClock struct { 14 l sync.RWMutex 15 t time.Time 16 } 17 18 // NewTestClockNow constructs a new test clock, using the current 19 // wall-clock time as the static time. 20 func NewTestClockNow() *TestClock { 21 return &TestClock{t: time.Now()} 22 } 23 24 // NewTestClockAndTimeNow constructs a new test clock, using the 25 // current wall-clock time as the static time, and returns that time 26 // as a convenience. 27 func NewTestClockAndTimeNow() (*TestClock, time.Time) { 28 t0 := time.Now() 29 return &TestClock{t: t0}, t0 30 } 31 32 // Now implements the Clock interface for TestClock. 33 func (tc *TestClock) Now() time.Time { 34 tc.l.RLock() 35 defer tc.l.RUnlock() 36 return tc.t 37 } 38 39 // Set sets the test clock time. 40 func (tc *TestClock) Set(t time.Time) { 41 tc.l.Lock() 42 defer tc.l.Unlock() 43 tc.t = t 44 } 45 46 // Add adds to the test clock time. 47 func (tc *TestClock) Add(d time.Duration) { 48 tc.l.Lock() 49 defer tc.l.Unlock() 50 tc.t = tc.t.Add(d) 51 }