-
Notifications
You must be signed in to change notification settings - Fork 17.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
time: mockable time support #8869
Comments
I'm not entirely sure this is a good idea. I'm also not sure what it would look like. If the goal is simply to provide Ticker and Timer calls for testing, I think that could be done entirely independently of the time package, along the lines of the old playground code. The testing package would keep its own queue of events, and step forward to the next event without actually waiting. Labels changed: added repo-main, release-none. |
Any chance of something happening for this? |
(I'm okay with hearing no! It's just an open cycle in my head I'm trying to clear out.) |
It's unlikely to happen any time soon. |
after lots of experimentation I figured out the mock clock sometimes simply doesn't properly trigger, so that in Usage.Report() sometimes nothing is received on the tick channel, despite advancing the fake clock by more than strictly nessecary (i tried with an extra ms), despite calling runtime.Goshed() ourselves, and despite sleeping 20 ms with the real clock. The author of the clock package confirms that due to the way the runtime schedules goroutines, there's no way around the fake clock sometimes not working. See https://gophers.slack.com/archives/general/p1462238960008162 Furthermore, in discussion with the golang developers at golang/go#8869 it becomes clear that it's unlikely that we'll have a fakeable clock anytime soon. Ben Johnson (clock author) suggests in the above mentioned gophers thread that we could mock out the tick function and pass in a different function in tests. However, that changes so much of the time logic that it becomes pointless to do any time-based testing in this design. We could also switch to simply test the basics, not time based. Since the timing code is pretty easy. However before we go that route, I wanted to try working with the real clock. Basically run the usage reporting in real time, but scaled down to millisecond level instead of second level, to make it finish fairly quickly. So now some semantics are changing a bit: * we allow up to <period> ms for the usage report to be in the state we need it * so we now works with steps, which don't happen at exact predictable timestamps, rather they have to happen within a timeframe * checking timestamp would have gotten more complicated, so I just removed it. It's easy to reason that if the updates come within the alotted times, then the timestamps should also be set correctly. * there's no serious need to explicitly pass around interval settings anymore, we just use 1 everywhere. If it turns out that this approach also triggers false positives (for example due to circleCI machines being maxed out of CPU and the reporting unable to happen within the needed time) then we can address as needed and still switch to the simpler approach. But that seems very unlikely. This should work.
after lots of experimentation I figured out the mock clock sometimes simply doesn't properly trigger, so that in Usage.Report() sometimes nothing is received on the tick channel, despite advancing the fake clock by more than strictly nessecary (i tried with an extra ms), despite calling runtime.Goshed() ourselves, and despite sleeping 20 ms with the real clock. The author of the clock package confirms that due to the way the runtime schedules goroutines, there's no way around the fake clock sometimes not working. See https://gophers.slack.com/archives/general/p1462238960008162 Furthermore, in discussion with the golang developers at golang/go#8869 it becomes clear that it's unlikely that we'll have a fakeable clock anytime soon. Ben Johnson (clock author) suggests in the above mentioned gophers thread that we could mock out the tick function and pass in a different function in tests. However, that changes so much of the time logic that it becomes pointless to do any time-based testing in this design. We could also switch to simply test the basics, not time based. Since the timing code is pretty easy. However before we go that route, I wanted to try working with the real clock. Basically run the usage reporting in real time, but scaled down to millisecond level instead of second level, to make it finish fairly quickly. So now some semantics are changing a bit: * we allow up to <period> ms for the usage report to be in the state we need it * so we now works with steps, which don't happen at exact predictable timestamps, rather they have to happen within a timeframe * checking timestamp would have gotten more complicated, so I just removed it. It's easy to reason that if the updates come within the alotted times, then the timestamps should also be set correctly. * there's no serious need to explicitly pass around interval settings anymore, we just use 1 everywhere. If it turns out that this approach also triggers false positives (for example due to circleCI machines being maxed out of CPU and the reporting unable to happen within the needed time) then we can address as needed and still switch to the simpler approach. But that seems very unlikely. This should work.
One possible step toward this, for the common
Then the existing Whether the ticker/timer implementations could take advantage of such a The primary motivation here, of course, is to provide a standard place to mock out a clock, while honoring the Go compatibility promise. It would, obviously, require altering any existing code that needs mocks, but that's already happening, so this would just provide a defined, supported way to do such mocks. One other (possible) implication of such a |
Having a caller-replaceable time.DefaultClock sounds both racy and like a step in the wrong direction. If this is about testability, we should live in a world where tests are parallelizable and don't muck with globals. (I'm ok with eating the costs of needing to write code to be testable; that's going to be true anyway, regardless of this yet another reason to write "hermetic" libraries.) My reading of this issue is to provide better means for such a mock-clock library to simulate the effects of time passing "until next interesting event" in the scheduler. |
Perhaps so, but it's a pattern commonly used elsewhere in the Go standard library.
Code which relies on this functionality for testing shouldn't mess with globals (the same holds for the other places in the stdlib where this is done), and should instead use dependency injection. The goal isn't to make it possible to modify I think of this as the same as |
Note that the suggestion of |
If you dig around the issues enough, you will find core devs sometimes expressing regret about those decisions. Just because it was done in the early days doesn't mean it should be the standard going forward. |
That's fair. I've often wondered about the wisdom of that myself. But I still don't think that renders my (entire) suggestion untenable. I'd welcome your feedback on the remainder of my proposal. Specifically on the For the sake of discussion, the I feel like this conversation got derailed by this (IMO, minor) aspect of my proposal. I'd rather address the core of it. |
I think the two existing & used libraries mentioned in the first comment are plenty to inform the API design; as far as I understand the challenge here is purely the integration with runtime. See mentions of "flaky". |
Yeah, my first paragraph in this ticket was really to set up the latter two that describe why we want and what needs stdlib or runtime support to write better time-dependent tests. There are likely lots of levels of ideas to address that Ticker and Timer problem. One is to give Tickers and Timers new constructor funcs that take some kind of expanded |
This ticket pre-dates the Go proposal mechanisms and we might be getting to the time for a formal proposal to resolve this one. It would be cool to hear ideas different from the rough sketch I gave above. I'm fairly sure there is one. |
When this issue was filed, context.Context was not in the standard library; Context was added in Go 1.7 in 2016. I like the idea of attaching mocks to the context. It may be considered a non-starter for some people as an abuse of context. The following assumes this is reasonable: Here's a precedent based on attaching a Clock interface on a context.Context. This is not racy and permits very well scoped tests:
main.go
main_test.go
IMHO this is quite clean. I'm not sure the Clock interface here should be used as-is. I'm not sure it's a good idea to pass a context in to Sleep and NewTimer. Still, I think something inspired by this could be added to the standard library without any regression. |
This comment has been minimized.
This comment has been minimized.
is this going to ever happen or not? |
@ivanjaros As far as I know nobody is actively working on this. |
salutations from 2022. almost 2023. any news on this ? There is an interesting piece on this issue here: https://dmitryfrank.com/articles/mocking_time_in_go The author says that atleast a way to wait for all the goroutines to run would still improve the situation. |
If something changes, people will comment here. Nothing has changed. |
@ianlancetaylor any suggestion about what it would take for something to change ? Would it be worth it to do a proposal for the new review process ? For reference, I've been using benbjohnson/clock too, and it works fairly well for all my needs - and those of many others too, judging by the star count - but it would be nice to have an idea of where stdlib is going or not. IMHO even a definite "won't happen" would be more useful than having this issue remain in limbo. |
A good first step would be to write down exactly what an API to address this issue would look like. That would likely become a proposal at some point, but it doesn't need to start as a proposal. I think it's clear that the core Go team is not going to work on this issue. But that in itself doesn't mean that this issue should be closed, because it is possible that someone else will develop a workable approach that could be incorporated into the standard library. At least, that doesn't seem to me to be clearly impossible. So it seems to me that if you are concerned that this issue is in limbo, you should simply assume that it will never be addressed. But if somebody wants to address it, please feel free to give it a try. |
Alright, since I got nerd-sniped by this, here are two fleshed-out proposals. I'd love to hear feedback on them both from the community and from core devs. Standard Interface ProposalAdd a new interface type, Clock, which requires a set of methods equivalent to the current top-level functions in the time package. Test helper packages can provide fake clock implementations that match the Clock interface, and packages which wish to use such helpers can design their functions/structs to take/store values matching the Clock interface. This is inspired by jmhodges’ fakeclock. type Clock interface {
func Now() Time
func After(d Duration) <-chan Time
func Sleep(d Duration)
func Since(t Time) Duration
func Until(t Time) Duration
func NewTicker(d Duration) Tocker
func AfterFunc(d Duration, f func()) Tocker
func NewTimer(d Duration) Tocker
} Additionally, a new non-exported type type clock struct {}
func NewClock() Clock { return &clock{} }
func (c *clock) Sleep(d Duration) { Sleep(d) }
// etc Note that the NewTicker, AfterFunc, and NewTimer methods above all return a Tocker (name to be bikeshedded). This is also a new interface type, nearly already satisfied by the existing Ticker and Timer concrete types. This allows test helper packages to additionally provide fake tickers and timers that send messages on the channel returned by the Listen() method. type Tocker interface { // name to be bike-shedded
func Listen() <-chan Time
func Reset(d Duration) bool
func Stop() bool
} Finally, add .Listen() methods to the existing Ticker and Timer types which return their .C member, to satisfy the Tocker interface. I believe this plan is fully backwards-compatible: only new types and methods are added to the time package, no existing exported symbols are changed. I believe this accomplishes the major testing goals, by allowing test helper packages to provide a variety of fake tickers and timers which implement a stdlib-supported interface (Tocker). For example, a FastClock’s NewTicker method could return a Tocker which sends a message on its channel 100x faster than a traditional ticker would. Or a ManualClock could expose a SendTick method, which causes any Tocker returned by its NewTicker method to send a message on its channel. Or an AutoClock could expose an Advance method which moves its own internal sense of time forward, and causes any Tockers returned by its NewTicker and NewTimer methods to send messages on their channels, if time was advanced far enough forward for them to fire. This approach has two major disadvantages. First, it massively increases the API surface of the time package by defining two new interfaces. Second, it requires all code which currently calls (e.g.) time.Sleep() to instead carry a Clock around and call c.Sleep(). Although there is lots of code (e.g. any code which already uses jmhodges’ library) which does this, it would become a requirement for any new code that wants to adopt this system. Customizable Time ProposalAdd two new methods, NewTimerCustom and NewTickerCustom, which replace the Timer/Ticker’s underlying runtimeTimer with something that can be controlled externally (i.e. by the test code, to manipulate the code-under-test). type RuntimeTimer interface { // name to be bike-shedded
func Start(c chan<- Time)
func Stop() bool
func Reset(d Duration) bool
}
func NewTimerCustom(d Duration, r RuntimeTimer) *Timer {
c := make(chan Time, 1)
t := &Timer{
C: c,
r: r,
}
t.r.Start(c)
return t
}
// etc Update the existing Ticker and Timer implementations to use this interface rather than runtimeTimer directly. For example: type Timer struct {
C <-chan Time
r RuntimeTimer
}
type runtimeTimerWrapper struct {
inner runtimeTimer
}
func (rt runtimeTimerWrapper) Start(c chan<- Time) { rt.inner.arg = c; startTimer(&rt.inner) }
func (rt runtimeTimerWrapper) Stop() bool { return stopTimer(&rt.inner) }
func (rt runtimeTimerWrapper) Reset(d Duration) bool { return resetTimer(&rt.inner, d) }
func NewTimer(d Duration) *Timer {
c := make(chan Time, 1)
t := &Timer{
C: c,
r: runtimeTimerWrapper{
inner: runtimeTimer{
when: when(d),
f: sendTime,
},
},
}
t.r.Start(c)
return t
}
func (t *Timer) Stop() bool {
if t.r == nil {
panic("time: Stop called on uninitialized Timer")
}
return t.r.Stop()
}
// etc I believe this plan is fully backwards-compatible: although it modifies existing types and functions, it only touches their non-exported runtimeTimer implementation details. I believe this accomplishes most of the testing goals, by allowing test helper packages to provide a variety of RuntimeTimer implementations that can send messages on their output channel without waiting for the system clock to advance. For example, there could be a ManualRuntimeTimer which exposes a .Tick(t time.Time) method, and sends that time on its channel every time that method is called. Or there could be an AutoRuntimeTimer which uses a channel to receive updates from a fake clock, and sends messages on its channel when time advances forward. The biggest disadvantage of this approach is that it may be difficult for testing code to supply custom RuntimeTimers to code-under-test. For example, the code under test may propagate a time.Duration value many layers deep in a call stack before finally calling time.NewTicker(d). Replacing that with time.NewTickerCustom would require plumbing the test-only RuntimeTimer implementation through that whole call stack as well. Perhaps the best solution to this problem is the approach taken by jmhodges’ package, where the code under test uses a custom Clock interface type, which can be implemented either by a “real'' clock or a fake one, and for the fake clock’s NewTicker method to call NewTickerCustom behind the scenes. This resembles the Clock interface in the first proposal above, but the definition of that interface would be left to individual test helper packages. Another approach to solving this problem would be to allow there to be a global variable of type RuntimeTimer which defaults to the runtimeTimerWrapper, and to allow test code to replace it with a custom RuntimeTimer. The time.NewTicker and time.NewTimer functions would automatically use the current global value. This would allow the code under test to be completely agnostic of the fact that its time is being messed with, at the cost of introducing a global. Overall, I prefer the second proposal. I believe it is a smaller and more elegant change, that more directly reflects the idea put forward by @jmhodges in this comment: #8869 (comment) |
@aarongable I'm surprised to not see |
While the second version is less intrusive, the first version appears to be more general, and looks a lot like the |
@flimzy @fgm Thank you both, @fgm The post above already includes |
I have a couple of concerns/comments about the "Standard Interface Proposal":
Further expanding on point 2 above, |
For whomever is following this, Ben B. Johnson archived the repository mentioned in the original issue but https://github.com/jonboulle/clockwork (which is about the same age, but more active) has emerged as another alternative to provide ideas for possible evolutions of the new "Standard API" proposal. |
The text was updated successfully, but these errors were encountered: