From 8b0aaa5f86e40a4699f278d09d116add63f8e4a0 Mon Sep 17 00:00:00 2001 From: Eng Zer Jun Date: Sun, 4 Sep 2022 23:14:53 +0800 Subject: [PATCH] test: use `T.TempDir` to create temporary test directory (#21043) A testing cleanup. This pull request replaces `os.MkdirTemp` with `t.TempDir`. We can use the `T.TempDir` function from the `testing` package to create temporary directory. The directory created by `T.TempDir` is automatically removed when the test and all its subtests complete. This saves us at least 2 lines (error check, and cleanup) on every instance, or in some cases adds cleanup that we forgot. Reference: https://pkg.go.dev/testing#T.TempDir ```go func TestFoo(t *testing.T) { // before tmpDir, err := os.MkdirTemp("", "") require.NoError(t, err) defer os.RemoveAll(tmpDir) // now tmpDir := t.TempDir() } ``` Signed-off-by: Eng Zer Jun --- cmd/migrate_storage_test.go | 3 +-- models/db/engine_test.go | 4 +-- modules/git/commit_info_test.go | 17 +++---------- modules/git/repo_compare_test.go | 8 ++---- modules/git/repo_tag_test.go | 8 ++---- modules/indexer/code/bleve_test.go | 10 +------- modules/indexer/issues/bleve_test.go | 13 ++-------- modules/indexer/issues/indexer_test.go | 9 +------ modules/log/file_test.go | 20 ++++----------- modules/queue/queue_disk_channel_test.go | 10 ++------ modules/queue/queue_disk_test.go | 7 +----- routers/web/repo/settings_test.go | 9 +------ services/wiki/wiki_test.go | 12 ++------- tests/integration/api_repo_file_get_test.go | 10 ++------ tests/integration/api_repo_test.go | 8 ------ tests/integration/create_no_session_test.go | 9 +------ tests/integration/git_clone_wiki_test.go | 3 +-- .../git_helper_for_declarative_test.go | 10 +++----- tests/integration/git_test.go | 21 ++++------------ tests/integration/gpg_git_test.go | 7 ++---- tests/integration/lfs_local_endpoint_test.go | 9 +++---- tests/integration/migrate_test.go | 11 +++++--- tests/integration/repo_tag_test.go | 8 ++---- tests/integration/ssh_key_test.go | 25 +++++-------------- 24 files changed, 57 insertions(+), 194 deletions(-) diff --git a/cmd/migrate_storage_test.go b/cmd/migrate_storage_test.go index e6d205e410..0d264ef5a1 100644 --- a/cmd/migrate_storage_test.go +++ b/cmd/migrate_storage_test.go @@ -53,8 +53,7 @@ func TestMigratePackages(t *testing.T) { ctx := context.Background() - p, err := os.MkdirTemp(os.TempDir(), "migrated_packages") - assert.NoError(t, err) + p := t.TempDir() dstStorage, err := storage.NewLocalStorage( ctx, diff --git a/models/db/engine_test.go b/models/db/engine_test.go index 41279c5005..c26d94c340 100644 --- a/models/db/engine_test.go +++ b/models/db/engine_test.go @@ -5,7 +5,6 @@ package db_test import ( - "os" "path/filepath" "testing" @@ -20,8 +19,7 @@ import ( func TestDumpDatabase(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - dir, err := os.MkdirTemp(os.TempDir(), "dump") - assert.NoError(t, err) + dir := t.TempDir() type Version struct { ID int64 `xorm:"pk autoincr"` diff --git a/modules/git/commit_info_test.go b/modules/git/commit_info_test.go index a12452c404..4bc3596896 100644 --- a/modules/git/commit_info_test.go +++ b/modules/git/commit_info_test.go @@ -6,13 +6,10 @@ package git import ( "context" - "os" "path/filepath" "testing" "time" - "code.gitea.io/gitea/modules/util" - "github.com/stretchr/testify/assert" ) @@ -20,18 +17,14 @@ const ( testReposDir = "tests/repos/" ) -func cloneRepo(url, name string) (string, error) { - repoDir, err := os.MkdirTemp("", name) - if err != nil { - return "", err - } +func cloneRepo(tb testing.TB, url string) (string, error) { + repoDir := tb.TempDir() if err := Clone(DefaultContext, url, repoDir, CloneRepoOptions{ Mirror: false, Bare: false, Quiet: true, Timeout: 5 * time.Minute, }); err != nil { - _ = util.RemoveAll(repoDir) return "", err } return repoDir, nil @@ -118,11 +111,10 @@ func TestEntries_GetCommitsInfo(t *testing.T) { testGetCommitsInfo(t, bareRepo1) - clonedPath, err := cloneRepo(bareRepo1Path, "repo1_TestEntries_GetCommitsInfo") + clonedPath, err := cloneRepo(t, bareRepo1Path) if err != nil { assert.NoError(t, err) } - defer util.RemoveAll(clonedPath) clonedRepo1, err := openRepositoryWithDefaultContext(clonedPath) if err != nil { assert.NoError(t, err) @@ -150,11 +142,10 @@ func BenchmarkEntries_GetCommitsInfo(b *testing.B) { var commit *Commit var entries Entries var repo *Repository - repoPath, err := cloneRepo(benchmark.url, benchmark.name) + repoPath, err := cloneRepo(b, benchmark.url) if err != nil { b.Fatal(err) } - defer util.RemoveAll(repoPath) if repo, err = openRepositoryWithDefaultContext(repoPath); err != nil { b.Fatal(err) diff --git a/modules/git/repo_compare_test.go b/modules/git/repo_compare_test.go index 245920c2bd..63f7254dea 100644 --- a/modules/git/repo_compare_test.go +++ b/modules/git/repo_compare_test.go @@ -10,19 +10,16 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/modules/util" - "github.com/stretchr/testify/assert" ) func TestGetFormatPatch(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") - clonedPath, err := cloneRepo(bareRepo1Path, "repo1_TestGetFormatPatch") + clonedPath, err := cloneRepo(t, bareRepo1Path) if err != nil { assert.NoError(t, err) return } - defer util.RemoveAll(clonedPath) repo, err := openRepositoryWithDefaultContext(clonedPath) if err != nil { @@ -84,12 +81,11 @@ func TestReadWritePullHead(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") // As we are writing we should clone the repository first - clonedPath, err := cloneRepo(bareRepo1Path, "TestReadWritePullHead") + clonedPath, err := cloneRepo(t, bareRepo1Path) if err != nil { assert.NoError(t, err) return } - defer util.RemoveAll(clonedPath) repo, err := openRepositoryWithDefaultContext(clonedPath) if err != nil { diff --git a/modules/git/repo_tag_test.go b/modules/git/repo_tag_test.go index 9d84672862..6a00473bb7 100644 --- a/modules/git/repo_tag_test.go +++ b/modules/git/repo_tag_test.go @@ -8,8 +8,6 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/modules/util" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -38,12 +36,11 @@ func TestRepository_GetTags(t *testing.T) { func TestRepository_GetTag(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") - clonedPath, err := cloneRepo(bareRepo1Path, "TestRepository_GetTag") + clonedPath, err := cloneRepo(t, bareRepo1Path) if err != nil { assert.NoError(t, err) return } - defer util.RemoveAll(clonedPath) bareRepo1, err := openRepositoryWithDefaultContext(clonedPath) if err != nil { @@ -143,12 +140,11 @@ func TestRepository_GetTag(t *testing.T) { func TestRepository_GetAnnotatedTag(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") - clonedPath, err := cloneRepo(bareRepo1Path, "TestRepository_GetAnnotatedTag") + clonedPath, err := cloneRepo(t, bareRepo1Path) if err != nil { assert.NoError(t, err) return } - defer util.RemoveAll(clonedPath) bareRepo1, err := openRepositoryWithDefaultContext(clonedPath) if err != nil { diff --git a/modules/indexer/code/bleve_test.go b/modules/indexer/code/bleve_test.go index 37ed2eb9f0..a34d54bc0e 100644 --- a/modules/indexer/code/bleve_test.go +++ b/modules/indexer/code/bleve_test.go @@ -5,11 +5,9 @@ package code import ( - "os" "testing" "code.gitea.io/gitea/models/unittest" - "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" ) @@ -17,13 +15,7 @@ import ( func TestBleveIndexAndSearch(t *testing.T) { unittest.PrepareTestEnv(t) - dir, err := os.MkdirTemp("", "bleve.index") - assert.NoError(t, err) - if err != nil { - assert.Fail(t, "Unable to create temporary directory") - return - } - defer util.RemoveAll(dir) + dir := t.TempDir() idx, _, err := NewBleveIndexer(dir) if err != nil { diff --git a/modules/indexer/issues/bleve_test.go b/modules/indexer/issues/bleve_test.go index 68a7831a3f..42d22f06a2 100644 --- a/modules/indexer/issues/bleve_test.go +++ b/modules/indexer/issues/bleve_test.go @@ -6,22 +6,13 @@ package issues import ( "context" - "os" "testing" - "code.gitea.io/gitea/modules/util" - "github.com/stretchr/testify/assert" ) func TestBleveIndexAndSearch(t *testing.T) { - dir, err := os.MkdirTemp("", "bleve.index") - assert.NoError(t, err) - if err != nil { - assert.Fail(t, "Unable to create temporary directory") - return - } - defer util.RemoveAll(dir) + dir := t.TempDir() indexer := NewBleveIndexer(dir) defer indexer.Close() @@ -30,7 +21,7 @@ func TestBleveIndexAndSearch(t *testing.T) { return } - err = indexer.Index([]*IndexerData{ + err := indexer.Index([]*IndexerData{ { ID: 1, RepoID: 2, diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index 6bafcbdf24..e8b9ff8370 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -6,7 +6,6 @@ package issues import ( "context" - "os" "path" "path/filepath" "testing" @@ -14,7 +13,6 @@ import ( "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/util" _ "code.gitea.io/gitea/models" @@ -32,11 +30,7 @@ func TestBleveSearchIssues(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) setting.Cfg = ini.Empty() - tmpIndexerDir, err := os.MkdirTemp("", "issues-indexer") - if err != nil { - assert.Fail(t, "Unable to create temporary directory: %v", err) - return - } + tmpIndexerDir := t.TempDir() setting.Cfg.Section("queue.issue_indexer").Key("DATADIR").MustString(path.Join(tmpIndexerDir, "issues.queue")) @@ -44,7 +38,6 @@ func TestBleveSearchIssues(t *testing.T) { setting.Indexer.IssuePath = path.Join(tmpIndexerDir, "issues.queue") defer func() { setting.Indexer.IssuePath = oldIssuePath - util.RemoveAll(tmpIndexerDir) }() setting.Indexer.IssueType = "bleve" diff --git a/modules/log/file_test.go b/modules/log/file_test.go index c3074b69df..cc2b9fe077 100644 --- a/modules/log/file_test.go +++ b/modules/log/file_test.go @@ -14,15 +14,11 @@ import ( "testing" "time" - "code.gitea.io/gitea/modules/util" - "github.com/stretchr/testify/assert" ) func TestFileLoggerFails(t *testing.T) { - tmpDir, err := os.MkdirTemp("", "TestFileLogger") - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() prefix := "TestPrefix " level := INFO @@ -34,7 +30,7 @@ func TestFileLoggerFails(t *testing.T) { // assert.True(t, ok) // Fail if there is bad json - err = fileLogger.Init("{") + err := fileLogger.Init("{") assert.Error(t, err) // Fail if there is no filename @@ -47,9 +43,7 @@ func TestFileLoggerFails(t *testing.T) { } func TestFileLogger(t *testing.T) { - tmpDir, err := os.MkdirTemp("", "TestFileLogger") - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() prefix := "TestPrefix " level := INFO @@ -150,9 +144,7 @@ func TestFileLogger(t *testing.T) { } func TestCompressFileLogger(t *testing.T) { - tmpDir, err := os.MkdirTemp("", "TestFileLogger") - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() prefix := "TestPrefix " level := INFO @@ -210,9 +202,7 @@ func TestCompressFileLogger(t *testing.T) { } func TestCompressOldFile(t *testing.T) { - tmpDir, err := os.MkdirTemp("", "TestFileLogger") - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() fname := filepath.Join(tmpDir, "test") nonGzip := filepath.Join(tmpDir, "test-nonGzip") diff --git a/modules/queue/queue_disk_channel_test.go b/modules/queue/queue_disk_channel_test.go index 22b4f0f452..b1820e73ac 100644 --- a/modules/queue/queue_disk_channel_test.go +++ b/modules/queue/queue_disk_channel_test.go @@ -5,13 +5,11 @@ package queue import ( - "os" "sync" "testing" "time" "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" ) @@ -33,9 +31,7 @@ func TestPersistableChannelQueue(t *testing.T) { queueShutdown := []func(){} queueTerminate := []func(){} - tmpDir, err := os.MkdirTemp("", "persistable-channel-queue-test-data") - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() queue, err := NewPersistableChannelQueue(handle, PersistableChannelQueueConfiguration{ DataDir: tmpDir, @@ -223,9 +219,7 @@ func TestPersistableChannelQueue_Pause(t *testing.T) { queueTerminate := []func(){} terminated := make(chan struct{}) - tmpDir, err := os.MkdirTemp("", "persistable-channel-queue-pause-test-data") - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() queue, err = NewPersistableChannelQueue(handle, PersistableChannelQueueConfiguration{ DataDir: tmpDir, diff --git a/modules/queue/queue_disk_test.go b/modules/queue/queue_disk_test.go index d2d8e135cb..b0835c896f 100644 --- a/modules/queue/queue_disk_test.go +++ b/modules/queue/queue_disk_test.go @@ -5,13 +5,10 @@ package queue import ( - "os" "sync" "testing" "time" - "code.gitea.io/gitea/modules/util" - "github.com/stretchr/testify/assert" ) @@ -30,9 +27,7 @@ func TestLevelQueue(t *testing.T) { queueShutdown := []func(){} queueTerminate := []func(){} - tmpDir, err := os.MkdirTemp("", "level-queue-test-data") - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() queue, err := NewLevelQueue(handle, LevelQueueConfiguration{ ByteFIFOQueueConfiguration: ByteFIFOQueueConfiguration{ diff --git a/routers/web/repo/settings_test.go b/routers/web/repo/settings_test.go index 946220b4fc..4acd7df5b8 100644 --- a/routers/web/repo/settings_test.go +++ b/routers/web/repo/settings_test.go @@ -6,7 +6,6 @@ package repo import ( "net/http" - "os" "testing" "code.gitea.io/gitea/models" @@ -19,7 +18,6 @@ import ( "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/test" - "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/services/forms" @@ -27,18 +25,13 @@ import ( ) func createSSHAuthorizedKeysTmpPath(t *testing.T) func() { - tmpDir, err := os.MkdirTemp("", "tmp-ssh") - if err != nil { - assert.Fail(t, "Unable to create temporary directory: %v", err) - return nil - } + tmpDir := t.TempDir() oldPath := setting.SSH.RootPath setting.SSH.RootPath = tmpDir return func() { setting.SSH.RootPath = oldPath - util.RemoveAll(tmpDir) } } diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go index 938a7d6acd..cabeecb60a 100644 --- a/services/wiki/wiki_test.go +++ b/services/wiki/wiki_test.go @@ -5,7 +5,6 @@ package wiki import ( - "os" "path/filepath" "testing" @@ -13,7 +12,6 @@ import ( "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/git" - "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" ) @@ -273,15 +271,9 @@ func TestPrepareWikiFileName_FirstPage(t *testing.T) { unittest.PrepareTestEnv(t) // Now create a temporaryDirectory - tmpDir, err := os.MkdirTemp("", "empty-wiki") - assert.NoError(t, err) - defer func() { - if _, err := os.Stat(tmpDir); !os.IsNotExist(err) { - _ = util.RemoveAll(tmpDir) - } - }() + tmpDir := t.TempDir() - err = git.InitRepository(git.DefaultContext, tmpDir, true) + err := git.InitRepository(git.DefaultContext, tmpDir, true) assert.NoError(t, err) gitRepo, err := git.OpenRepository(git.DefaultContext, tmpDir) diff --git a/tests/integration/api_repo_file_get_test.go b/tests/integration/api_repo_file_get_test.go index 2a7a5fa634..cca72c2b3e 100644 --- a/tests/integration/api_repo_file_get_test.go +++ b/tests/integration/api_repo_file_get_test.go @@ -7,11 +7,9 @@ package integration import ( "net/http" "net/url" - "os" "testing" api "code.gitea.io/gitea/modules/structs" - "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" @@ -30,18 +28,14 @@ func TestAPIGetRawFileOrLFS(t *testing.T) { httpContext := NewAPITestContext(t, "user2", "repo-lfs-test") doAPICreateRepository(httpContext, false, func(t *testing.T, repository api.Repository) { u.Path = httpContext.GitPath() - dstPath, err := os.MkdirTemp("", httpContext.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath) + dstPath := t.TempDir() u.Path = httpContext.GitPath() u.User = url.UserPassword("user2", userPassword) t.Run("Clone", doGitClone(dstPath, u)) - dstPath2, err := os.MkdirTemp("", httpContext.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath2) + dstPath2 := t.TempDir() t.Run("Partial Clone", doPartialGitClone(dstPath2, u)) diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index 483503ccbb..bfe0c0aa9c 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -8,7 +8,6 @@ import ( "fmt" "net/http" "net/url" - "os" "testing" "code.gitea.io/gitea/models" @@ -19,7 +18,6 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" - "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" @@ -389,9 +387,6 @@ func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) { httpContext := baseAPITestContext httpContext.Reponame = "repo-tmp-17" - dstPath, err := os.MkdirTemp("", httpContext.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath) t.Run("CreateRepo", doAPICreateRepository(httpContext, false)) user, err := user_model.GetUserByName(db.DefaultContext, httpContext.Username) @@ -473,9 +468,6 @@ func testAPIRepoCreateConflict(t *testing.T, u *url.URL) { httpContext := baseAPITestContext httpContext.Reponame = "repo-tmp-17" - dstPath, err := os.MkdirTemp("", httpContext.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath) t.Run("CreateRepo", doAPICreateRepository(httpContext, false)) req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+httpContext.Token, diff --git a/tests/integration/create_no_session_test.go b/tests/integration/create_no_session_test.go index c9b90974d7..c617b1828a 100644 --- a/tests/integration/create_no_session_test.go +++ b/tests/integration/create_no_session_test.go @@ -14,7 +14,6 @@ import ( "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/routers" "code.gitea.io/gitea/tests" @@ -70,13 +69,7 @@ func TestSessionFileCreation(t *testing.T) { config.Provider = "file" // Now create a temporaryDirectory - tmpDir, err := os.MkdirTemp("", "sessions") - assert.NoError(t, err) - defer func() { - if _, err := os.Stat(tmpDir); !os.IsNotExist(err) { - _ = util.RemoveAll(tmpDir) - } - }() + tmpDir := t.TempDir() config.ProviderConfig = tmpDir newConfigBytes, err := json.Marshal(config) diff --git a/tests/integration/git_clone_wiki_test.go b/tests/integration/git_clone_wiki_test.go index 4bdbc9b7c3..3e10b17d40 100644 --- a/tests/integration/git_clone_wiki_test.go +++ b/tests/integration/git_clone_wiki_test.go @@ -35,8 +35,7 @@ func TestRepoCloneWiki(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { defer tests.PrepareTestEnv(t)() - dstPath, err := os.MkdirTemp("", "clone_wiki") - assert.NoError(t, err) + dstPath := t.TempDir() r := fmt.Sprintf("%suser2/repo1.wiki.git", u.String()) u, _ = url.Parse(r) diff --git a/tests/integration/git_helper_for_declarative_test.go b/tests/integration/git_helper_for_declarative_test.go index 666f9f6fe9..4f2e540883 100644 --- a/tests/integration/git_helper_for_declarative_test.go +++ b/tests/integration/git_helper_for_declarative_test.go @@ -27,11 +27,9 @@ import ( ) func withKeyFile(t *testing.T, keyname string, callback func(string)) { - tmpDir, err := os.MkdirTemp("", "key-file") - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() - err = os.Chmod(tmpDir, 0o700) + err := os.Chmod(tmpDir, 0o700) assert.NoError(t, err) keyFile := filepath.Join(tmpDir, keyname) @@ -120,9 +118,7 @@ func doPartialGitClone(dstLocalPath string, u *url.URL) func(*testing.T) { func doGitCloneFail(u *url.URL) func(*testing.T) { return func(t *testing.T) { - tmpDir, err := os.MkdirTemp("", "doGitCloneFail") - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() assert.Error(t, git.Clone(git.DefaultContext, u.String(), tmpDir, git.CloneRepoOptions{})) exist, err := util.IsExist(filepath.Join(tmpDir, "README.md")) assert.NoError(t, err) diff --git a/tests/integration/git_test.go b/tests/integration/git_test.go index caeb5db8b3..bf5e809dab 100644 --- a/tests/integration/git_test.go +++ b/tests/integration/git_test.go @@ -27,7 +27,6 @@ import ( "code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" - "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" @@ -57,9 +56,7 @@ func testGit(t *testing.T, u *url.URL) { httpContext.Reponame = "repo-tmp-17" forkedUserCtx.Reponame = httpContext.Reponame - dstPath, err := os.MkdirTemp("", httpContext.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath) + dstPath := t.TempDir() t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false)) t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, httpContext.Username, perm.AccessModeRead)) @@ -71,9 +68,7 @@ func testGit(t *testing.T, u *url.URL) { t.Run("Clone", doGitClone(dstPath, u)) - dstPath2, err := os.MkdirTemp("", httpContext.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath2) + dstPath2 := t.TempDir() t.Run("Partial Clone", doPartialGitClone(dstPath2, u)) @@ -114,9 +109,7 @@ func testGit(t *testing.T, u *url.URL) { sshURL := createSSHUrl(sshContext.GitPath(), u) // Setup clone folder - dstPath, err := os.MkdirTemp("", sshContext.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath) + dstPath := t.TempDir() t.Run("Clone", doGitClone(dstPath, sshURL)) @@ -140,9 +133,7 @@ func testGit(t *testing.T, u *url.URL) { } func ensureAnonymousClone(t *testing.T, u *url.URL) { - dstLocalPath, err := os.MkdirTemp("", "repo1") - assert.NoError(t, err) - defer util.RemoveAll(dstLocalPath) + dstLocalPath := t.TempDir() t.Run("CloneAnonymous", doGitClone(dstLocalPath, u)) } @@ -560,9 +551,7 @@ func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) { u.Path = ctx.GitPath() // Create a temporary directory - tmpDir, err := os.MkdirTemp("", ctx.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() // Now create local repository to push as our test and set its origin t.Run("InitTestRepository", doGitInitTestRepository(tmpDir)) diff --git a/tests/integration/gpg_git_test.go b/tests/integration/gpg_git_test.go index 2e16d150c8..80f484926d 100644 --- a/tests/integration/gpg_git_test.go +++ b/tests/integration/gpg_git_test.go @@ -16,7 +16,6 @@ import ( "code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" - "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" @@ -29,11 +28,9 @@ func TestGPGGit(t *testing.T) { username := "user2" // OK Set a new GPG home - tmpDir, err := os.MkdirTemp("", "temp-gpg") - assert.NoError(t, err) - defer util.RemoveAll(tmpDir) + tmpDir := t.TempDir() - err = os.Chmod(tmpDir, 0o700) + err := os.Chmod(tmpDir, 0o700) assert.NoError(t, err) oldGNUPGHome := os.Getenv("GNUPGHOME") diff --git a/tests/integration/lfs_local_endpoint_test.go b/tests/integration/lfs_local_endpoint_test.go index 88c08c63db..4042dc95b3 100644 --- a/tests/integration/lfs_local_endpoint_test.go +++ b/tests/integration/lfs_local_endpoint_test.go @@ -25,15 +25,12 @@ func str2url(raw string) *url.URL { func TestDetermineLocalEndpoint(t *testing.T) { defer tests.PrepareTestEnv(t)() - root, _ := os.MkdirTemp("", "lfs_test") - defer os.RemoveAll(root) + root := t.TempDir() - rootdotgit, _ := os.MkdirTemp("", "lfs_test") - defer os.RemoveAll(rootdotgit) + rootdotgit := t.TempDir() os.Mkdir(filepath.Join(rootdotgit, ".git"), 0o700) - lfsroot, _ := os.MkdirTemp("", "lfs_test") - defer os.RemoveAll(lfsroot) + lfsroot := t.TempDir() // Test cases cases := []struct { diff --git a/tests/integration/migrate_test.go b/tests/integration/migrate_test.go index 0fe4014344..99d5d6c8dd 100644 --- a/tests/integration/migrate_test.go +++ b/tests/integration/migrate_test.go @@ -9,6 +9,7 @@ import ( "net/http" "net/url" "os" + "path/filepath" "testing" repo_model "code.gitea.io/gitea/models/repo" @@ -29,16 +30,18 @@ func TestMigrateLocalPath(t *testing.T) { old := setting.ImportLocalPaths setting.ImportLocalPaths = true - lowercasePath, err := os.MkdirTemp("", "lowercase") // may not be lowercase because MkdirTemp creates a random directory name which may be mixedcase + basePath := t.TempDir() + + lowercasePath := filepath.Join(basePath, "lowercase") + err := os.Mkdir(lowercasePath, 0o700) assert.NoError(t, err) - defer os.RemoveAll(lowercasePath) err = migrations.IsMigrateURLAllowed(lowercasePath, adminUser) assert.NoError(t, err, "case lowercase path") - mixedcasePath, err := os.MkdirTemp("", "mIxeDCaSe") + mixedcasePath := filepath.Join(basePath, "mIxeDCaSe") + err = os.Mkdir(mixedcasePath, 0o700) assert.NoError(t, err) - defer os.RemoveAll(mixedcasePath) err = migrations.IsMigrateURLAllowed(mixedcasePath, adminUser) assert.NoError(t, err, "case mixedcase path") diff --git a/tests/integration/repo_tag_test.go b/tests/integration/repo_tag_test.go index a91f1fb209..fb08895e21 100644 --- a/tests/integration/repo_tag_test.go +++ b/tests/integration/repo_tag_test.go @@ -6,7 +6,6 @@ package integration import ( "net/url" - "os" "testing" "code.gitea.io/gitea/models" @@ -15,7 +14,6 @@ import ( "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/git" - "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/services/release" "code.gitea.io/gitea/tests" @@ -59,16 +57,14 @@ func TestCreateNewTagProtected(t *testing.T) { username := "user2" httpContext := NewAPITestContext(t, username, "repo1") - dstPath, err := os.MkdirTemp("", httpContext.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath) + dstPath := t.TempDir() u.Path = httpContext.GitPath() u.User = url.UserPassword(username, userPassword) doGitClone(dstPath, u)(t) - _, _, err = git.NewCommand(git.DefaultContext, "tag", "v-2").RunStdString(&git.RunOpts{Dir: dstPath}) + _, _, err := git.NewCommand(git.DefaultContext, "tag", "v-2").RunStdString(&git.RunOpts{Dir: dstPath}) assert.NoError(t, err) _, _, err = git.NewCommand(git.DefaultContext, "push", "--tags").RunStdString(&git.RunOpts{Dir: dstPath}) diff --git a/tests/integration/ssh_key_test.go b/tests/integration/ssh_key_test.go index 65d9b84404..fd98af5125 100644 --- a/tests/integration/ssh_key_test.go +++ b/tests/integration/ssh_key_test.go @@ -15,7 +15,6 @@ import ( "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" - "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" ) @@ -61,9 +60,7 @@ func testPushDeployKeyOnEmptyRepo(t *testing.T, u *url.URL) { t.Run("CreatePushDeployKey", doAPICreateDeployKey(ctx, keyname, keyFile, false)) // Setup the testing repository - dstPath, err := os.MkdirTemp("", "repo-tmp-deploy-key-empty-repo-1") - assert.NoError(t, err) - defer util.RemoveAll(dstPath) + dstPath := t.TempDir() t.Run("InitTestRepository", doGitInitTestRepository(dstPath)) @@ -107,9 +104,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) { withKeyFile(t, keyname, func(keyFile string) { var userKeyPublicKeyID int64 t.Run("KeyCanOnlyBeUser", func(t *testing.T) { - dstPath, err := os.MkdirTemp("", ctx.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath) + dstPath := t.TempDir() sshURL := createSSHUrl(ctx.GitPath(), u) @@ -133,9 +128,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) { }) t.Run("KeyCanBeAnyDeployButNotUserAswell", func(t *testing.T) { - dstPath, err := os.MkdirTemp("", ctx.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath) + dstPath := t.TempDir() sshURL := createSSHUrl(ctx.GitPath(), u) @@ -151,9 +144,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) { t.Run("FailToPush", doGitPushTestRepositoryFail(dstPath, "origin", "master")) otherSSHURL := createSSHUrl(otherCtx.GitPath(), u) - dstOtherPath, err := os.MkdirTemp("", otherCtx.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstOtherPath) + dstOtherPath := t.TempDir() t.Run("AddWriterDeployKeyToOther", doAPICreateDeployKey(otherCtx, keyname, keyFile, false)) @@ -168,9 +159,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) { t.Run("DeleteRepositoryShouldReleaseKey", func(t *testing.T) { otherSSHURL := createSSHUrl(otherCtx.GitPath(), u) - dstOtherPath, err := os.MkdirTemp("", otherCtx.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstOtherPath) + dstOtherPath := t.TempDir() t.Run("DeleteRepository", doAPIDeleteRepository(ctx)) @@ -190,9 +179,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) { userKeyPublicKeyID = publicKey.ID })) - dstPath, err := os.MkdirTemp("", ctx.Reponame) - assert.NoError(t, err) - defer util.RemoveAll(dstPath) + dstPath := t.TempDir() sshURL := createSSHUrl(ctx.GitPath(), u)