diff options
author | Patrick Steinhardt <psteinhardt@gitlab.com> | 2020-11-17 14:34:13 +0300 |
---|---|---|
committer | Patrick Steinhardt <psteinhardt@gitlab.com> | 2020-11-17 14:34:13 +0300 |
commit | 71353b6dcf4fae488ede449ec12555d4d1e30b0a (patch) | |
tree | 85326b43837b9549d9b0e61cf683ff244590f93a /STYLE.md | |
parent | 036b0bea317cee228359d63786a7f5281326960e (diff) |
style: Document gotchas when using defers with `os.Exit()`
Using `os.Exit()` will cause the calling process to exit immediately
without executing any deferred functions. In the context of our tests,
this means that any created ondisk state may not get cleaned up
correctly. This commit thus documents those pitfalls in "STYLE.md".
Diffstat (limited to 'STYLE.md')
-rw-r--r-- | STYLE.md | 26 |
1 files changed, 26 insertions, 0 deletions
@@ -223,6 +223,32 @@ func TestTime(t *testing.T) { [Cheney blog post]: https://dave.cheney.net/2013/06/09/writing-table-driven-tests-in-go [Golang wiki]: https://github.com/golang/go/wiki/TableDrivenTests +### Fatal exit + +Aborting test execution with any function which directly or indirectly calls +`os.Exit()` should be avoided as this will cause any deferred function calls to +not be executed. As a result, tests may leave behind testing state. Most +importantly, this includes any calls to `log.Fatal()` and related functions. + +### Common setup + +When all tests require a common setup, we use the `TestMain()` function for +this. `TestMain()` must call `os.Exit()` to indicate whether any tests failed. +As this will cause deferred function calls to not be processed, we use the +following pattern: + +``` +func TestMain(m *testing.M) { + os.Exit(testMain(m)) +} + +func testMain(m *testing.M) int { + cleanup := testhelper.Configure() + defer cleanup() + return m.Run() +} +``` + ## Black box and white box testing The dominant style of testing in Gitaly is "white box" testing, meaning |