time.Now returns the current local time as a time.Time. Calling it inside time-sensitive logic can make tests brittle because execution delays change the observed boundary. section 11.6
A timing-dependent test
A cache test creates events with time.Now().Add offsets, trims entries older than 15 milliseconds, and expects two events. If the machine becomes busy, the moving clock can produce a different result. section 11.6
type Cache struct {
mu sync.RWMutex
events []Event
}
type Event struct {
Timestamp time.Time
Data string
}
func (c *Cache) TrimOlderThan(since time.Duration) {
c.mu.RLock()
defer c.mu.RUnlock()
t := time.Now().Add(-since) #1
for i := 0; i < len(c.events); i++ {
if c.events[i].Timestamp.After(t) {
c.events = c.events[i:] #2
return
}
}
}
Inspect the direct implementation: TrimOlderThan computes a cutoff with time.Now().Add(-since) before scanning time-sorted events. section 11.6
