2
2
mirror of https://github.com/octoleo/restic.git synced 2024-11-21 20:35:12 +00:00

test: Use testing.T.Cleanup to remove tempdirs

This commit is contained in:
greatroar 2022-12-09 13:42:33 +01:00
parent eae7366563
commit f90bf84ba7
31 changed files with 79 additions and 176 deletions

View File

@ -14,8 +14,7 @@ import (
) )
func TestCollectTargets(t *testing.T) { func TestCollectTargets(t *testing.T) {
dir, cleanup := rtest.TempDir(t) dir := rtest.TempDir(t)
defer cleanup()
fooSpace := "foo " fooSpace := "foo "
barStar := "bar*" // Must sort before the others, below. barStar := "bar*" // Must sort before the others, below.

View File

@ -84,8 +84,7 @@ func TestIsExcludedByFile(t *testing.T) {
} }
for _, tc := range tests { for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) { t.Run(tc.name, func(t *testing.T) {
tempDir, cleanup := test.TempDir(t) tempDir := test.TempDir(t)
defer cleanup()
foo := filepath.Join(tempDir, "foo") foo := filepath.Join(tempDir, "foo")
err := os.WriteFile(foo, []byte("foo"), 0666) err := os.WriteFile(foo, []byte("foo"), 0666)
@ -115,8 +114,7 @@ func TestIsExcludedByFile(t *testing.T) {
// cancel each other out. It was initially written to demonstrate a bug in // cancel each other out. It was initially written to demonstrate a bug in
// rejectIfPresent. // rejectIfPresent.
func TestMultipleIsExcludedByFile(t *testing.T) { func TestMultipleIsExcludedByFile(t *testing.T) {
tempDir, cleanup := test.TempDir(t) tempDir := test.TempDir(t)
defer cleanup()
// Create some files in a temporary directory. // Create some files in a temporary directory.
// Files in UPPERCASE will be used as exclusion triggers later on. // Files in UPPERCASE will be used as exclusion triggers later on.
@ -240,8 +238,7 @@ func TestParseInvalidSizeStr(t *testing.T) {
// TestIsExcludedByFileSize is for testing the instance of // TestIsExcludedByFileSize is for testing the instance of
// --exclude-larger-than parameters // --exclude-larger-than parameters
func TestIsExcludedByFileSize(t *testing.T) { func TestIsExcludedByFileSize(t *testing.T) {
tempDir, cleanup := test.TempDir(t) tempDir := test.TempDir(t)
defer cleanup()
// Max size of file is set to be 1k // Max size of file is set to be 1k
maxSizeStr := "1k" maxSizeStr := "1k"

View File

@ -31,8 +31,7 @@ func Test_PrintFunctionsRespectsGlobalStdout(t *testing.T) {
} }
func TestReadRepo(t *testing.T) { func TestReadRepo(t *testing.T) {
tempDir, cleanup := test.TempDir(t) tempDir := test.TempDir(t)
defer cleanup()
// test --repo option // test --repo option
var opts GlobalOptions var opts GlobalOptions

View File

@ -160,10 +160,8 @@ func TestFillSecondaryGlobalOpts(t *testing.T) {
} }
//Create temp dir to create password file. //Create temp dir to create password file.
dir, cleanup := rtest.TempDir(t) dir := rtest.TempDir(t)
defer cleanup() cleanup := rtest.Chdir(t, dir)
cleanup = rtest.Chdir(t, dir)
defer cleanup() defer cleanup()
//Create temporary password file //Create temporary password file

View File

@ -26,17 +26,12 @@ import (
) )
func prepareTempdirRepoSrc(t testing.TB, src TestDir) (tempdir string, repo restic.Repository, cleanup func()) { func prepareTempdirRepoSrc(t testing.TB, src TestDir) (tempdir string, repo restic.Repository, cleanup func()) {
tempdir, removeTempdir := restictest.TempDir(t) tempdir = restictest.TempDir(t)
repo, removeRepository := repository.TestRepository(t) repo, removeRepository := repository.TestRepository(t)
TestCreateFiles(t, tempdir, src) TestCreateFiles(t, tempdir, src)
cleanup = func() { return tempdir, repo, removeRepository
removeRepository()
removeTempdir()
}
return tempdir, repo, cleanup
} }
func saveFile(t testing.TB, repo restic.Repository, filename string, filesystem fs.FS) (*restic.Node, ItemStats) { func saveFile(t testing.TB, repo restic.Repository, filename string, filesystem fs.FS) (*restic.Node, ItemStats) {
@ -470,8 +465,7 @@ func appendToFile(t testing.TB, filename string, data []byte) {
} }
func TestArchiverSaveFileIncremental(t *testing.T) { func TestArchiverSaveFileIncremental(t *testing.T) {
tempdir, removeTempdir := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer removeTempdir()
testRepo, removeRepository := repository.TestRepository(t) testRepo, removeRepository := repository.TestRepository(t)
defer removeRepository() defer removeRepository()
@ -688,8 +682,7 @@ func TestFileChanged(t *testing.T) {
t.Skip("don't run test on Windows") t.Skip("don't run test on Windows")
} }
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
filename := filepath.Join(tempdir, "file") filename := filepath.Join(tempdir, "file")
content := defaultContent content := defaultContent
@ -725,8 +718,7 @@ func TestFileChanged(t *testing.T) {
} }
func TestFilChangedSpecialCases(t *testing.T) { func TestFilChangedSpecialCases(t *testing.T) {
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
filename := filepath.Join(tempdir, "file") filename := filepath.Join(tempdir, "file")
content := []byte("foobar") content := []byte("foobar")
@ -913,8 +905,7 @@ func TestArchiverSaveDir(t *testing.T) {
} }
func TestArchiverSaveDirIncremental(t *testing.T) { func TestArchiverSaveDirIncremental(t *testing.T) {
tempdir, removeTempdir := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer removeTempdir()
testRepo, removeRepository := repository.TestRepository(t) testRepo, removeRepository := repository.TestRepository(t)
defer removeRepository() defer removeRepository()
@ -1901,11 +1892,10 @@ func TestArchiverContextCanceled(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
cancel() cancel()
tempdir, removeTempdir := restictest.TempDir(t) tempdir := restictest.TempDir(t)
TestCreateFiles(t, tempdir, TestDir{ TestCreateFiles(t, tempdir, TestDir{
"targetfile": TestFile{Content: "foobar"}, "targetfile": TestFile{Content: "foobar"},
}) })
defer removeTempdir()
// Ensure that the archiver itself reports the canceled context and not just the backend // Ensure that the archiver itself reports the canceled context and not just the backend
repo, _ := repository.TestRepositoryWithBackend(t, &noCancelBackend{mem.New()}, 0) repo, _ := repository.TestRepositoryWithBackend(t, &noCancelBackend{mem.New()}, 0)

View File

@ -15,8 +15,8 @@ import (
"golang.org/x/sync/errgroup" "golang.org/x/sync/errgroup"
) )
func createTestFiles(t testing.TB, num int) (files []string, cleanup func()) { func createTestFiles(t testing.TB, num int) (files []string) {
tempdir, cleanup := test.TempDir(t) tempdir := test.TempDir(t)
for i := 0; i < 15; i++ { for i := 0; i < 15; i++ {
filename := fmt.Sprintf("testfile-%d", i) filename := fmt.Sprintf("testfile-%d", i)
@ -27,7 +27,7 @@ func createTestFiles(t testing.TB, num int) (files []string, cleanup func()) {
files = append(files, filepath.Join(tempdir, filename)) files = append(files, filepath.Join(tempdir, filename))
} }
return files, cleanup return files
} }
func startFileSaver(ctx context.Context, t testing.TB) (*FileSaver, context.Context, *errgroup.Group) { func startFileSaver(ctx context.Context, t testing.TB) (*FileSaver, context.Context, *errgroup.Group) {
@ -60,8 +60,7 @@ func TestFileSaver(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
files, cleanup := createTestFiles(t, 15) files := createTestFiles(t, 15)
defer cleanup()
startFn := func() {} startFn := func() {}
completeReadingFn := func() {} completeReadingFn := func() {}

View File

@ -81,9 +81,7 @@ func TestScanner(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
TestCreateFiles(t, tempdir, test.src) TestCreateFiles(t, tempdir, test.src)
back := restictest.Chdir(t, tempdir) back := restictest.Chdir(t, tempdir)
@ -218,9 +216,7 @@ func TestScannerError(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
TestCreateFiles(t, tempdir, test.src) TestCreateFiles(t, tempdir, test.src)
back := restictest.Chdir(t, tempdir) back := restictest.Chdir(t, tempdir)
@ -292,9 +288,7 @@ func TestScannerCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
TestCreateFiles(t, tempdir, src) TestCreateFiles(t, tempdir, src)
back := restictest.Chdir(t, tempdir) back := restictest.Chdir(t, tempdir)

View File

@ -101,8 +101,7 @@ func TestTestCreateFiles(t *testing.T) {
} }
for i, test := range tests { for i, test := range tests {
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
tempdir := filepath.Join(tempdir, fmt.Sprintf("test-%d", i)) tempdir := filepath.Join(tempdir, fmt.Sprintf("test-%d", i))
@ -192,8 +191,7 @@ func TestTestWalkFiles(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
got := make(map[string]string) got := make(map[string]string)
@ -323,9 +321,7 @@ func TestTestEnsureFiles(t *testing.T) {
for _, test := range tests { for _, test := range tests {
t.Run("", func(t *testing.T) { t.Run("", func(t *testing.T) {
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
createFilesAt(t, tempdir, test.files) createFilesAt(t, tempdir, test.files)
subtestT := testing.TB(t) subtestT := testing.TB(t)
@ -456,8 +452,7 @@ func TestTestEnsureSnapshot(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
targetDir := filepath.Join(tempdir, "target") targetDir := filepath.Join(tempdir, "target")
err := fs.Mkdir(targetDir, 0700) err := fs.Mkdir(targetDir, 0700)

View File

@ -439,9 +439,7 @@ func TestTree(t *testing.T) {
t.Skip("skip test on unix") t.Skip("skip test on unix")
} }
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
TestCreateFiles(t, tempdir, test.src) TestCreateFiles(t, tempdir, test.src)
back := restictest.Chdir(t, tempdir) back := restictest.Chdir(t, tempdir)

View File

@ -14,8 +14,7 @@ import (
) )
func TestDefaultLayout(t *testing.T) { func TestDefaultLayout(t *testing.T) {
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
var tests = []struct { var tests = []struct {
path string path string
@ -141,8 +140,7 @@ func TestDefaultLayout(t *testing.T) {
} }
func TestRESTLayout(t *testing.T) { func TestRESTLayout(t *testing.T) {
path, cleanup := rtest.TempDir(t) path := rtest.TempDir(t)
defer cleanup()
var tests = []struct { var tests = []struct {
restic.Handle restic.Handle
@ -287,8 +285,7 @@ func TestRESTLayoutURLs(t *testing.T) {
} }
func TestS3LegacyLayout(t *testing.T) { func TestS3LegacyLayout(t *testing.T) {
path, cleanup := rtest.TempDir(t) path := rtest.TempDir(t)
defer cleanup()
var tests = []struct { var tests = []struct {
restic.Handle restic.Handle
@ -355,8 +352,7 @@ func TestS3LegacyLayout(t *testing.T) {
} }
func TestDetectLayout(t *testing.T) { func TestDetectLayout(t *testing.T) {
path, cleanup := rtest.TempDir(t) path := rtest.TempDir(t)
defer cleanup()
var tests = []struct { var tests = []struct {
filename string filename string
@ -393,8 +389,7 @@ func TestDetectLayout(t *testing.T) {
} }
func TestParseLayout(t *testing.T) { func TestParseLayout(t *testing.T) {
path, cleanup := rtest.TempDir(t) path := rtest.TempDir(t)
defer cleanup()
var tests = []struct { var tests = []struct {
layoutName string layoutName string
@ -433,8 +428,7 @@ func TestParseLayout(t *testing.T) {
} }
func TestParseLayoutInvalid(t *testing.T) { func TestParseLayoutInvalid(t *testing.T) {
path, cleanup := rtest.TempDir(t) path := rtest.TempDir(t)
defer cleanup()
var invalidNames = []string{ var invalidNames = []string{
"foo", "bar", "local", "foo", "bar", "local",

View File

@ -10,8 +10,7 @@ import (
) )
func TestLayout(t *testing.T) { func TestLayout(t *testing.T) {
path, cleanup := rtest.TempDir(t) path := rtest.TempDir(t)
defer cleanup()
var tests = []struct { var tests = []struct {
filename string filename string

View File

@ -24,8 +24,7 @@ func TestNoSpacePermanent(t *testing.T) {
return nil, fmt.Errorf("not creating tempfile, %w", syscall.ENOSPC) return nil, fmt.Errorf("not creating tempfile, %w", syscall.ENOSPC)
} }
dir, cleanup := rtest.TempDir(t) dir := rtest.TempDir(t)
defer cleanup()
be, err := Open(context.Background(), Config{Path: dir, Connections: 2}) be, err := Open(context.Background(), Config{Path: dir, Connections: 2})
rtest.OK(t, err) rtest.OK(t, err)

View File

@ -120,8 +120,7 @@ func removeAll(t testing.TB, dir string) {
} }
func TestOpenNotExistingDirectory(t *testing.T) { func TestOpenNotExistingDirectory(t *testing.T) {
dir, cleanup := rtest.TempDir(t) dir := rtest.TempDir(t)
defer cleanup()
// local.Open must not create any files dirs in the repo // local.Open must not create any files dirs in the repo
openclose(t, filepath.Join(dir, "repo")) openclose(t, filepath.Join(dir, "repo"))

View File

@ -13,7 +13,7 @@ import (
) )
func newTestSuite(t testing.TB) *test.Suite { func newTestSuite(t testing.TB) *test.Suite {
dir, cleanup := rtest.TempDir(t) dir := rtest.TempDir(t)
return &test.Suite{ return &test.Suite{
// NewConfig returns a config for a new temporary backend that will be used in tests. // NewConfig returns a config for a new temporary backend that will be used in tests.
@ -43,13 +43,6 @@ func newTestSuite(t testing.TB) *test.Suite {
cfg := config.(rclone.Config) cfg := config.(rclone.Config)
return rclone.Open(cfg, nil) return rclone.Open(cfg, nil)
}, },
// CleanupFn removes data created during the tests.
Cleanup: func(config interface{}) error {
t.Logf("cleanup dir %v", dir)
cleanup()
return nil
},
} }
} }

View File

@ -12,9 +12,7 @@ import (
// restic should detect rclone exiting. // restic should detect rclone exiting.
func TestRcloneExit(t *testing.T) { func TestRcloneExit(t *testing.T) {
dir, cleanup := rtest.TempDir(t) dir := rtest.TempDir(t)
defer cleanup()
cfg := NewConfig() cfg := NewConfig()
cfg.Remote = dir cfg.Remote = dir
be, err := Open(cfg, nil) be, err := Open(cfg, nil)

View File

@ -112,9 +112,7 @@ func TestBackendREST(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
dir, cleanup := rtest.TempDir(t) dir := rtest.TempDir(t)
defer cleanup()
serverURL, cleanup := runRESTServer(ctx, t, dir) serverURL, cleanup := runRESTServer(ctx, t, dir)
defer cleanup() defer cleanup()
@ -144,9 +142,7 @@ func BenchmarkBackendREST(t *testing.B) {
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
dir, cleanup := rtest.TempDir(t) dir := rtest.TempDir(t)
defer cleanup()
serverURL, cleanup := runRESTServer(ctx, t, dir) serverURL, cleanup := runRESTServer(ctx, t, dir)
defer cleanup() defer cleanup()

View File

@ -101,9 +101,8 @@ func newRandomCredentials(t testing.TB) (key, secret string) {
type MinioTestConfig struct { type MinioTestConfig struct {
s3.Config s3.Config
tempdir string tempdir string
removeTempdir func() stopServer func()
stopServer func()
} }
func createS3(t testing.TB, cfg MinioTestConfig, tr http.RoundTripper) (be restic.Backend, err error) { func createS3(t testing.TB, cfg MinioTestConfig, tr http.RoundTripper) (be restic.Backend, err error) {
@ -132,7 +131,7 @@ func newMinioTestSuite(ctx context.Context, t testing.TB) *test.Suite {
NewConfig: func() (interface{}, error) { NewConfig: func() (interface{}, error) {
cfg := MinioTestConfig{} cfg := MinioTestConfig{}
cfg.tempdir, cfg.removeTempdir = rtest.TempDir(t) cfg.tempdir = rtest.TempDir(t)
key, secret := newRandomCredentials(t) key, secret := newRandomCredentials(t)
cfg.stopServer = runMinio(ctx, t, cfg.tempdir, key, secret) cfg.stopServer = runMinio(ctx, t, cfg.tempdir, key, secret)
@ -179,9 +178,6 @@ func newMinioTestSuite(ctx context.Context, t testing.TB) *test.Suite {
if cfg.stopServer != nil { if cfg.stopServer != nil {
cfg.stopServer() cfg.stopServer()
} }
if cfg.removeTempdir != nil {
cfg.removeTempdir()
}
return nil return nil
}, },
} }

View File

@ -16,8 +16,7 @@ func TestLayout(t *testing.T) {
t.Skip("sftp server binary not available") t.Skip("sftp server binary not available")
} }
path, cleanup := rtest.TempDir(t) path := rtest.TempDir(t)
defer cleanup()
var tests = []struct { var tests = []struct {
filename string filename string

View File

@ -60,8 +60,10 @@ func (s *Suite) RunTests(t *testing.T) {
return return
} }
if err = s.Cleanup(s.Config); err != nil { if s.Cleanup != nil {
t.Fatal(err) if err = s.Cleanup(s.Config); err != nil {
t.Fatal(err)
}
} }
} }

View File

@ -57,10 +57,7 @@ func randomData(n int) (restic.Handle, []byte) {
func TestBackend(t *testing.T) { func TestBackend(t *testing.T) {
be := mem.New() be := mem.New()
c := TestNewCache(t)
c, cleanup := TestNewCache(t)
defer cleanup()
wbe := c.Wrap(be) wbe := c.Wrap(be)
h, data := randomData(5234142) h, data := randomData(5234142)
@ -128,10 +125,7 @@ func (be loadErrorBackend) Load(ctx context.Context, h restic.Handle, length int
func TestErrorBackend(t *testing.T) { func TestErrorBackend(t *testing.T) {
be := mem.New() be := mem.New()
c := TestNewCache(t)
c, cleanup := TestNewCache(t)
defer cleanup()
h, data := randomData(5234142) h, data := randomData(5234142)
// save directly in backend // save directly in backend
@ -174,9 +168,7 @@ func TestErrorBackend(t *testing.T) {
func TestBackendRemoveBroken(t *testing.T) { func TestBackendRemoveBroken(t *testing.T) {
be := mem.New() be := mem.New()
c := TestNewCache(t)
c, cleanup := TestNewCache(t)
defer cleanup()
h, data := randomData(5234142) h, data := randomData(5234142)
// save directly in backend // save directly in backend

View File

@ -87,8 +87,7 @@ func TestFiles(t *testing.T) {
t.Logf("seed is %v", seed) t.Logf("seed is %v", seed)
rand.Seed(seed) rand.Seed(seed)
c, cleanup := TestNewCache(t) c := TestNewCache(t)
defer cleanup()
var tests = []restic.FileType{ var tests = []restic.FileType{
restic.SnapshotFile, restic.SnapshotFile,
@ -140,8 +139,7 @@ func TestFileLoad(t *testing.T) {
t.Logf("seed is %v", seed) t.Logf("seed is %v", seed)
rand.Seed(seed) rand.Seed(seed)
c, cleanup := TestNewCache(t) c := TestNewCache(t)
defer cleanup()
// save about 5 MiB of data in the cache // save about 5 MiB of data in the cache
data := test.Random(rand.Int(), 5234142) data := test.Random(rand.Int(), 5234142)
@ -223,10 +221,8 @@ func TestFileSaveConcurrent(t *testing.T) {
const nproc = 40 const nproc = 40
c, cleanup := TestNewCache(t)
defer cleanup()
var ( var (
c = TestNewCache(t)
data = test.Random(1, 10000) data = test.Random(1, 10000)
g errgroup.Group g errgroup.Group
id restic.ID id restic.ID

View File

@ -9,12 +9,12 @@ import (
// TestNewCache returns a cache in a temporary directory which is removed when // TestNewCache returns a cache in a temporary directory which is removed when
// cleanup is called. // cleanup is called.
func TestNewCache(t testing.TB) (*Cache, func()) { func TestNewCache(t testing.TB) *Cache {
dir, cleanup := test.TempDir(t) dir := test.TempDir(t)
t.Logf("created new cache at %v", dir) t.Logf("created new cache at %v", dir)
cache, err := New(restic.NewRandomID().String(), dir) cache, err := New(restic.NewRandomID().String(), dir)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
return cache, cleanup return cache
} }

View File

@ -13,17 +13,12 @@ import (
) )
func prepareTempdirRepoSrc(t testing.TB, src archiver.TestDir) (tempdir string, repo restic.Repository, cleanup func()) { func prepareTempdirRepoSrc(t testing.TB, src archiver.TestDir) (tempdir string, repo restic.Repository, cleanup func()) {
tempdir, removeTempdir := rtest.TempDir(t) tempdir = rtest.TempDir(t)
repo, removeRepository := repository.TestRepository(t) repo, removeRepository := repository.TestRepository(t)
archiver.TestCreateFiles(t, tempdir, src) archiver.TestCreateFiles(t, tempdir, src)
cleanup = func() { return tempdir, repo, removeRepository
removeRepository()
removeTempdir()
}
return tempdir, repo, cleanup
} }
type CheckDump func(t *testing.T, testDir string, testDump *bytes.Buffer) error type CheckDump func(t *testing.T, testDir string, testDump *bytes.Buffer) error

View File

@ -9,9 +9,7 @@ import (
) )
func TestExtendedStat(t *testing.T) { func TestExtendedStat(t *testing.T) {
tempdir, cleanup := restictest.TempDir(t) tempdir := restictest.TempDir(t)
defer cleanup()
filename := filepath.Join(tempdir, "file") filename := filepath.Join(tempdir, "file")
err := os.WriteFile(filename, []byte("foobar"), 0640) err := os.WriteFile(filename, []byte("foobar"), 0640)
if err != nil { if err != nil {

View File

@ -27,9 +27,7 @@ func TestByteReader(t *testing.T) {
func TestFileReader(t *testing.T) { func TestFileReader(t *testing.T) {
buf := []byte("foobar") buf := []byte("foobar")
d, cleanup := test.TempDir(t) d := test.TempDir(t)
defer cleanup()
filename := filepath.Join(d, "file-reader-test") filename := filepath.Join(d, "file-reader-test")
err := os.WriteFile(filename, buf, 0600) err := os.WriteFile(filename, buf, 0600)
if err != nil { if err != nil {

View File

@ -185,8 +185,7 @@ func verifyRestore(t *testing.T, r *fileRestorer, repo *TestRepo) {
} }
func TestFileRestorerBasic(t *testing.T) { func TestFileRestorerBasic(t *testing.T) {
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
for _, sparse := range []bool{false, true} { for _, sparse := range []bool{false, true} {
restoreAndVerify(t, tempdir, []TestFile{ restoreAndVerify(t, tempdir, []TestFile{
@ -217,8 +216,7 @@ func TestFileRestorerBasic(t *testing.T) {
} }
func TestFileRestorerPackSkip(t *testing.T) { func TestFileRestorerPackSkip(t *testing.T) {
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
files := make(map[string]bool) files := make(map[string]bool)
files["file2"] = true files["file2"] = true
@ -250,8 +248,7 @@ func TestFileRestorerPackSkip(t *testing.T) {
} }
func TestErrorRestoreFiles(t *testing.T) { func TestErrorRestoreFiles(t *testing.T) {
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
content := []TestFile{ content := []TestFile{
{ {
name: "file1", name: "file1",
@ -282,8 +279,7 @@ func TestDownloadError(t *testing.T) {
} }
func testPartialDownloadError(t *testing.T, part int) { func testPartialDownloadError(t *testing.T, part int) {
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
content := []TestFile{ content := []TestFile{
{ {
name: "file1", name: "file1",

View File

@ -8,9 +8,7 @@ import (
) )
func TestFilesWriterBasic(t *testing.T) { func TestFilesWriterBasic(t *testing.T) {
dir, cleanup := rtest.TempDir(t) dir := rtest.TempDir(t)
defer cleanup()
w := newFilesWriter(1) w := newFilesWriter(1)
f1 := dir + "/f1" f1 := dir + "/f1"

View File

@ -14,8 +14,7 @@ import (
func TestPreallocate(t *testing.T) { func TestPreallocate(t *testing.T) {
for _, i := range []int64{0, 1, 4096, 1024 * 1024} { for _, i := range []int64{0, 1, 4096, 1024 * 1024} {
t.Run(strconv.FormatInt(i, 10), func(t *testing.T) { t.Run(strconv.FormatInt(i, 10), func(t *testing.T) {
dirpath, cleanup := test.TempDir(t) dirpath := test.TempDir(t)
defer cleanup()
flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY flags := os.O_CREATE | os.O_TRUNC | os.O_WRONLY
wr, err := os.OpenFile(path.Join(dirpath, "test"), flags, 0600) wr, err := os.OpenFile(path.Join(dirpath, "test"), flags, 0600)

View File

@ -328,9 +328,7 @@ func TestRestorer(t *testing.T) {
res := NewRestorer(context.TODO(), repo, sn, false) res := NewRestorer(context.TODO(), repo, sn, false)
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
// make sure we're creating a new subdir of the tempdir // make sure we're creating a new subdir of the tempdir
tempdir = filepath.Join(tempdir, "target") tempdir = filepath.Join(tempdir, "target")
@ -448,9 +446,7 @@ func TestRestorerRelative(t *testing.T) {
res := NewRestorer(context.TODO(), repo, sn, false) res := NewRestorer(context.TODO(), repo, sn, false)
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
cleanup = rtest.Chdir(t, tempdir) cleanup = rtest.Chdir(t, tempdir)
defer cleanup() defer cleanup()
@ -682,9 +678,7 @@ func TestRestorerTraverseTree(t *testing.T) {
res.SelectFilter = test.Select res.SelectFilter = test.Select
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
@ -776,9 +770,7 @@ func TestRestorerConsistentTimestampsAndPermissions(t *testing.T) {
return selectedForRestore, childMayBeSelected return selectedForRestore, childMayBeSelected
} }
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
@ -818,9 +810,7 @@ func TestVerifyCancel(t *testing.T) {
res := NewRestorer(context.TODO(), repo, sn, false) res := NewRestorer(context.TODO(), repo, sn, false)
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()
@ -863,9 +853,7 @@ func TestRestorerSparseFiles(t *testing.T) {
res := NewRestorer(context.TODO(), repo, sn, true) res := NewRestorer(context.TODO(), repo, sn, true)
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()

View File

@ -36,9 +36,7 @@ func TestRestorerRestoreEmptyHardlinkedFileds(t *testing.T) {
return true, true return true, true
} }
tempdir, cleanup := rtest.TempDir(t) tempdir := rtest.TempDir(t)
defer cleanup()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
defer cancel() defer cancel()

View File

@ -191,22 +191,23 @@ func RemoveAll(t testing.TB, path string) {
OK(t, err) OK(t, err)
} }
// TempDir returns a temporary directory that is removed when cleanup is // TempDir returns a temporary directory that is removed by t.Cleanup,
// called, except if TestCleanupTempDirs is set to false. // except if TestCleanupTempDirs is set to false.
func TempDir(t testing.TB) (path string, cleanup func()) { func TempDir(t testing.TB) string {
tempdir, err := os.MkdirTemp(TestTempDir, "restic-test-") tempdir, err := os.MkdirTemp(TestTempDir, "restic-test-")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
return tempdir, func() { t.Cleanup(func() {
if !TestCleanupTempDirs { if !TestCleanupTempDirs {
t.Logf("leaving temporary directory %v used for test", tempdir) t.Logf("leaving temporary directory %v used for test", tempdir)
return return
} }
RemoveAll(t, tempdir) RemoveAll(t, tempdir)
} })
return tempdir
} }
// Chdir changes the current directory to dest. // Chdir changes the current directory to dest.