103 points · by zdw · 6y ago · 33 comments
Typically you would just do this with contexts. I was going to write down some examples of not using contexts, but I think your best bet is to just rewrite code to take contexts when it can be cancelled. A common mistake that people make is timing out some operation, usually happening in another goroutine, and then their program ends up leaking goroutines and crashing because the abandoned work was never correctly cleaned up. If your API doesn't allow you to abort, you will have to modify it, because downstream RPC servers come and go, people press the "stop" button in their browser, TCP connections close, etc.
Or, create the timer outside and inject its channel. Want to fire the timer? Just write to the channel.
If you do expect to get a lot of value from testing the event loop, blocking on individual messages received or not received as in the article is a reasonable way to de-flakify your tests (in that case, I'd expect the tests to inject mocks and/or use private interfaces). However, it is a code smell if any other tests are depending on the details of that event loop.
- Even though Clock is an interface, Timer is not. This means that if you want to use that package in combination with gomock, you're out of luck.
- The Clock interface doesn't provide a wrapper for context.WithTimeout(), which also depends on the system clock.
- Nit: The Clock interface also exposes functions like time.After(), which should in my opinion never be used in production code, as they don't support efficient cancelation. You should use timers instead.
In the end I resorted to writing my own set of interfaces.
Code: https://github.com/buildbarn/bb-storage/tree/master/pkg/cloc...
Documentation: https://pkg.go.dev/github.com/buildbarn/bb-storage/pkg/clock
In general, libraries should offer structs, and you should declare your own interfaces with the subset of methods that you require.
This is somewhat messy here because the timer channel is accessed by a field rather than a method, but you could write a struct that embeds time.Timer and adds C() as a method. Then both your wrapped time.Timer and your mock/fake could fulfill your interface.
Defining interfaces around existing types works, but quickly falls apart as soon as methods return concrete types. In those cases you need to write more complex wrappers, which is often not worth the hassle.
Can you expand on this? I find time.After super useful for time arithmetic in control flow, like checking for expiry, validating leases, etc.
I’m talking about the free function After() that’s part of the time package:
https://golang.org/pkg/time/#After
That one can be used to create a channel that triggers after a certain amount of time. The reason you shouldn’t be using that one is because you can’t clean it up before it triggers. This means that any code that bails out early ends up leaking memory temporarily.
defer dates.SetNowSource(dates.DefaultNowSource)
dates.SetNowSource(dates.NewSequentialNowSource(time.Date(2018, 10, 18, 14, 20, 30, 123456, time.UTC)))
dates.Now()Difference in mine is that dates.SetNowSource returns a reset function that you can defer, like with context.WithCancel().
I'd say in a lot of, or most circumstances it's best to just bite the bullet and refactor the mess into something more maintainable.
But there are exceptions to every rule, and let's face it, sometimes it's just too expensive.
Well what you can often do in these circumstances is just mock out the whole damn time package. That's what I did when faced with a similar situation and I was pleasantly surprised with the results.
I wrote https://github.com/echlebek/timeproxy to be a drop-in import for stdlib time. (Modulo any drift in stdlib since it was written)
I wrote https://github.com/echlebek/crock as a fake time implementation that I can exercise complete control over. It lets me control tickers, timers, time.Now, and all that however I like.
Since timeproxy just dispatches all calls to stdlib by default, I feel confident using it in production.
crock has some bugs, but they usually only show up in pathological cases, and you can easily prove that its code path will only get executed in tests, by ensuring that it only gets imported in _test.go files.
So far to my knowledge I'm the only user of these libraries, although I have employed them in a large open source application. Really, the libraries are less important than concept, which I learned from a Go author's slide deck on mocking out the os library years ago.
1. Pass in a value called `now func() time.Time` into the constructor function of my struct. This allows me to call `inst.now()` on a particular instance of my structure.
2. Have a global field in a package: `var Now func() time.Time = time.Now` This allows `mypkg.Now()`
All of this avoids taking yet another external package dependency with only a couple of lines of code.
You don't have to use globals for any of this, but people like doing it, and then have a bunch of workarounds to make the tests work. If you don't want workarounds, your API can be "func CreateRow(..., now time.Time)" or "func DoSomethingWithTimeout(timeout time.Duration)" and just pass the correct values in. (Don't do the timeout one, though, just use a context.)
So you could set up multiple incoming streams, advance the clock to a very high level of precision and assert e.g packet A triggered packet B after 20ms, or timer X fired after 1s. This made the tests extremely reliable and fast to run, since you were pretty much CPU bound - something that I don't think would have been otherwise possible.
I'm not jumping to conclusions, I have my own mock for time that I wrote in an afternoon which has survived several years on a big golang app
Mocking system clocks for testing just confirms that truth. If you can't think of an alternative to using some variation of systemtime function for business operational rules, I'm not really sure what you're pushing to production.
time.Now in go returns both the system time (i.e. if you do '.Seconds' or 'String' on that time, you get a wall clock time), but also returns a monotonic time (if you subtract or compare two times, it uses monotonic time).
Go's time package isn't just systemtime, and there's really not an alternative to it in the language. You're arguing against a strawman.
Maybe you're using time-package right and avoiding the above, maybe not. Timestamp usage is best to avoid for anything business critical.
I assumed this package about mocking time was _not_ about mocking timestamps but program behavior. For example, if I have a loop that says "every 20 seconds, do X", and I want to test that, I now have to mock time.
That's not about timestamps, that's about comparing monotonic clocks for "20s have elapsed".
The go time package doesn't just give you a timestamp to do something with, it also lets you compare times. That was my point.
It sounds like your original comment was arguing that mocking time isn't useful, so I assumed you meant all uses of time.