Suppose that I set up a Docker container with a DB for my tests, and I do that in testing.TestMain because I want this to be done once and globally. I write a defer
statement in this testing.Main()
that does the cleanup (namely, removes the DB container).
Now, suppose that something goes wrong and my tests panic. This issue tells me that I can not write custom recover
code to ensure that the container is removed. This is true: testing.M.Run()
does its own recover()
call, and it looks like there's no way to override its behaviour.
The question is: what should I do to make sure that my cleanup code is executed no matter what?
As noted in the issue you linked to:
The panic could come from a goroutine started by a test and the testing package can't add a defer to those goroutines to catch the panic.
Aadditionally, some panics are impossible to recover, e.g. out of menory or runtime memory corruption.
In short, you cannot make sure that any code will be executed in all circumstances.
If your cleanup is non-critical, you can do it before & after (i.e. at the start of your tests, check if your container already exists and destroy it before creating a new one, then make a best effort to destroy it at the end). If your cleanup is critical, then wrap your go test
call with something (e.g. a shell script or makefile) and make the wrapper responsible for the setup & teardown of external dependencies.