mirror of
https://github.com/EchoVault/SugarDB.git
synced 2025-10-16 13:00:40 +08:00
Implemented a Clock interface that is injected everywhere time.Now and time.After are used.
This commit is contained in:
41
internal/clock/clock.go
Normal file
41
internal/clock/clock.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package clock
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Clock interface {
|
||||
Now() time.Time
|
||||
After(d time.Duration) <-chan time.Time
|
||||
}
|
||||
|
||||
func NewClock() Clock {
|
||||
// If we're in a test environment, return the mock clock.
|
||||
if strings.Contains(os.Args[0], ".test") {
|
||||
return MockClock{}
|
||||
}
|
||||
return RealClock{}
|
||||
}
|
||||
|
||||
type RealClock struct{}
|
||||
|
||||
func (RealClock) Now() time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
|
||||
func (RealClock) After(d time.Duration) <-chan time.Time {
|
||||
return time.After(d)
|
||||
}
|
||||
|
||||
type MockClock struct{}
|
||||
|
||||
func (MockClock) Now() time.Time {
|
||||
t, _ := time.Parse(time.RFC3339, "2036-01-02T15:04:05+07:00")
|
||||
return t
|
||||
}
|
||||
|
||||
func (MockClock) After(d time.Duration) <-chan time.Time {
|
||||
return time.After(d)
|
||||
}
|
Reference in New Issue
Block a user