forked from gitea/gitea
1
0
Fork 0

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 <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun 2022-09-04 23:14:53 +08:00 committed by GitHub
parent c722a26e7e
commit 8b0aaa5f86
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
24 changed files with 57 additions and 194 deletions

View File

@ -53,8 +53,7 @@ func TestMigratePackages(t *testing.T) {
ctx := context.Background() ctx := context.Background()
p, err := os.MkdirTemp(os.TempDir(), "migrated_packages") p := t.TempDir()
assert.NoError(t, err)
dstStorage, err := storage.NewLocalStorage( dstStorage, err := storage.NewLocalStorage(
ctx, ctx,

View File

@ -5,7 +5,6 @@
package db_test package db_test
import ( import (
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -20,8 +19,7 @@ import (
func TestDumpDatabase(t *testing.T) { func TestDumpDatabase(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
dir, err := os.MkdirTemp(os.TempDir(), "dump") dir := t.TempDir()
assert.NoError(t, err)
type Version struct { type Version struct {
ID int64 `xorm:"pk autoincr"` ID int64 `xorm:"pk autoincr"`

View File

@ -6,13 +6,10 @@ package git
import ( import (
"context" "context"
"os"
"path/filepath" "path/filepath"
"testing" "testing"
"time" "time"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -20,18 +17,14 @@ const (
testReposDir = "tests/repos/" testReposDir = "tests/repos/"
) )
func cloneRepo(url, name string) (string, error) { func cloneRepo(tb testing.TB, url string) (string, error) {
repoDir, err := os.MkdirTemp("", name) repoDir := tb.TempDir()
if err != nil {
return "", err
}
if err := Clone(DefaultContext, url, repoDir, CloneRepoOptions{ if err := Clone(DefaultContext, url, repoDir, CloneRepoOptions{
Mirror: false, Mirror: false,
Bare: false, Bare: false,
Quiet: true, Quiet: true,
Timeout: 5 * time.Minute, Timeout: 5 * time.Minute,
}); err != nil { }); err != nil {
_ = util.RemoveAll(repoDir)
return "", err return "", err
} }
return repoDir, nil return repoDir, nil
@ -118,11 +111,10 @@ func TestEntries_GetCommitsInfo(t *testing.T) {
testGetCommitsInfo(t, bareRepo1) testGetCommitsInfo(t, bareRepo1)
clonedPath, err := cloneRepo(bareRepo1Path, "repo1_TestEntries_GetCommitsInfo") clonedPath, err := cloneRepo(t, bareRepo1Path)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
} }
defer util.RemoveAll(clonedPath)
clonedRepo1, err := openRepositoryWithDefaultContext(clonedPath) clonedRepo1, err := openRepositoryWithDefaultContext(clonedPath)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
@ -150,11 +142,10 @@ func BenchmarkEntries_GetCommitsInfo(b *testing.B) {
var commit *Commit var commit *Commit
var entries Entries var entries Entries
var repo *Repository var repo *Repository
repoPath, err := cloneRepo(benchmark.url, benchmark.name) repoPath, err := cloneRepo(b, benchmark.url)
if err != nil { if err != nil {
b.Fatal(err) b.Fatal(err)
} }
defer util.RemoveAll(repoPath)
if repo, err = openRepositoryWithDefaultContext(repoPath); err != nil { if repo, err = openRepositoryWithDefaultContext(repoPath); err != nil {
b.Fatal(err) b.Fatal(err)

View File

@ -10,19 +10,16 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestGetFormatPatch(t *testing.T) { func TestGetFormatPatch(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
clonedPath, err := cloneRepo(bareRepo1Path, "repo1_TestGetFormatPatch") clonedPath, err := cloneRepo(t, bareRepo1Path)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
} }
defer util.RemoveAll(clonedPath)
repo, err := openRepositoryWithDefaultContext(clonedPath) repo, err := openRepositoryWithDefaultContext(clonedPath)
if err != nil { if err != nil {
@ -84,12 +81,11 @@ func TestReadWritePullHead(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
// As we are writing we should clone the repository first // As we are writing we should clone the repository first
clonedPath, err := cloneRepo(bareRepo1Path, "TestReadWritePullHead") clonedPath, err := cloneRepo(t, bareRepo1Path)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
} }
defer util.RemoveAll(clonedPath)
repo, err := openRepositoryWithDefaultContext(clonedPath) repo, err := openRepositoryWithDefaultContext(clonedPath)
if err != nil { if err != nil {

View File

@ -8,8 +8,6 @@ import (
"path/filepath" "path/filepath"
"testing" "testing"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -38,12 +36,11 @@ func TestRepository_GetTags(t *testing.T) {
func TestRepository_GetTag(t *testing.T) { func TestRepository_GetTag(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
clonedPath, err := cloneRepo(bareRepo1Path, "TestRepository_GetTag") clonedPath, err := cloneRepo(t, bareRepo1Path)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
} }
defer util.RemoveAll(clonedPath)
bareRepo1, err := openRepositoryWithDefaultContext(clonedPath) bareRepo1, err := openRepositoryWithDefaultContext(clonedPath)
if err != nil { if err != nil {
@ -143,12 +140,11 @@ func TestRepository_GetTag(t *testing.T) {
func TestRepository_GetAnnotatedTag(t *testing.T) { func TestRepository_GetAnnotatedTag(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
clonedPath, err := cloneRepo(bareRepo1Path, "TestRepository_GetAnnotatedTag") clonedPath, err := cloneRepo(t, bareRepo1Path)
if err != nil { if err != nil {
assert.NoError(t, err) assert.NoError(t, err)
return return
} }
defer util.RemoveAll(clonedPath)
bareRepo1, err := openRepositoryWithDefaultContext(clonedPath) bareRepo1, err := openRepositoryWithDefaultContext(clonedPath)
if err != nil { if err != nil {

View File

@ -5,11 +5,9 @@
package code package code
import ( import (
"os"
"testing" "testing"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -17,13 +15,7 @@ import (
func TestBleveIndexAndSearch(t *testing.T) { func TestBleveIndexAndSearch(t *testing.T) {
unittest.PrepareTestEnv(t) unittest.PrepareTestEnv(t)
dir, err := os.MkdirTemp("", "bleve.index") dir := t.TempDir()
assert.NoError(t, err)
if err != nil {
assert.Fail(t, "Unable to create temporary directory")
return
}
defer util.RemoveAll(dir)
idx, _, err := NewBleveIndexer(dir) idx, _, err := NewBleveIndexer(dir)
if err != nil { if err != nil {

View File

@ -6,22 +6,13 @@ package issues
import ( import (
"context" "context"
"os"
"testing" "testing"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestBleveIndexAndSearch(t *testing.T) { func TestBleveIndexAndSearch(t *testing.T) {
dir, err := os.MkdirTemp("", "bleve.index") dir := t.TempDir()
assert.NoError(t, err)
if err != nil {
assert.Fail(t, "Unable to create temporary directory")
return
}
defer util.RemoveAll(dir)
indexer := NewBleveIndexer(dir) indexer := NewBleveIndexer(dir)
defer indexer.Close() defer indexer.Close()
@ -30,7 +21,7 @@ func TestBleveIndexAndSearch(t *testing.T) {
return return
} }
err = indexer.Index([]*IndexerData{ err := indexer.Index([]*IndexerData{
{ {
ID: 1, ID: 1,
RepoID: 2, RepoID: 2,

View File

@ -6,7 +6,6 @@ package issues
import ( import (
"context" "context"
"os"
"path" "path"
"path/filepath" "path/filepath"
"testing" "testing"
@ -14,7 +13,6 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
_ "code.gitea.io/gitea/models" _ "code.gitea.io/gitea/models"
@ -32,11 +30,7 @@ func TestBleveSearchIssues(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, unittest.PrepareTestDatabase())
setting.Cfg = ini.Empty() setting.Cfg = ini.Empty()
tmpIndexerDir, err := os.MkdirTemp("", "issues-indexer") tmpIndexerDir := t.TempDir()
if err != nil {
assert.Fail(t, "Unable to create temporary directory: %v", err)
return
}
setting.Cfg.Section("queue.issue_indexer").Key("DATADIR").MustString(path.Join(tmpIndexerDir, "issues.queue")) 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") setting.Indexer.IssuePath = path.Join(tmpIndexerDir, "issues.queue")
defer func() { defer func() {
setting.Indexer.IssuePath = oldIssuePath setting.Indexer.IssuePath = oldIssuePath
util.RemoveAll(tmpIndexerDir)
}() }()
setting.Indexer.IssueType = "bleve" setting.Indexer.IssueType = "bleve"

View File

@ -14,15 +14,11 @@ import (
"testing" "testing"
"time" "time"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
func TestFileLoggerFails(t *testing.T) { func TestFileLoggerFails(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "TestFileLogger") tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
prefix := "TestPrefix " prefix := "TestPrefix "
level := INFO level := INFO
@ -34,7 +30,7 @@ func TestFileLoggerFails(t *testing.T) {
// assert.True(t, ok) // assert.True(t, ok)
// Fail if there is bad json // Fail if there is bad json
err = fileLogger.Init("{") err := fileLogger.Init("{")
assert.Error(t, err) assert.Error(t, err)
// Fail if there is no filename // Fail if there is no filename
@ -47,9 +43,7 @@ func TestFileLoggerFails(t *testing.T) {
} }
func TestFileLogger(t *testing.T) { func TestFileLogger(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "TestFileLogger") tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
prefix := "TestPrefix " prefix := "TestPrefix "
level := INFO level := INFO
@ -150,9 +144,7 @@ func TestFileLogger(t *testing.T) {
} }
func TestCompressFileLogger(t *testing.T) { func TestCompressFileLogger(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "TestFileLogger") tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
prefix := "TestPrefix " prefix := "TestPrefix "
level := INFO level := INFO
@ -210,9 +202,7 @@ func TestCompressFileLogger(t *testing.T) {
} }
func TestCompressOldFile(t *testing.T) { func TestCompressOldFile(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "TestFileLogger") tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
fname := filepath.Join(tmpDir, "test") fname := filepath.Join(tmpDir, "test")
nonGzip := filepath.Join(tmpDir, "test-nonGzip") nonGzip := filepath.Join(tmpDir, "test-nonGzip")

View File

@ -5,13 +5,11 @@
package queue package queue
import ( import (
"os"
"sync" "sync"
"testing" "testing"
"time" "time"
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -33,9 +31,7 @@ func TestPersistableChannelQueue(t *testing.T) {
queueShutdown := []func(){} queueShutdown := []func(){}
queueTerminate := []func(){} queueTerminate := []func(){}
tmpDir, err := os.MkdirTemp("", "persistable-channel-queue-test-data") tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
queue, err := NewPersistableChannelQueue(handle, PersistableChannelQueueConfiguration{ queue, err := NewPersistableChannelQueue(handle, PersistableChannelQueueConfiguration{
DataDir: tmpDir, DataDir: tmpDir,
@ -223,9 +219,7 @@ func TestPersistableChannelQueue_Pause(t *testing.T) {
queueTerminate := []func(){} queueTerminate := []func(){}
terminated := make(chan struct{}) terminated := make(chan struct{})
tmpDir, err := os.MkdirTemp("", "persistable-channel-queue-pause-test-data") tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
queue, err = NewPersistableChannelQueue(handle, PersistableChannelQueueConfiguration{ queue, err = NewPersistableChannelQueue(handle, PersistableChannelQueueConfiguration{
DataDir: tmpDir, DataDir: tmpDir,

View File

@ -5,13 +5,10 @@
package queue package queue
import ( import (
"os"
"sync" "sync"
"testing" "testing"
"time" "time"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -30,9 +27,7 @@ func TestLevelQueue(t *testing.T) {
queueShutdown := []func(){} queueShutdown := []func(){}
queueTerminate := []func(){} queueTerminate := []func(){}
tmpDir, err := os.MkdirTemp("", "level-queue-test-data") tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
queue, err := NewLevelQueue(handle, LevelQueueConfiguration{ queue, err := NewLevelQueue(handle, LevelQueueConfiguration{
ByteFIFOQueueConfiguration: ByteFIFOQueueConfiguration{ ByteFIFOQueueConfiguration: ByteFIFOQueueConfiguration{

View File

@ -6,7 +6,6 @@ package repo
import ( import (
"net/http" "net/http"
"os"
"testing" "testing"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -19,7 +18,6 @@ import (
"code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/services/forms" "code.gitea.io/gitea/services/forms"
@ -27,18 +25,13 @@ import (
) )
func createSSHAuthorizedKeysTmpPath(t *testing.T) func() { func createSSHAuthorizedKeysTmpPath(t *testing.T) func() {
tmpDir, err := os.MkdirTemp("", "tmp-ssh") tmpDir := t.TempDir()
if err != nil {
assert.Fail(t, "Unable to create temporary directory: %v", err)
return nil
}
oldPath := setting.SSH.RootPath oldPath := setting.SSH.RootPath
setting.SSH.RootPath = tmpDir setting.SSH.RootPath = tmpDir
return func() { return func() {
setting.SSH.RootPath = oldPath setting.SSH.RootPath = oldPath
util.RemoveAll(tmpDir)
} }
} }

View File

@ -5,7 +5,6 @@
package wiki package wiki
import ( import (
"os"
"path/filepath" "path/filepath"
"testing" "testing"
@ -13,7 +12,6 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -273,15 +271,9 @@ func TestPrepareWikiFileName_FirstPage(t *testing.T) {
unittest.PrepareTestEnv(t) unittest.PrepareTestEnv(t)
// Now create a temporaryDirectory // Now create a temporaryDirectory
tmpDir, err := os.MkdirTemp("", "empty-wiki") tmpDir := t.TempDir()
assert.NoError(t, err)
defer func() {
if _, err := os.Stat(tmpDir); !os.IsNotExist(err) {
_ = util.RemoveAll(tmpDir)
}
}()
err = git.InitRepository(git.DefaultContext, tmpDir, true) err := git.InitRepository(git.DefaultContext, tmpDir, true)
assert.NoError(t, err) assert.NoError(t, err)
gitRepo, err := git.OpenRepository(git.DefaultContext, tmpDir) gitRepo, err := git.OpenRepository(git.DefaultContext, tmpDir)

View File

@ -7,11 +7,9 @@ package integration
import ( import (
"net/http" "net/http"
"net/url" "net/url"
"os"
"testing" "testing"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/tests" "code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -30,18 +28,14 @@ func TestAPIGetRawFileOrLFS(t *testing.T) {
httpContext := NewAPITestContext(t, "user2", "repo-lfs-test") httpContext := NewAPITestContext(t, "user2", "repo-lfs-test")
doAPICreateRepository(httpContext, false, func(t *testing.T, repository api.Repository) { doAPICreateRepository(httpContext, false, func(t *testing.T, repository api.Repository) {
u.Path = httpContext.GitPath() u.Path = httpContext.GitPath()
dstPath, err := os.MkdirTemp("", httpContext.Reponame) dstPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstPath)
u.Path = httpContext.GitPath() u.Path = httpContext.GitPath()
u.User = url.UserPassword("user2", userPassword) u.User = url.UserPassword("user2", userPassword)
t.Run("Clone", doGitClone(dstPath, u)) t.Run("Clone", doGitClone(dstPath, u))
dstPath2, err := os.MkdirTemp("", httpContext.Reponame) dstPath2 := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstPath2)
t.Run("Partial Clone", doPartialGitClone(dstPath2, u)) t.Run("Partial Clone", doPartialGitClone(dstPath2, u))

View File

@ -8,7 +8,6 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
"os"
"testing" "testing"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -19,7 +18,6 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/tests" "code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -389,9 +387,6 @@ func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) {
httpContext := baseAPITestContext httpContext := baseAPITestContext
httpContext.Reponame = "repo-tmp-17" 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)) t.Run("CreateRepo", doAPICreateRepository(httpContext, false))
user, err := user_model.GetUserByName(db.DefaultContext, httpContext.Username) user, err := user_model.GetUserByName(db.DefaultContext, httpContext.Username)
@ -473,9 +468,6 @@ func testAPIRepoCreateConflict(t *testing.T, u *url.URL) {
httpContext := baseAPITestContext httpContext := baseAPITestContext
httpContext.Reponame = "repo-tmp-17" 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)) t.Run("CreateRepo", doAPICreateRepository(httpContext, false))
req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+httpContext.Token, req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos?token="+httpContext.Token,

View File

@ -14,7 +14,6 @@ import (
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/routers" "code.gitea.io/gitea/routers"
"code.gitea.io/gitea/tests" "code.gitea.io/gitea/tests"
@ -70,13 +69,7 @@ func TestSessionFileCreation(t *testing.T) {
config.Provider = "file" config.Provider = "file"
// Now create a temporaryDirectory // Now create a temporaryDirectory
tmpDir, err := os.MkdirTemp("", "sessions") tmpDir := t.TempDir()
assert.NoError(t, err)
defer func() {
if _, err := os.Stat(tmpDir); !os.IsNotExist(err) {
_ = util.RemoveAll(tmpDir)
}
}()
config.ProviderConfig = tmpDir config.ProviderConfig = tmpDir
newConfigBytes, err := json.Marshal(config) newConfigBytes, err := json.Marshal(config)

View File

@ -35,8 +35,7 @@ func TestRepoCloneWiki(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) { onGiteaRun(t, func(t *testing.T, u *url.URL) {
defer tests.PrepareTestEnv(t)() defer tests.PrepareTestEnv(t)()
dstPath, err := os.MkdirTemp("", "clone_wiki") dstPath := t.TempDir()
assert.NoError(t, err)
r := fmt.Sprintf("%suser2/repo1.wiki.git", u.String()) r := fmt.Sprintf("%suser2/repo1.wiki.git", u.String())
u, _ = url.Parse(r) u, _ = url.Parse(r)

View File

@ -27,11 +27,9 @@ import (
) )
func withKeyFile(t *testing.T, keyname string, callback func(string)) { func withKeyFile(t *testing.T, keyname string, callback func(string)) {
tmpDir, err := os.MkdirTemp("", "key-file") tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
err = os.Chmod(tmpDir, 0o700) err := os.Chmod(tmpDir, 0o700)
assert.NoError(t, err) assert.NoError(t, err)
keyFile := filepath.Join(tmpDir, keyname) 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) { func doGitCloneFail(u *url.URL) func(*testing.T) {
return func(t *testing.T) { return func(t *testing.T) {
tmpDir, err := os.MkdirTemp("", "doGitCloneFail") tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
assert.Error(t, git.Clone(git.DefaultContext, u.String(), tmpDir, git.CloneRepoOptions{})) assert.Error(t, git.Clone(git.DefaultContext, u.String(), tmpDir, git.CloneRepoOptions{}))
exist, err := util.IsExist(filepath.Join(tmpDir, "README.md")) exist, err := util.IsExist(filepath.Join(tmpDir, "README.md"))
assert.NoError(t, err) assert.NoError(t, err)

View File

@ -27,7 +27,6 @@ import (
"code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/tests" "code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -57,9 +56,7 @@ func testGit(t *testing.T, u *url.URL) {
httpContext.Reponame = "repo-tmp-17" httpContext.Reponame = "repo-tmp-17"
forkedUserCtx.Reponame = httpContext.Reponame forkedUserCtx.Reponame = httpContext.Reponame
dstPath, err := os.MkdirTemp("", httpContext.Reponame) dstPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstPath)
t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false)) t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false))
t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, httpContext.Username, perm.AccessModeRead)) 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)) t.Run("Clone", doGitClone(dstPath, u))
dstPath2, err := os.MkdirTemp("", httpContext.Reponame) dstPath2 := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstPath2)
t.Run("Partial Clone", doPartialGitClone(dstPath2, u)) t.Run("Partial Clone", doPartialGitClone(dstPath2, u))
@ -114,9 +109,7 @@ func testGit(t *testing.T, u *url.URL) {
sshURL := createSSHUrl(sshContext.GitPath(), u) sshURL := createSSHUrl(sshContext.GitPath(), u)
// Setup clone folder // Setup clone folder
dstPath, err := os.MkdirTemp("", sshContext.Reponame) dstPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstPath)
t.Run("Clone", doGitClone(dstPath, sshURL)) 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) { func ensureAnonymousClone(t *testing.T, u *url.URL) {
dstLocalPath, err := os.MkdirTemp("", "repo1") dstLocalPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstLocalPath)
t.Run("CloneAnonymous", doGitClone(dstLocalPath, u)) 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() u.Path = ctx.GitPath()
// Create a temporary directory // Create a temporary directory
tmpDir, err := os.MkdirTemp("", ctx.Reponame) tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
// Now create local repository to push as our test and set its origin // Now create local repository to push as our test and set its origin
t.Run("InitTestRepository", doGitInitTestRepository(tmpDir)) t.Run("InitTestRepository", doGitInitTestRepository(tmpDir))

View File

@ -16,7 +16,6 @@ import (
"code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/process"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/tests" "code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -29,11 +28,9 @@ func TestGPGGit(t *testing.T) {
username := "user2" username := "user2"
// OK Set a new GPG home // OK Set a new GPG home
tmpDir, err := os.MkdirTemp("", "temp-gpg") tmpDir := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(tmpDir)
err = os.Chmod(tmpDir, 0o700) err := os.Chmod(tmpDir, 0o700)
assert.NoError(t, err) assert.NoError(t, err)
oldGNUPGHome := os.Getenv("GNUPGHOME") oldGNUPGHome := os.Getenv("GNUPGHOME")

View File

@ -25,15 +25,12 @@ func str2url(raw string) *url.URL {
func TestDetermineLocalEndpoint(t *testing.T) { func TestDetermineLocalEndpoint(t *testing.T) {
defer tests.PrepareTestEnv(t)() defer tests.PrepareTestEnv(t)()
root, _ := os.MkdirTemp("", "lfs_test") root := t.TempDir()
defer os.RemoveAll(root)
rootdotgit, _ := os.MkdirTemp("", "lfs_test") rootdotgit := t.TempDir()
defer os.RemoveAll(rootdotgit)
os.Mkdir(filepath.Join(rootdotgit, ".git"), 0o700) os.Mkdir(filepath.Join(rootdotgit, ".git"), 0o700)
lfsroot, _ := os.MkdirTemp("", "lfs_test") lfsroot := t.TempDir()
defer os.RemoveAll(lfsroot)
// Test cases // Test cases
cases := []struct { cases := []struct {

View File

@ -9,6 +9,7 @@ import (
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"path/filepath"
"testing" "testing"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
@ -29,16 +30,18 @@ func TestMigrateLocalPath(t *testing.T) {
old := setting.ImportLocalPaths old := setting.ImportLocalPaths
setting.ImportLocalPaths = true 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) assert.NoError(t, err)
defer os.RemoveAll(lowercasePath)
err = migrations.IsMigrateURLAllowed(lowercasePath, adminUser) err = migrations.IsMigrateURLAllowed(lowercasePath, adminUser)
assert.NoError(t, err, "case lowercase path") 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) assert.NoError(t, err)
defer os.RemoveAll(mixedcasePath)
err = migrations.IsMigrateURLAllowed(mixedcasePath, adminUser) err = migrations.IsMigrateURLAllowed(mixedcasePath, adminUser)
assert.NoError(t, err, "case mixedcase path") assert.NoError(t, err, "case mixedcase path")

View File

@ -6,7 +6,6 @@ package integration
import ( import (
"net/url" "net/url"
"os"
"testing" "testing"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
@ -15,7 +14,6 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/services/release" "code.gitea.io/gitea/services/release"
"code.gitea.io/gitea/tests" "code.gitea.io/gitea/tests"
@ -59,16 +57,14 @@ func TestCreateNewTagProtected(t *testing.T) {
username := "user2" username := "user2"
httpContext := NewAPITestContext(t, username, "repo1") httpContext := NewAPITestContext(t, username, "repo1")
dstPath, err := os.MkdirTemp("", httpContext.Reponame) dstPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstPath)
u.Path = httpContext.GitPath() u.Path = httpContext.GitPath()
u.User = url.UserPassword(username, userPassword) u.User = url.UserPassword(username, userPassword)
doGitClone(dstPath, u)(t) 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) assert.NoError(t, err)
_, _, err = git.NewCommand(git.DefaultContext, "push", "--tags").RunStdString(&git.RunOpts{Dir: dstPath}) _, _, err = git.NewCommand(git.DefaultContext, "push", "--tags").RunStdString(&git.RunOpts{Dir: dstPath})

View File

@ -15,7 +15,6 @@ import (
"code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/git"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "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)) t.Run("CreatePushDeployKey", doAPICreateDeployKey(ctx, keyname, keyFile, false))
// Setup the testing repository // Setup the testing repository
dstPath, err := os.MkdirTemp("", "repo-tmp-deploy-key-empty-repo-1") dstPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstPath)
t.Run("InitTestRepository", doGitInitTestRepository(dstPath)) t.Run("InitTestRepository", doGitInitTestRepository(dstPath))
@ -107,9 +104,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) {
withKeyFile(t, keyname, func(keyFile string) { withKeyFile(t, keyname, func(keyFile string) {
var userKeyPublicKeyID int64 var userKeyPublicKeyID int64
t.Run("KeyCanOnlyBeUser", func(t *testing.T) { t.Run("KeyCanOnlyBeUser", func(t *testing.T) {
dstPath, err := os.MkdirTemp("", ctx.Reponame) dstPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstPath)
sshURL := createSSHUrl(ctx.GitPath(), u) sshURL := createSSHUrl(ctx.GitPath(), u)
@ -133,9 +128,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) {
}) })
t.Run("KeyCanBeAnyDeployButNotUserAswell", func(t *testing.T) { t.Run("KeyCanBeAnyDeployButNotUserAswell", func(t *testing.T) {
dstPath, err := os.MkdirTemp("", ctx.Reponame) dstPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstPath)
sshURL := createSSHUrl(ctx.GitPath(), u) sshURL := createSSHUrl(ctx.GitPath(), u)
@ -151,9 +144,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) {
t.Run("FailToPush", doGitPushTestRepositoryFail(dstPath, "origin", "master")) t.Run("FailToPush", doGitPushTestRepositoryFail(dstPath, "origin", "master"))
otherSSHURL := createSSHUrl(otherCtx.GitPath(), u) otherSSHURL := createSSHUrl(otherCtx.GitPath(), u)
dstOtherPath, err := os.MkdirTemp("", otherCtx.Reponame) dstOtherPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstOtherPath)
t.Run("AddWriterDeployKeyToOther", doAPICreateDeployKey(otherCtx, keyname, keyFile, false)) 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) { t.Run("DeleteRepositoryShouldReleaseKey", func(t *testing.T) {
otherSSHURL := createSSHUrl(otherCtx.GitPath(), u) otherSSHURL := createSSHUrl(otherCtx.GitPath(), u)
dstOtherPath, err := os.MkdirTemp("", otherCtx.Reponame) dstOtherPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstOtherPath)
t.Run("DeleteRepository", doAPIDeleteRepository(ctx)) t.Run("DeleteRepository", doAPIDeleteRepository(ctx))
@ -190,9 +179,7 @@ func testKeyOnlyOneType(t *testing.T, u *url.URL) {
userKeyPublicKeyID = publicKey.ID userKeyPublicKeyID = publicKey.ID
})) }))
dstPath, err := os.MkdirTemp("", ctx.Reponame) dstPath := t.TempDir()
assert.NoError(t, err)
defer util.RemoveAll(dstPath)
sshURL := createSSHUrl(ctx.GitPath(), u) sshURL := createSSHUrl(ctx.GitPath(), u)