Re:Mocking time and testing event loops in Go
by jrockway on Monday May 25, 2020 @07:59AM
(#23300160)
When I programmed Java I injected a lot of clocks and didn't find it to be that terrible. I find myself not doing that in Go, instead preferring to leave timekeeping out of as much code as possible, and letting the calling code set the time constraints.
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.
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.