Replaced defer statements with t.Cleanup in docs #157
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi there,
I just replaced the
defer
statements witht.Cleanup
in the README, as it's generally not a good idea to usedefer
in tests. Lemme explain why.Consider this test:
I'm using the httpstatus service as mock URLs to send requests to. Sending requests to
https://mock.httpstatus.io/{status_code}
always returns a response with the specified status code.The test above is using test tables to send
GET
requests to the following two endpoints:https://mock.httpstatus.io/400
https://mock.httpstatus.io/404
Normally
https://mock.httpstatus.io
will respond with400
and404
respectively, but the test is mocking both to respond with200
. If we run this test, it does exactly that, and passes with no issues:$ go test PASS ok github.com/alvii147/httpmock-playground 0.550s
The problem shows up when we add the
t.Parallel()
directive to make the two test cases run in parallel:When we run this, we get:
The logged output is telling us that
https://mock.httpstatus.io
actually responded with400
and404
respectively, which means we actually sent a request tohttps://mock.httpstatus.io
, andhttpmock
failed to intercept it. But why?The answer is the
defer
statement actually runs before the individual test cases when the test cases are parallelized. This is an important feature of Go's testing library, you can read more about it here.For this purpose exactly, Go's testing library offers the
t.Cleanup()
. Any function passed intot.Cleanup()
will only execute after all sub tests have executed and returned. If we replace thedefer
statement witht.Cleanup()
, this issue no longer persists, and we are able to run tests in parallel properly:$ go test PASS ok github.com/alvii147/httpmock-playground 0.507s