30 March, 2019

TIL #14 - testing time, requests, anonymous functions,

Notes taken between: 2-30 March 2019

testing time sensitive functions in Go

If you've ever written js>var now = time.Now() in a function and then tried to test it you would have encountered how time will change on each test run. so to mock out time in tests youll first have to set outside your function

var now = time.Now

and inside your function you would call it.


and then in your test you would set the time. js>now = func() time.Time { return time.Unix(100, 0) }

there are also libraries that handle mocking time; some favourites include: https://github.com/jonboulle/clockwork Replace uses of the time package with the clockwork.Clock interface instead. example of testing .Sleep() https://github.com/jonboulle/clockwork/blob/master/example_test.go Dwnside: needs to change application code:

Another contender: https://github.com/thejerf/abtime "Package abtime provides abstracted time functionality that can be swapped between testing and real without changing application code.”

Mock times, timers, and tickers

  • Stub is replacement for some dependency in your code that will be used during test execution. It is typically built for one particular test and unlikely can be reused for another because it has hardcoded expectations and assumptions.

  • Mock takes stubs to next level. It adds means for configuration, so you can set up different expectations for different tests. That makes mocks more complicated, but reusable for different tests.

Go test requests

In go you have to handle your errors or use an _ to ignore them. Bu how should you handle errors in tests? The question you should ask yourself is how likely is it to cause a hard to debug problem in a few lines? if likely, handle your errors. If you're doing a request in a test rather than r, _ := http.NewRequest(...) you should use httptest.NewRequest instead as it doesnt return an error, and sets the request up much more like an incoming request a server would see.

php interfaces vs golang ineterfaces