tests: Make sure TestMain cleans up after itself

os.Exit() doesn't execute defer-ed functions, OTOH we call panic()
in case of setup errors, which does run defer-ed functions. So move
the actual test setup and execution in a separate function which will
execute all defer-ed functions and return the exit code from the
test suite to TestMain.
This commit is contained in:
Alexander Todorov 2020-04-24 12:48:39 +02:00 committed by Tom Gundersen
parent 5fd2590579
commit 7ce08bc788
2 changed files with 24 additions and 14 deletions

View file

@ -19,29 +19,35 @@ var testState *TestState
// Setup the socket to use for running the tests
// Also makes sure there is a running server to test against
func TestMain(m *testing.M) {
func executeTests(m *testing.M) int {
var err error
testState, err = setUpTestState("/run/weldr/api.socket", 60*time.Second, false)
if err != nil {
fmt.Printf("ERROR: Test setup failed: %s\n", err)
os.Exit(1)
panic(err)
}
// Setup the test repo
dir, err := test.SetUpTemporaryRepository()
if err != nil {
fmt.Printf("ERROR: Test repo setup failed: %s\n", err)
os.Exit(1)
panic(err)
}
// Cleanup after the tests
defer func() {
err := test.TearDownTemporaryRepository(dir)
if err != nil {
fmt.Printf("ERROR: Failed to clean up temporary repository: %s\n", err)
}
}()
testState.repoDir = dir
// Run the tests
rc := m.Run()
// Cleanup after the tests
err = test.TearDownTemporaryRepository(dir)
if err != nil {
fmt.Printf("ERROR: Failed to clean up temporary repository: %s\n", err)
}
os.Exit(rc)
return m.Run()
}
func TestMain(m *testing.M) {
os.Exit(executeTests(m))
}

View file

@ -23,7 +23,7 @@ import (
// Hold test state to share between tests
var testState *TestState
func TestMain(m *testing.M) {
func executeTests(m *testing.M) int {
// Setup the mocked server running on a temporary domain socket
tmpdir, err := ioutil.TempDir("", "client_test-")
if err != nil {
@ -53,7 +53,7 @@ func TestMain(m *testing.M) {
go func() {
err := server.Serve(ln)
if err != nil {
if err != nil && err != http.ErrServerClosed {
panic(err)
}
}()
@ -64,5 +64,9 @@ func TestMain(m *testing.M) {
}
// Run the tests
os.Exit(m.Run())
return m.Run()
}
func TestMain(m *testing.M) {
os.Exit(executeTests(m))
}