Skip to content

Commit d27d720

Browse files
ethantkoeniglunny
authored andcommitted
Use unique temp dirs in unit tests (#3494)
* Use unique temp dirs in unit tests * Remove temp dirs after tests run * os.RemoveAll -> removeAllWithRetry
1 parent 2f5c1ba commit d27d720

File tree

1 file changed

+25
-8
lines changed

1 file changed

+25
-8
lines changed

models/unit_tests.go

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ package models
66

77
import (
88
"fmt"
9+
"io/ioutil"
10+
"net/url"
911
"os"
1012
"path/filepath"
1113
"testing"
@@ -18,7 +20,6 @@ import (
1820
"github.com/go-xorm/xorm"
1921
"github.com/stretchr/testify/assert"
2022
"gopkg.in/testfixtures.v2"
21-
"net/url"
2223
)
2324

2425
// NonexistentID an ID that will never exist
@@ -27,32 +28,48 @@ const NonexistentID = 9223372036854775807
2728
// giteaRoot a path to the gitea root
2829
var giteaRoot string
2930

31+
func fatalTestError(fmtStr string, args ...interface{}) {
32+
fmt.Fprintf(os.Stderr, fmtStr, args...)
33+
os.Exit(1)
34+
}
35+
3036
// MainTest a reusable TestMain(..) function for unit tests that need to use a
3137
// test database. Creates the test database, and sets necessary settings.
3238
func MainTest(m *testing.M, pathToGiteaRoot string) {
3339
var err error
3440
giteaRoot = pathToGiteaRoot
3541
fixturesDir := filepath.Join(pathToGiteaRoot, "models", "fixtures")
3642
if err = createTestEngine(fixturesDir); err != nil {
37-
fmt.Fprintf(os.Stderr, "Error creating test engine: %v\n", err)
38-
os.Exit(1)
43+
fatalTestError("Error creating test engine: %v\n", err)
3944
}
4045

4146
setting.AppURL = "https://try.gitea.io/"
4247
setting.RunUser = "runuser"
4348
setting.SSH.Port = 3000
4449
setting.SSH.Domain = "try.gitea.io"
45-
setting.RepoRootPath = filepath.Join(os.TempDir(), "repos")
46-
setting.AppDataPath = filepath.Join(os.TempDir(), "appdata")
50+
setting.RepoRootPath, err = ioutil.TempDir(os.TempDir(), "repos")
51+
if err != nil {
52+
fatalTestError("TempDir: %v\n", err)
53+
}
54+
setting.AppDataPath, err = ioutil.TempDir(os.TempDir(), "appdata")
55+
if err != nil {
56+
fatalTestError("TempDir: %v\n", err)
57+
}
4758
setting.AppWorkPath = pathToGiteaRoot
4859
setting.StaticRootPath = pathToGiteaRoot
4960
setting.GravatarSourceURL, err = url.Parse("https://secure.gravatar.com/avatar/")
5061
if err != nil {
51-
fmt.Fprintf(os.Stderr, "Error url.Parse: %v\n", err)
52-
os.Exit(1)
62+
fatalTestError("url.Parse: %v\n", err)
5363
}
5464

55-
os.Exit(m.Run())
65+
exitStatus := m.Run()
66+
if err = removeAllWithRetry(setting.RepoRootPath); err != nil {
67+
fatalTestError("os.RemoveAll: %v\n", err)
68+
}
69+
if err = removeAllWithRetry(setting.AppDataPath); err != nil {
70+
fatalTestError("os.RemoveAll: %v\n", err)
71+
}
72+
os.Exit(exitStatus)
5673
}
5774

5875
func createTestEngine(fixturesDir string) error {

0 commit comments

Comments
 (0)