diff options
author | Patrick Steinhardt <psteinhardt@gitlab.com> | 2021-04-23 11:37:11 +0300 |
---|---|---|
committer | Patrick Steinhardt <psteinhardt@gitlab.com> | 2021-04-23 11:37:11 +0300 |
commit | 055ad62dd5d82955ddfb5f050732427df5928878 (patch) | |
tree | c9b8a1c17aeab466ea7881e31fc7c3aea01531c3 | |
parent | 16479e5771b69a2b4c22aade7c0a7fc2a6f897ce (diff) | |
parent | b7e6dd3a79fd4819a4daa35aa983168fd0b4e1d2 (diff) |
Merge branch 'pks-tempdir-cleanup' into 'master'
testhelper: Convert `TempDir()` to use `t.Cleanup()`
See merge request gitlab-org/gitaly!3375
57 files changed, 143 insertions, 290 deletions
diff --git a/client/dial_test.go b/client/dial_test.go index b9a1dabe2..e3f5a8cd8 100644 --- a/client/dial_test.go +++ b/client/dial_test.go @@ -41,8 +41,7 @@ func TestDial(t *testing.T) { unixSocketAbsPath := connectionMap["unix"] - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) unixSocketPath := filepath.Join(tempDir, "gitaly.socket") require.NoError(t, os.Symlink(unixSocketAbsPath, unixSocketPath)) diff --git a/cmd/gitaly-backup/create_test.go b/cmd/gitaly-backup/create_test.go index 4adaa916c..e14944dda 100644 --- a/cmd/gitaly-backup/create_test.go +++ b/cmd/gitaly-backup/create_test.go @@ -24,8 +24,7 @@ func TestCreateSubcommand(t *testing.T) { gitalyAddr := testserver.RunGitalyServer(t, cfg, nil, setup.RegisterAll) - path, cleanup := testhelper.TempDir(t) - t.Cleanup(cleanup) + path := testhelper.TempDir(t) var repos []*gitalypb.Repository for i := 0; i < 5; i++ { diff --git a/cmd/gitaly-hooks/hooks_test.go b/cmd/gitaly-hooks/hooks_test.go index de1633e95..a79baf910 100644 --- a/cmd/gitaly-hooks/hooks_test.go +++ b/cmd/gitaly-hooks/hooks_test.go @@ -104,8 +104,7 @@ func testMain(m *testing.M) int { } func TestHooksPrePostWithSymlinkedStoragePath(t *testing.T) { - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) cfg, repo, repoPath := testcfg.BuildWithRepo(t) testhelper.ConfigureGitalyHooksBin(t, cfg) @@ -248,8 +247,7 @@ func TestHooksUpdate(t *testing.T) { glUsername := "iamgitlab" glProtocol := "ssh" - customHooksDir, cleanup := testhelper.TempDir(t) - defer cleanup() + customHooksDir := testhelper.TempDir(t) cfg := testcfg.Build(t, testcfg.WithBase(config.Cfg{ Auth: auth.Config{Token: "abc123"}, @@ -283,8 +281,7 @@ func testHooksUpdate(t *testing.T, cfg config.Cfg, glValues glHookValues) { cmd.Env = envForHooks(t, cfg, repo, glValues, proxyValues{}) cmd.Dir = repoPath - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) customHookArgsPath := filepath.Join(tempDir, "containsarguments") dumpArgsToTempfileScript := fmt.Sprintf(`#!/usr/bin/env ruby @@ -511,8 +508,7 @@ func TestCheckOK(t *testing.T) { serverURL, cleanup := testhelper.NewGitlabTestServer(t, c) defer cleanup() - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) gitlabShellDir := filepath.Join(tempDir, "gitlab-shell") require.NoError(t, os.MkdirAll(gitlabShellDir, 0755)) @@ -556,8 +552,7 @@ func TestCheckBadCreds(t *testing.T) { serverURL, cleanup := testhelper.NewGitlabTestServer(t, c) defer cleanup() - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) gitlabShellDir := filepath.Join(tempDir, "gitlab-shell") require.NoError(t, os.MkdirAll(gitlabShellDir, 0755)) @@ -697,8 +692,7 @@ func TestGitalyHooksPackObjects(t *testing.T) { t.Run(tc.desc, func(t *testing.T) { defer runHookServiceServer(t, cfg)() - tempDir, cleanTempDir := testhelper.TempDir(t) - defer cleanTempDir() + tempDir := testhelper.TempDir(t) args := append(baseArgs[1:], tc.extraArgs...) args = append(args, repoPath, tempDir) diff --git a/cmd/gitaly-lfs-smudge/lfs_smudge_test.go b/cmd/gitaly-lfs-smudge/lfs_smudge_test.go index 097d0df60..d87c2b1fe 100644 --- a/cmd/gitaly-lfs-smudge/lfs_smudge_test.go +++ b/cmd/gitaly-lfs-smudge/lfs_smudge_test.go @@ -69,7 +69,7 @@ func (m *mapConfig) Get(key string) string { } func runTestServer(t *testing.T, options testhelper.GitlabTestServerOptions) (config.Gitlab, func()) { - tempDir, cleanup := testhelper.TempDir(t) + tempDir := testhelper.TempDir(t) testhelper.WriteShellSecretFile(t, tempDir, secretToken) secretFilePath := filepath.Join(tempDir, ".gitlab_shell_secret") @@ -79,7 +79,6 @@ func runTestServer(t *testing.T, options testhelper.GitlabTestServerOptions) (co c := config.Gitlab{URL: serverURL, SecretFile: secretFilePath, HTTPSettings: config.HTTPSettings{CAFile: certPath}} return c, func() { - cleanup() serverCleanup() } } @@ -116,8 +115,7 @@ func TestSuccessfulLfsSmudge(t *testing.T) { }) require.NoError(t, err) - tmpDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tmpDir := testhelper.TempDir(t) env := map[string]string{ "GL_REPOSITORY": "project-1", @@ -225,8 +223,7 @@ func TestUnsuccessfulLfsSmudge(t *testing.T) { tlsCfg, err := json.Marshal(tc.tlsCfg) require.NoError(t, err) - tmpDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tmpDir := testhelper.TempDir(t) env := map[string]string{ "GL_REPOSITORY": "project-1", diff --git a/cmd/gitaly-ssh/auth_test.go b/cmd/gitaly-ssh/auth_test.go index 4a5c713f3..f1b1d218b 100644 --- a/cmd/gitaly-ssh/auth_test.go +++ b/cmd/gitaly-ssh/auth_test.go @@ -39,8 +39,7 @@ func TestConnectivity(t *testing.T) { certPoolPath := filepath.Join(cwd, "testdata", "certs") - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) relativeSocketPath, err := filepath.Rel(cwd, filepath.Join(tempDir, "gitaly.socket")) require.NoError(t, err) diff --git a/cmd/praefect/subcmd_test.go b/cmd/praefect/subcmd_test.go index ea91e60df..d966b77d0 100644 --- a/cmd/praefect/subcmd_test.go +++ b/cmd/praefect/subcmd_test.go @@ -33,7 +33,7 @@ func registerServerService(impl gitalypb.ServerServiceServer) svcRegistrar { func listenAndServe(t testing.TB, svcs []svcRegistrar) (net.Listener, testhelper.Cleanup) { t.Helper() - tmp, clean := testhelper.TempDir(t) + tmp := testhelper.TempDir(t) ln, err := net.Listen("unix", filepath.Join(tmp, "gitaly")) require.NoError(t, err) @@ -57,6 +57,5 @@ func listenAndServe(t testing.TB, svcs []svcRegistrar) (net.Listener, testhelper return ln, func() { srv.Stop() - clean() } } diff --git a/internal/backup/backup_test.go b/internal/backup/backup_test.go index 11e4c1b22..ce85f235f 100644 --- a/internal/backup/backup_test.go +++ b/internal/backup/backup_test.go @@ -21,8 +21,7 @@ func TestFilesystem_BackupRepository(t *testing.T) { gitalyAddr := testserver.RunGitalyServer(t, cfg, nil, setup.RegisterAll) - path, cleanup := testhelper.TempDir(t) - t.Cleanup(cleanup) + path := testhelper.TempDir(t) hooksRepo, hooksRepoPath, _ := gittest.CloneRepoAtStorage(t, cfg.Storages[0], "hooks") require.NoError(t, os.Mkdir(filepath.Join(hooksRepoPath, "custom_hooks"), os.ModePerm)) diff --git a/internal/bootstrap/bootstrap_test.go b/internal/bootstrap/bootstrap_test.go index 0b0e63fa3..dff68d09b 100644 --- a/internal/bootstrap/bootstrap_test.go +++ b/internal/bootstrap/bootstrap_test.go @@ -60,8 +60,7 @@ func (s *testServer) slowRequest(duration time.Duration) <-chan error { } func TestCreateUnixListener(t *testing.T) { - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) socketPath := filepath.Join(tempDir, "gitaly-test-unix-socket") if err := os.Remove(socketPath); err != nil { @@ -291,8 +290,7 @@ func makeBootstrap(t *testing.T) (*Bootstrap, *testServer) { } } - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) for network, address := range map[string]string{ "tcp": "127.0.0.1:0", diff --git a/internal/cache/cachedb_test.go b/internal/cache/cachedb_test.go index 184305600..2be2d70f8 100644 --- a/internal/cache/cachedb_test.go +++ b/internal/cache/cachedb_test.go @@ -136,7 +136,6 @@ func TestLoserCount(t *testing.T) { // the test can be contaminate by other tests using the cache, so a // dedicated storage location should be used cfgBuilder := testcfg.NewGitalyCfgBuilder(testcfg.WithStorages("storage-1", "storage-2")) - defer cfgBuilder.Cleanup() cfg := cfgBuilder.Build(t) db := cache.NewStreamDB(cache.NewLeaseKeyer(config.NewLocator(cfg))) diff --git a/internal/cache/walker_internal_test.go b/internal/cache/walker_internal_test.go index 438978f77..a09d75563 100644 --- a/internal/cache/walker_internal_test.go +++ b/internal/cache/walker_internal_test.go @@ -20,8 +20,7 @@ func TestCleanWalkDirNotExists(t *testing.T) { } func TestCleanWalkEmptyDirs(t *testing.T) { - tmp, cleanup := testhelper.TempDir(t) - defer cleanup() + tmp := testhelper.TempDir(t) for _, tt := range []struct { path string diff --git a/internal/cgroups/mock_linux_test.go b/internal/cgroups/mock_linux_test.go index 6376cbf4b..15cc78057 100644 --- a/internal/cgroups/mock_linux_test.go +++ b/internal/cgroups/mock_linux_test.go @@ -33,10 +33,10 @@ type mockCgroup struct { subsystems []cgroups.Subsystem } -func newMock(t *testing.T) (*mockCgroup, func()) { +func newMock(t *testing.T) *mockCgroup { t.Helper() - root, clean := testhelper.TempDir(t) + root := testhelper.TempDir(t) subsystems, err := defaultSubsystems(root) require.NoError(t, err) @@ -48,7 +48,7 @@ func newMock(t *testing.T) (*mockCgroup, func()) { return &mockCgroup{ root: root, subsystems: subsystems, - }, clean + } } func (m *mockCgroup) hierarchy() ([]cgroups.Subsystem, error) { diff --git a/internal/cgroups/v1_linux_test.go b/internal/cgroups/v1_linux_test.go index c2bbd04bd..5fcadfc64 100644 --- a/internal/cgroups/v1_linux_test.go +++ b/internal/cgroups/v1_linux_test.go @@ -33,8 +33,7 @@ func defaultCgroupsConfig() cgroups.Config { } func TestSetup(t *testing.T) { - mock, clean := newMock(t) - defer clean() + mock := newMock(t) v1Manager := &CGroupV1Manager{ cfg: defaultCgroupsConfig(), @@ -60,8 +59,7 @@ func TestSetup(t *testing.T) { } func TestAddCommand(t *testing.T) { - mock, clean := newMock(t) - defer clean() + mock := newMock(t) config := defaultCgroupsConfig() v1Manager1 := &CGroupV1Manager{ @@ -99,8 +97,7 @@ func TestAddCommand(t *testing.T) { } func TestCleanup(t *testing.T) { - mock, clean := newMock(t) - defer clean() + mock := newMock(t) v1Manager := &CGroupV1Manager{ cfg: defaultCgroupsConfig(), diff --git a/internal/git/command_factory_test.go b/internal/git/command_factory_test.go index 127936180..dbcffbf5f 100644 --- a/internal/git/command_factory_test.go +++ b/internal/git/command_factory_test.go @@ -32,8 +32,7 @@ func TestGitCommandProxy(t *testing.T) { ctx, cancel := testhelper.Context() defer cancel() - dir, cleanup := testhelper.TempDir(t) - defer cleanup() + dir := testhelper.TempDir(t) gitCmdFactory := git.NewExecCommandFactory(cfg) cmd, err := gitCmdFactory.NewWithoutRepo(ctx, git.SubCmd{ @@ -62,8 +61,7 @@ func TestExecCommandFactory_NewWithDir(t *testing.T) { }) t.Run("runs in dir", func(t *testing.T) { - repoPath, cleanup := testhelper.TempDir(t) - defer cleanup() + repoPath := testhelper.TempDir(t) testhelper.MustRunCommand(t, nil, "git", "init", repoPath) testhelper.MustRunCommand(t, nil, "git", "-C", repoPath, "commit", "--allow-empty", diff --git a/internal/git/dirs_test.go b/internal/git/dirs_test.go index e0bb87e0c..90b044dcd 100644 --- a/internal/git/dirs_test.go +++ b/internal/git/dirs_test.go @@ -50,8 +50,7 @@ func TestObjectDirsNoAlternates(t *testing.T) { } func TestObjectDirsOutsideStorage(t *testing.T) { - tmp, clean := testhelper.TempDir(t) - defer clean() + tmp := testhelper.TempDir(t) storageRoot := filepath.Join(tmp, "storage-root") repoPath := filepath.Join(storageRoot, "repo") diff --git a/internal/git/gittest/hooks.go b/internal/git/gittest/hooks.go index 09e91cf29..3c8aad791 100644 --- a/internal/git/gittest/hooks.go +++ b/internal/git/gittest/hooks.go @@ -7,15 +7,14 @@ import ( "path/filepath" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gitlab.com/gitlab-org/gitaly/internal/git/hooks" "gitlab.com/gitlab-org/gitaly/internal/testhelper" ) // WriteEnvToCustomHook dumps the env vars that the custom hooks receives to a file func WriteEnvToCustomHook(t testing.TB, repoPath, hookName string) string { - tempDir, cleanup := testhelper.TempDir(t) - t.Cleanup(cleanup) + tempDir := testhelper.TempDir(t) outputPath := filepath.Join(tempDir, "hook.env") hookContent := fmt.Sprintf("#!/bin/sh\n/usr/bin/env >%s\n", outputPath) @@ -50,28 +49,21 @@ func WriteCustomHook(t testing.TB, repoPath, name string, content []byte) { // CaptureHookEnv creates a bogus 'update' Git hook to sniff out what // environment variables get set for hooks. func CaptureHookEnv(t testing.TB) (string, func()) { - tempDir, cleanup := testhelper.TempDir(t) + tempDir := testhelper.TempDir(t) oldOverride := hooks.Override hooks.Override = filepath.Join(tempDir, "hooks") hookOutputFile := filepath.Join(tempDir, "hook.env") - if !assert.NoError(t, os.MkdirAll(hooks.Override, 0755)) { - cleanup() - t.FailNow() - } + require.NoError(t, os.MkdirAll(hooks.Override, 0755)) script := []byte(` #!/bin/sh env | grep -e ^GIT -e ^GL_ > ` + hookOutputFile + "\n") - if !assert.NoError(t, ioutil.WriteFile(filepath.Join(hooks.Override, "update"), script, 0755)) { - cleanup() - t.FailNow() - } + require.NoError(t, ioutil.WriteFile(filepath.Join(hooks.Override, "update"), script, 0755)) return hookOutputFile, func() { - cleanup() hooks.Override = oldOverride } } diff --git a/internal/git/gittest/protocol.go b/internal/git/gittest/protocol.go index d6f8ebb08..701b361ed 100644 --- a/internal/git/gittest/protocol.go +++ b/internal/git/gittest/protocol.go @@ -15,8 +15,7 @@ import ( // protocol to be tested. It returns a function to read the GIT_PROTOCOl environment variable // created by the wrapper script, the modified configuration as well as a cleanup function. func EnableGitProtocolV2Support(t testing.TB, cfg config.Cfg) (func() string, config.Cfg) { - dir, cleanupDir := testhelper.TempDir(t) - t.Cleanup(cleanupDir) + dir := testhelper.TempDir(t) gitPath := filepath.Join(dir, "git") envPath := filepath.Join(dir, "git-env") diff --git a/internal/git/localrepo/remote_test.go b/internal/git/localrepo/remote_test.go index 79c93a6a8..14659e816 100644 --- a/internal/git/localrepo/remote_test.go +++ b/internal/git/localrepo/remote_test.go @@ -443,8 +443,7 @@ func TestRepo_Push(t *testing.T) { cfg, sourceRepoPb, _ := testcfg.BuildWithRepo(t) - tmpDir, clean := testhelper.TempDir(t) - defer clean() + tmpDir := testhelper.TempDir(t) gitPath := filepath.Join(tmpDir, "git-hook") envPath := filepath.Join(tmpDir, "GIT_SSH_PATH") diff --git a/internal/git/packfile/packfile_test.go b/internal/git/packfile/packfile_test.go index 7353248df..2074f903a 100644 --- a/internal/git/packfile/packfile_test.go +++ b/internal/git/packfile/packfile_test.go @@ -21,8 +21,7 @@ func testMain(m *testing.M) int { } func TestList(t *testing.T) { - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) emptyRepo := filepath.Join(tempDir, "empty.git") testhelper.MustRunCommand(t, nil, "git", "init", "--bare", emptyRepo) diff --git a/internal/gitaly/hook/access_test.go b/internal/gitaly/hook/access_test.go index e32b559f1..da34b4c7e 100644 --- a/internal/gitaly/hook/access_test.go +++ b/internal/gitaly/hook/access_test.go @@ -46,8 +46,7 @@ func TestAccess_verifyParams(t *testing.T) { gitAlternateObjectDirsFull = append(gitAlternateObjectDirsFull, filepath.Join(testRepoPath, gitAlternateObjectDirRel)) } - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) testhelper.WriteShellSecretFile(t, tempDir, secretToken) secretFilePath := filepath.Join(tempDir, ".gitlab_shell_secret") @@ -149,8 +148,7 @@ func TestAccess_escapedAndRelativeURLs(t *testing.T) { gitAlternateObjectDirsFull = append(gitAlternateObjectDirsFull, filepath.Join(testRepoPath, gitAlternateObjectDirRel)) } - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) testhelper.WriteShellSecretFile(t, tempDir, secretToken) secretFilePath := filepath.Join(tempDir, ".gitlab_shell_secret") @@ -244,8 +242,7 @@ func TestAccess_allowedResponseHandling(t *testing.T) { defer cleanup() - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) testhelper.WriteShellSecretFile(t, tempDir, "secret_token") secretFilePath := filepath.Join(tempDir, ".gitlab_shell_secret") @@ -386,8 +383,7 @@ func TestAccess_allowedResponseHandling(t *testing.T) { } func TestAccess_preReceive(t *testing.T) { - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) testhelper.WriteShellSecretFile(t, tempDir, "secret_token") @@ -477,8 +473,7 @@ func TestAccess_preReceive(t *testing.T) { } func TestAccess_postReceive(t *testing.T) { - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) testhelper.WriteShellSecretFile(t, tempDir, "secret_token") diff --git a/internal/gitaly/hook/custom_test.go b/internal/gitaly/hook/custom_test.go index 763bab9c3..eeecf12f3 100644 --- a/internal/gitaly/hook/custom_test.go +++ b/internal/gitaly/hook/custom_test.go @@ -82,8 +82,7 @@ func TestCustomHooksSuccess(t *testing.T) { for _, tc := range testCases { t.Run(tc.hookName, func(t *testing.T) { - globalCustomHooksDir, cleanupGlobalDir := testhelper.TempDir(t) - defer cleanupGlobalDir() + globalCustomHooksDir := testhelper.TempDir(t) locator := config.NewLocator(cfg) // hook is in project custom hook directory <repository>.git/custom_hooks/<hook_name> @@ -104,8 +103,7 @@ func TestCustomHooksSuccess(t *testing.T) { func TestCustomHookPartialFailure(t *testing.T) { cfg, repo, repoPath := testcfg.BuildWithRepo(t) - globalCustomHooksDir, cleanup := testhelper.TempDir(t) - defer cleanup() + globalCustomHooksDir := testhelper.TempDir(t) ctx, cancel := testhelper.Context() defer cancel() @@ -179,8 +177,7 @@ func TestCustomHookPartialFailure(t *testing.T) { func TestCustomHooksMultipleHooks(t *testing.T) { cfg, repo, repoPath := testcfg.BuildWithRepo(t) - globalCustomHooksDir, cleanup := testhelper.TempDir(t) - defer cleanup() + globalCustomHooksDir := testhelper.TempDir(t) ctx, cancel := testhelper.Context() defer cancel() @@ -228,8 +225,7 @@ func TestCustomHooksMultipleHooks(t *testing.T) { func TestCustomHooksWithSymlinks(t *testing.T) { cfg, repo, _ := testcfg.BuildWithRepo(t) - globalCustomHooksDir, cleanup := testhelper.TempDir(t) - defer cleanup() + globalCustomHooksDir := testhelper.TempDir(t) ctx, cancel := testhelper.Context() defer cancel() @@ -299,8 +295,7 @@ func TestCustomHooksWithSymlinks(t *testing.T) { func TestMultilineStdin(t *testing.T) { cfg, repo, repoPath := testcfg.BuildWithRepo(t) - globalCustomHooksDir, cleanup := testhelper.TempDir(t) - defer cleanup() + globalCustomHooksDir := testhelper.TempDir(t) ctx, cancel := testhelper.Context() defer cancel() @@ -332,8 +327,7 @@ old3 new3 ref3 func TestMultipleScriptsStdin(t *testing.T) { cfg, repo, repoPath := testcfg.BuildWithRepo(t) - globalCustomHooksDir, cleanup := testhelper.TempDir(t) - defer cleanup() + globalCustomHooksDir := testhelper.TempDir(t) ctx, cancel := testhelper.Context() defer cancel() diff --git a/internal/gitaly/maintenance/optimize_test.go b/internal/gitaly/maintenance/optimize_test.go index 2a18b7de6..c205bbd2e 100644 --- a/internal/gitaly/maintenance/optimize_test.go +++ b/internal/gitaly/maintenance/optimize_test.go @@ -37,7 +37,6 @@ func (mo *mockOptimizer) OptimizeRepository(ctx context.Context, req *gitalypb.O func TestOptimizeReposRandomly(t *testing.T) { cfgBuilder := testcfg.NewGitalyCfgBuilder(testcfg.WithStorages("0", "1", "2")) - defer cfgBuilder.Cleanup() cfg := cfgBuilder.Build(t) for _, storage := range cfg.Storages { diff --git a/internal/gitaly/maintenance/randomwalker_test.go b/internal/gitaly/maintenance/randomwalker_test.go index 9213197c9..fcb0e48c2 100644 --- a/internal/gitaly/maintenance/randomwalker_test.go +++ b/internal/gitaly/maintenance/randomwalker_test.go @@ -147,8 +147,7 @@ func TestRandomWalk(t *testing.T) { }, } { t.Run(tc.desc, func(t *testing.T) { - root, cleanup := testhelper.TempDir(t) - defer cleanup() + root := testhelper.TempDir(t) for _, dir := range tc.dirs { require.NoError(t, os.MkdirAll(filepath.Join(root, dir), 0777)) @@ -192,8 +191,7 @@ func TestRandomWalk(t *testing.T) { } func TestRandomWalk_withRemovedDirs(t *testing.T) { - root, cleanup := testhelper.TempDir(t) - defer cleanup() + root := testhelper.TempDir(t) for _, dir := range []string{"foo/bar", "foo/bar/deleteme", "foo/baz/qux", "foo/baz/other"} { require.NoError(t, os.MkdirAll(filepath.Join(root, dir), 0777)) diff --git a/internal/gitaly/server/server_factory_test.go b/internal/gitaly/server/server_factory_test.go index a6ed061fd..78ef98747 100644 --- a/internal/gitaly/server/server_factory_test.go +++ b/internal/gitaly/server/server_factory_test.go @@ -91,8 +91,7 @@ func TestGitalyServerFactory(t *testing.T) { }) t.Run("secure", func(t *testing.T) { - certFile, keyFile, remove := testhelper.GenerateTestCerts(t) - t.Cleanup(remove) + certFile, keyFile := testhelper.GenerateCerts(t) cfg := testcfg.Build(t, testcfg.WithBase(config.Cfg{TLS: config.TLS{ CertPath: certFile, diff --git a/internal/gitaly/service/conflicts/resolve_conflicts_test.go b/internal/gitaly/service/conflicts/resolve_conflicts_test.go index 4e7d9cbcd..3dca33205 100644 --- a/internal/gitaly/service/conflicts/resolve_conflicts_test.go +++ b/internal/gitaly/service/conflicts/resolve_conflicts_test.go @@ -454,8 +454,7 @@ func testResolveConflictsIdenticalContentFeatured(t *testing.T, ctx context.Cont targetOID, err := repo.ResolveRevision(ctx, git.Revision(targetBranch)) require.NoError(t, err) - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) var conflictingPaths []string for _, rev := range []string{ diff --git a/internal/gitaly/service/hook/pack_objects_test.go b/internal/gitaly/service/hook/pack_objects_test.go index 5ac8cd19c..97d444114 100644 --- a/internal/gitaly/service/hook/pack_objects_test.go +++ b/internal/gitaly/service/hook/pack_objects_test.go @@ -48,9 +48,7 @@ func TestServer_PackObjectsHook_invalidArgument(t *testing.T) { func cfgWithCache(t *testing.T) (config.Cfg, *gitalypb.Repository, string) { cfg, repo, repoPath := testcfg.BuildWithRepo(t) cfg.PackObjectsCache.Enabled = true - var cleanup func() - cfg.PackObjectsCache.Dir, cleanup = testhelper.TempDir(t) - t.Cleanup(cleanup) + cfg.PackObjectsCache.Dir = testhelper.TempDir(t) return cfg, repo, repoPath } diff --git a/internal/gitaly/service/hook/post_receive_test.go b/internal/gitaly/service/hook/post_receive_test.go index cc062f95f..034f95452 100644 --- a/internal/gitaly/service/hook/post_receive_test.go +++ b/internal/gitaly/service/hook/post_receive_test.go @@ -36,8 +36,7 @@ func TestPostReceiveInvalidArgument(t *testing.T) { func TestHooksMissingStdin(t *testing.T) { user, password, secretToken := "user", "password", "secret token" - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) testhelper.WriteShellSecretFile(t, tempDir, secretToken) cfg, repo, repoPath := testcfg.BuildWithRepo(t) @@ -186,8 +185,7 @@ To create a merge request for okay, visit: secretToken := "secret token" user, password := "user", "password" - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) testhelper.WriteShellSecretFile(t, tempDir, secretToken) for _, tc := range testCases { diff --git a/internal/gitaly/service/hook/pre_receive_test.go b/internal/gitaly/service/hook/pre_receive_test.go index 39b5b6e6f..cd27cf1d1 100644 --- a/internal/gitaly/service/hook/pre_receive_test.go +++ b/internal/gitaly/service/hook/pre_receive_test.go @@ -98,8 +98,7 @@ func TestPreReceiveHook_GitlabAPIAccess(t *testing.T) { gitAlternateObjectAbsDirs = append(gitAlternateObjectAbsDirs, filepath.Join(repoPath, gitAltObjectRel)) } - tmpDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tmpDir := testhelper.TempDir(t) secretFilePath := filepath.Join(tmpDir, ".gitlab_shell_secret") testhelper.WriteShellSecretFile(t, tmpDir, secretToken) @@ -231,8 +230,7 @@ func TestPreReceive_APIErrors(t *testing.T) { }, } - tmpDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tmpDir := testhelper.TempDir(t) secretFilePath := filepath.Join(tmpDir, ".gitlab_shell_secret") testhelper.WriteShellSecretFile(t, tmpDir, "token") @@ -305,8 +303,7 @@ func TestPreReceiveHook_CustomHookErrors(t *testing.T) { srv := httptest.NewServer(mux) defer srv.Close() - tmpDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tmpDir := testhelper.TempDir(t) secretFilePath := filepath.Join(tmpDir, ".gitlab_shell_secret") testhelper.WriteShellSecretFile(t, tmpDir, "token") @@ -441,8 +438,7 @@ func TestPreReceiveHook_Primary(t *testing.T) { srv := httptest.NewServer(mux) defer srv.Close() - tmpDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tmpDir := testhelper.TempDir(t) secretFilePath := filepath.Join(tmpDir, ".gitlab_shell_secret") testhelper.WriteShellSecretFile(t, tmpDir, "token") diff --git a/internal/gitaly/service/internalgitaly/walkrepos_test.go b/internal/gitaly/service/internalgitaly/walkrepos_test.go index ff4925174..a55886217 100644 --- a/internal/gitaly/service/internalgitaly/walkrepos_test.go +++ b/internal/gitaly/service/internalgitaly/walkrepos_test.go @@ -35,8 +35,7 @@ func (w *streamWrapper) Send(resp *gitalypb.WalkReposResponse) error { } func TestWalkRepos(t *testing.T) { - testRoot, clean := testhelper.TempDir(t) - defer clean() + testRoot := testhelper.TempDir(t) storageName := "default" storageRoot := filepath.Join(testRoot, "storage") diff --git a/internal/gitaly/service/namespace/testhelper_test.go b/internal/gitaly/service/namespace/testhelper_test.go index a76d71298..fed1f8461 100644 --- a/internal/gitaly/service/namespace/testhelper_test.go +++ b/internal/gitaly/service/namespace/testhelper_test.go @@ -15,7 +15,6 @@ import ( func setupNamespaceService(t testing.TB) (config.Cfg, gitalypb.NamespaceServiceClient) { cfgBuilder := testcfg.NewGitalyCfgBuilder(testcfg.WithStorages("default", "other")) - t.Cleanup(cfgBuilder.Cleanup) cfg := cfgBuilder.Build(t) locator := config.NewLocator(cfg) diff --git a/internal/gitaly/service/objectpool/fetch_into_object_pool_test.go b/internal/gitaly/service/objectpool/fetch_into_object_pool_test.go index 8e601a3ce..3df38142a 100644 --- a/internal/gitaly/service/objectpool/fetch_into_object_pool_test.go +++ b/internal/gitaly/service/objectpool/fetch_into_object_pool_test.go @@ -96,8 +96,7 @@ func TestFetchIntoObjectPool_hooks(t *testing.T) { require.NoError(t, pool.Remove(ctx)) }() - hookDir, cleanup := testhelper.TempDir(t) - defer cleanup() + hookDir := testhelper.TempDir(t) defer func(oldValue string) { hooks.Override = oldValue @@ -164,7 +163,6 @@ func TestFetchIntoObjectPool_CollectLogStatistics(t *testing.T) { func TestFetchIntoObjectPool_Failure(t *testing.T) { cfgBuilder := testcfg.NewGitalyCfgBuilder() - defer cfgBuilder.Cleanup() cfg, repos := cfgBuilder.BuildWithRepoAt(t, t.Name()) locator := config.NewLocator(cfg) diff --git a/internal/gitaly/service/operations/tags_test.go b/internal/gitaly/service/operations/tags_test.go index d51ca29f6..c39ac9693 100644 --- a/internal/gitaly/service/operations/tags_test.go +++ b/internal/gitaly/service/operations/tags_test.go @@ -89,7 +89,7 @@ func testSuccessfulGitHooksForUserDeleteTagRequest(t *testing.T, ctx context.Con } } -func writeAssertObjectTypePreReceiveHook(t *testing.T, cfg config.Cfg) (string, func()) { +func writeAssertObjectTypePreReceiveHook(t *testing.T, cfg config.Cfg) string { t.Helper() hook := fmt.Sprintf(`#!/usr/bin/env ruby @@ -118,15 +118,15 @@ unless out.chomp == expected_object_type abort "pre-receive hook error: expected '#{ref_name}' update of '#{old_value}' (a) -> '#{new_value}' (b) for 'b' to be a '#{expected_object_type}' object, got '#{out}'" end`, cfg.Git.BinPath) - dir, cleanup := testhelper.TempDir(t) + dir := testhelper.TempDir(t) hookPath := filepath.Join(dir, "pre-receive") require.NoError(t, ioutil.WriteFile(hookPath, []byte(hook), 0755)) - return hookPath, cleanup + return hookPath } -func writeAssertObjectTypeUpdateHook(t *testing.T, cfg config.Cfg) (string, func()) { +func writeAssertObjectTypeUpdateHook(t *testing.T, cfg config.Cfg) string { t.Helper() hook := fmt.Sprintf(`#!/usr/bin/env ruby @@ -151,12 +151,12 @@ unless out.chomp == expected_object_type abort "update hook error: expected '#{ref_name}' update of '#{old_value}' (a) -> '#{new_value}' (b) for 'b' to be a '#{expected_object_type}' object, got '#{out}'" end`, cfg.Git.BinPath) - dir, cleanup := testhelper.TempDir(t) + dir := testhelper.TempDir(t) hookPath := filepath.Join(dir, "pre-receive") require.NoError(t, ioutil.WriteFile(hookPath, []byte(hook), 0755)) - return hookPath, cleanup + return hookPath } func TestSuccessfulUserCreateTagRequest(t *testing.T) { @@ -176,11 +176,9 @@ func testSuccessfulUserCreateTagRequest(t *testing.T, ctx context.Context) { inputTagName := "to-be-créated-soon" - preReceiveHook, cleanup := writeAssertObjectTypePreReceiveHook(t, cfg) - defer cleanup() + preReceiveHook := writeAssertObjectTypePreReceiveHook(t, cfg) - updateHook, cleanup := writeAssertObjectTypeUpdateHook(t, cfg) - defer cleanup() + updateHook := writeAssertObjectTypeUpdateHook(t, cfg) testCases := []struct { desc string @@ -265,8 +263,7 @@ func TestUserCreateTagWithTransaction(t *testing.T) { repo := localrepo.New(git.NewExecCommandFactory(cfg), repoProto, cfg) - hooksOutputDir, cleanup := testhelper.TempDir(t) - defer cleanup() + hooksOutputDir := testhelper.TempDir(t) hooksOutputPath := filepath.Join(hooksOutputDir, "output") // We're creating a set of custom hooks which simply @@ -433,11 +430,9 @@ func TestSuccessfulUserCreateTagRequestAnnotatedLightweightDisambiguation(t *tes func testSuccessfulUserCreateTagRequestAnnotatedLightweightDisambiguation(t *testing.T, ctx context.Context) { ctx, cfg, repo, repoPath, client := setupOperationsService(t, ctx) - preReceiveHook, cleanup := writeAssertObjectTypePreReceiveHook(t, cfg) - defer cleanup() + preReceiveHook := writeAssertObjectTypePreReceiveHook(t, cfg) - updateHook, cleanup := writeAssertObjectTypeUpdateHook(t, cfg) - defer cleanup() + updateHook := writeAssertObjectTypeUpdateHook(t, cfg) testCases := []struct { desc string @@ -608,11 +603,9 @@ func TestSuccessfulUserCreateTagRequestToNonCommit(t *testing.T) { inputTagName := "to-be-créated-soon" - preReceiveHook, cleanup := writeAssertObjectTypePreReceiveHook(t, cfg) - defer cleanup() + preReceiveHook := writeAssertObjectTypePreReceiveHook(t, cfg) - updateHook, cleanup := writeAssertObjectTypeUpdateHook(t, cfg) - defer cleanup() + updateHook := writeAssertObjectTypeUpdateHook(t, cfg) testCases := []struct { desc string @@ -721,11 +714,9 @@ func TestSuccessfulUserCreateTagNestedTags(t *testing.T) { repo := localrepo.New(git.NewExecCommandFactory(cfg), repoProto, cfg) - preReceiveHook, cleanup := writeAssertObjectTypePreReceiveHook(t, cfg) - defer cleanup() + preReceiveHook := writeAssertObjectTypePreReceiveHook(t, cfg) - updateHook, cleanup := writeAssertObjectTypeUpdateHook(t, cfg) - defer cleanup() + updateHook := writeAssertObjectTypeUpdateHook(t, cfg) testCases := []struct { desc string diff --git a/internal/gitaly/service/remote/fetch_internal_remote_test.go b/internal/gitaly/service/remote/fetch_internal_remote_test.go index c7e413ed7..23f2f19b9 100644 --- a/internal/gitaly/service/remote/fetch_internal_remote_test.go +++ b/internal/gitaly/service/remote/fetch_internal_remote_test.go @@ -65,8 +65,7 @@ func listenGitalySSHCalls(t *testing.T, conf config.Cfg) func() []GitalySSHParam updatedPath := initialPath + "-actual" require.NoError(t, os.Rename(initialPath, updatedPath)) - tmpDir, clean := testhelper.TempDir(t) - t.Cleanup(clean) + tmpDir := testhelper.TempDir(t) script := fmt.Sprintf(` #!/bin/sh @@ -160,7 +159,6 @@ func TestSuccessfulFetchInternalRemote(t *testing.T) { gittest.CreateCommit(t, remoteCfg, remoteRepoPath, "master", nil) localCfgBuilder := testcfg.NewGitalyCfgBuilder(testcfg.WithStorages("gitaly-1")) - t.Cleanup(localCfgBuilder.Cleanup) localCfg, localRepos := localCfgBuilder.BuildWithRepoAt(t, "stub") localRepo := localRepos[0] diff --git a/internal/gitaly/service/repository/archive_test.go b/internal/gitaly/service/repository/archive_test.go index 4f00c45af..cb369c5d9 100644 --- a/internal/gitaly/service/repository/archive_test.go +++ b/internal/gitaly/service/repository/archive_test.go @@ -181,8 +181,7 @@ func TestGetArchiveWithLfsSuccess(t *testing.T) { LfsBody: lfsBody, } - gitlabShellDir, cleanup := testhelper.TempDir(t) - defer cleanup() + gitlabShellDir := testhelper.TempDir(t) defer func(cfg config.Cfg) { config.Config = cfg @@ -439,8 +438,7 @@ func TestGetArchivePathInjection(t *testing.T) { defer cancel() // Adding a temp directory representing the .ssh directory - sshDirectory, cleanup := testhelper.TempDir(t) - defer cleanup() + sshDirectory := testhelper.TempDir(t) // Adding an empty authorized_keys file authorizedKeysPath := filepath.Join(sshDirectory, "authorized_keys") diff --git a/internal/gitaly/service/repository/create_from_snapshot_test.go b/internal/gitaly/service/repository/create_from_snapshot_test.go index 97c8fa7b5..9c31da7ca 100644 --- a/internal/gitaly/service/repository/create_from_snapshot_test.go +++ b/internal/gitaly/service/repository/create_from_snapshot_test.go @@ -84,8 +84,7 @@ func TestCreateRepositoryFromSnapshotSuccess(t *testing.T) { defer srv.Close() const storageName = "default" - storagePath, cleanTempDir := testhelper.TempDir(t) - defer cleanTempDir() + storagePath := testhelper.TempDir(t) repoRelativePath := filepath.Join("non-existing-parent", "repository") req := &gitalypb.CreateRepositoryFromSnapshotRequest{ diff --git a/internal/gitaly/service/repository/fetch_remote_test.go b/internal/gitaly/service/repository/fetch_remote_test.go index 67102e5b8..28108f3f9 100644 --- a/internal/gitaly/service/repository/fetch_remote_test.go +++ b/internal/gitaly/service/repository/fetch_remote_test.go @@ -84,8 +84,7 @@ func TestFetchRemoteSuccess(t *testing.T) { } func TestFetchRemote_sshCommand(t *testing.T) { - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) // We ain't got a nice way to intercept the SSH call, so we just write a custom git command // which simply prints the GIT_SSH_COMMAND environment variable. diff --git a/internal/gitaly/service/repository/fork_test.go b/internal/gitaly/service/repository/fork_test.go index 039857f86..558a157a8 100644 --- a/internal/gitaly/service/repository/fork_test.go +++ b/internal/gitaly/service/repository/fork_test.go @@ -170,7 +170,7 @@ func TestFailedCreateForkRequestDueToExistingTarget(t *testing.T) { } func injectCustomCATestCerts(t *testing.T) (*x509.CertPool, testhelper.Cleanup) { - certFile, keyFile, removeCerts := testhelper.GenerateTestCerts(t) + certFile, keyFile := testhelper.GenerateCerts(t) oldTLSConfig := config.Config.TLS @@ -181,7 +181,6 @@ func injectCustomCATestCerts(t *testing.T) (*x509.CertPool, testhelper.Cleanup) cleanup := func() { config.Config.TLS = oldTLSConfig revertEnv() - removeCerts() } caPEMBytes, err := ioutil.ReadFile(certFile) diff --git a/internal/gitaly/service/repository/redirecting_test_server_test.go b/internal/gitaly/service/repository/redirecting_test_server_test.go index 1c8957502..159a05767 100644 --- a/internal/gitaly/service/repository/redirecting_test_server_test.go +++ b/internal/gitaly/service/repository/redirecting_test_server_test.go @@ -38,8 +38,7 @@ func StartRedirectingTestServer() (*RedirectingTestServerState, *httptest.Server } func TestRedirectingServerRedirects(t *testing.T) { - dir, cleanup := testhelper.TempDir(t) - defer cleanup() + dir := testhelper.TempDir(t) httpServerState, redirectingServer := StartRedirectingTestServer() diff --git a/internal/gitaly/service/repository/replicate_test.go b/internal/gitaly/service/repository/replicate_test.go index 3d993edaa..578076e73 100644 --- a/internal/gitaly/service/repository/replicate_test.go +++ b/internal/gitaly/service/repository/replicate_test.go @@ -29,8 +29,7 @@ import ( ) func TestReplicateRepository(t *testing.T) { - tmpPath, cleanup := testhelper.TempDir(t) - defer cleanup() + tmpPath := testhelper.TempDir(t) replicaPath := filepath.Join(tmpPath, "replica") require.NoError(t, os.MkdirAll(replicaPath, 0755)) @@ -231,8 +230,7 @@ func TestReplicateRepository_BadRepository(t *testing.T) { }, } { t.Run(tc.desc, func(t *testing.T) { - targetStorageRoot, cleanup := testhelper.TempDir(t) - defer cleanup() + targetStorageRoot := testhelper.TempDir(t) defer func(storages []config.Storage) { config.Config.Storages = storages @@ -303,8 +301,7 @@ func TestReplicateRepository_BadRepository(t *testing.T) { } func TestReplicateRepository_FailedFetchInternalRemote(t *testing.T) { - tmpPath, cleanup := testhelper.TempDir(t) - defer cleanup() + tmpPath := testhelper.TempDir(t) replicaPath := filepath.Join(tmpPath, "replica") require.NoError(t, os.MkdirAll(replicaPath, 0755)) diff --git a/internal/gitaly/service/repository/repository_test.go b/internal/gitaly/service/repository/repository_test.go index 22db3659a..9c127781d 100644 --- a/internal/gitaly/service/repository/repository_test.go +++ b/internal/gitaly/service/repository/repository_test.go @@ -15,8 +15,7 @@ import ( ) func TestRepositoryExists(t *testing.T) { - storageOtherDir, cleanup := testhelper.TempDir(t) - defer cleanup() + storageOtherDir := testhelper.TempDir(t) // Setup storage paths testStorages := []config.Storage{ diff --git a/internal/gitaly/service/smarthttp/receive_pack_test.go b/internal/gitaly/service/smarthttp/receive_pack_test.go index e63aa3b05..2b16b6f57 100644 --- a/internal/gitaly/service/smarthttp/receive_pack_test.go +++ b/internal/gitaly/service/smarthttp/receive_pack_test.go @@ -162,8 +162,7 @@ func TestFailedReceivePackRequestWithGitOpts(t *testing.T) { func TestFailedReceivePackRequestDueToHooksFailure(t *testing.T) { cfg, repo, _ := testcfg.BuildWithRepo(t) - hookDir, cleanup := testhelper.TempDir(t) - defer cleanup() + hookDir := testhelper.TempDir(t) defer func(override string) { hooks.Override = override @@ -385,8 +384,7 @@ func TestPostReceivePackToHooks(t *testing.T) { ) var cleanup func() - cfg.GitlabShell.Dir, cleanup = testhelper.TempDir(t) - defer cleanup() + cfg.GitlabShell.Dir = testhelper.TempDir(t) cfg.Auth.Token = "abc123" cfg.Gitlab.SecretFile = testhelper.WriteShellSecretFile(t, cfg.GitlabShell.Dir, secretToken) @@ -493,8 +491,7 @@ func testPostReceiveWithTransactionsViaPraefect(t *testing.T, ctx context.Contex serverURL, cleanup := testhelper.NewGitlabTestServer(t, opts) defer cleanup() - gitlabShellDir, cleanup := testhelper.TempDir(t) - defer cleanup() + gitlabShellDir := testhelper.TempDir(t) cfg.GitlabShell.Dir = gitlabShellDir cfg.Gitlab.URL = serverURL cfg.Gitlab.HTTPSettings.User = gitlabUser diff --git a/internal/gitaly/service/smarthttp/upload_pack_test.go b/internal/gitaly/service/smarthttp/upload_pack_test.go index 4e2e9db37..a6ee67429 100644 --- a/internal/gitaly/service/smarthttp/upload_pack_test.go +++ b/internal/gitaly/service/smarthttp/upload_pack_test.go @@ -235,9 +235,7 @@ func TestSuccessfulUploadPackDeepenRequest(t *testing.T) { func TestUploadPackWithPackObjectsHook(t *testing.T) { cfg, repo, repoPath := testcfg.BuildWithRepo(t) - var cleanup func() - cfg.BinDir, cleanup = testhelper.TempDir(t) - defer cleanup() + cfg.BinDir = testhelper.TempDir(t) outputPath := filepath.Join(cfg.BinDir, "output") hookScript := fmt.Sprintf("#!/bin/sh\necho 'I was invoked' >'%s'\nshift\nexec '%s' \"$@\"\n", outputPath, cfg.Git.BinPath) diff --git a/internal/gitaly/service/ssh/receive_pack_test.go b/internal/gitaly/service/ssh/receive_pack_test.go index f35adec0b..8675c2876 100644 --- a/internal/gitaly/service/ssh/receive_pack_test.go +++ b/internal/gitaly/service/ssh/receive_pack_test.go @@ -187,8 +187,7 @@ func TestReceivePackPushHookFailure(t *testing.T) { serverSocketPath, stop := runSSHServer(t, cfg) defer stop() - hookDir, cleanup := testhelper.TempDir(t) - defer cleanup() + hookDir := testhelper.TempDir(t) defer func(old string) { hooks.Override = old }(hooks.Override) hooks.Override = hookDir @@ -265,8 +264,7 @@ func TestSSHReceivePackToHooks(t *testing.T) { readProto, cfg := gittest.EnableGitProtocolV2Support(t, cfg) - tempGitlabShellDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempGitlabShellDir := testhelper.TempDir(t) cfg.GitlabShell.Dir = tempGitlabShellDir diff --git a/internal/gitaly/service/ssh/upload_pack_test.go b/internal/gitaly/service/ssh/upload_pack_test.go index 31d2dcf72..fcf53b9aa 100644 --- a/internal/gitaly/service/ssh/upload_pack_test.go +++ b/internal/gitaly/service/ssh/upload_pack_test.go @@ -211,8 +211,7 @@ func TestUploadPackCloneSuccess(t *testing.T) { ) defer stop() - localRepoPath, cleanup := testhelper.TempDir(t) - defer cleanup() + localRepoPath := testhelper.TempDir(t) tests := []struct { cmd *exec.Cmd @@ -256,8 +255,7 @@ func TestUploadPackCloneSuccess(t *testing.T) { func TestUploadPackWithPackObjectsHook(t *testing.T) { cfg, repo, _ := testcfg.BuildWithRepo(t) - filterDir, cleanup := testhelper.TempDir(t) - defer cleanup() + filterDir := testhelper.TempDir(t) outputPath := filepath.Join(filterDir, "output") cfg.BinDir = filterDir @@ -282,8 +280,7 @@ exec '%s' "$@" serverSocketPath, stop := runSSHServer(t, cfg) defer stop() - localRepoPath, cleanup := testhelper.TempDir(t) - defer cleanup() + localRepoPath := testhelper.TempDir(t) err := cloneCommand{ repository: repo, @@ -381,8 +378,7 @@ func TestUploadPackCloneWithPartialCloneFilter(t *testing.T) { // Run the clone with filtering enabled in both runs. The only // difference is that in the first run, we have the // UploadPackFilter flag disabled. - localPath, cleanup := testhelper.TempDir(t) - defer cleanup() + localPath := testhelper.TempDir(t) cmd := cloneCommand{ repository: repo, @@ -406,8 +402,7 @@ func TestUploadPackCloneSuccessWithGitProtocol(t *testing.T) { testhelper.ConfigureGitalySSHBin(t, cfg) testhelper.ConfigureGitalyHooksBin(t, cfg) - localRepoPath, cleanup := testhelper.TempDir(t) - defer cleanup() + localRepoPath := testhelper.TempDir(t) tests := []struct { cmd *exec.Cmd @@ -456,8 +451,7 @@ func TestUploadPackCloneHideTags(t *testing.T) { serverSocketPath, stop := runSSHServer(t, cfg) defer stop() - localRepoPath, cleanup := testhelper.TempDir(t) - defer cleanup() + localRepoPath := testhelper.TempDir(t) cmd := exec.Command(cfg.Git.BinPath, "clone", "--mirror", "git@localhost:test/test.git", localRepoPath) cmd.Env = os.Environ() @@ -485,8 +479,7 @@ func TestUploadPackCloneFailure(t *testing.T) { serverSocketPath, stop := runSSHServer(t, cfg) defer stop() - localRepoPath, cleanup := testhelper.TempDir(t) - defer cleanup() + localRepoPath := testhelper.TempDir(t) cmd := cloneCommand{ repository: &gitalypb.Repository{ diff --git a/internal/praefect/grpc-proxy/proxy/handler_test.go b/internal/praefect/grpc-proxy/proxy/handler_test.go index 833f9ac01..e20678708 100644 --- a/internal/praefect/grpc-proxy/proxy/handler_test.go +++ b/internal/praefect/grpc-proxy/proxy/handler_test.go @@ -389,8 +389,7 @@ func TestProxyErrorPropagation(t *testing.T) { }, } { t.Run(tc.desc, func(t *testing.T) { - tmpDir, clean := testhelper.TempDir(t) - defer clean() + tmpDir := testhelper.TempDir(t) backendListener, err := net.Listen("unix", filepath.Join(tmpDir, "backend")) require.NoError(t, err) diff --git a/internal/praefect/info_service_test.go b/internal/praefect/info_service_test.go index df9c16b70..123c09d9d 100644 --- a/internal/praefect/info_service_test.go +++ b/internal/praefect/info_service_test.go @@ -24,8 +24,7 @@ import ( func TestInfoService_RepositoryReplicas(t *testing.T) { cfg := gconfig.Config - tempDir, cleanupTempDir := testhelper.TempDir(t) - defer cleanupTempDir() + tempDir := testhelper.TempDir(t) cfg.Storages = []gconfig.Storage{{Name: "gitaly-1"}, {Name: "gitaly-2"}, {Name: "gitaly-3"}} for i := range cfg.Storages { diff --git a/internal/praefect/replicator_pg_test.go b/internal/praefect/replicator_pg_test.go index 934e4a337..25cc508a3 100644 --- a/internal/praefect/replicator_pg_test.go +++ b/internal/praefect/replicator_pg_test.go @@ -31,8 +31,7 @@ func TestReplicatorInvalidSourceRepository(t *testing.T) { ctx, cancel := testhelper.Context() defer cancel() - tmp, cleanDir := testhelper.TempDir(t) - defer cleanDir() + tmp := testhelper.TempDir(t) socketPath := filepath.Join(tmp, "socket") ln, err := net.Listen("unix", socketPath) diff --git a/internal/praefect/replicator_test.go b/internal/praefect/replicator_test.go index 80ec36d48..e7de290e4 100644 --- a/internal/praefect/replicator_test.go +++ b/internal/praefect/replicator_test.go @@ -96,8 +96,7 @@ func testMain(m *testing.M) int { func TestReplMgr_ProcessBacklog(t *testing.T) { backupStorageName := "backup" - backupDir, cleanup := testhelper.TempDir(t) - defer cleanup() + backupDir := testhelper.TempDir(t) defer func(oldStorages []gitaly_config.Storage) { gitaly_config.Config.Storages = oldStorages }(gitaly_config.Config.Storages) @@ -613,8 +612,7 @@ func getChecksumFunc(ctx context.Context, client gitalypb.RepositoryServiceClien func TestProcessBacklog_FailedJobs(t *testing.T) { backupStorageName := "backup" - backupDir, cleanup := testhelper.TempDir(t) - defer cleanup() + backupDir := testhelper.TempDir(t) defer func(oldStorages []gitaly_config.Storage) { gitaly_config.Config.Storages = oldStorages }(gitaly_config.Config.Storages) gitaly_config.Config.Storages = append(gitaly_config.Config.Storages, gitaly_config.Storage{ @@ -743,8 +741,7 @@ func TestProcessBacklog_FailedJobs(t *testing.T) { func TestProcessBacklog_Success(t *testing.T) { defer func(oldStorages []gitaly_config.Storage) { gitaly_config.Config.Storages = oldStorages }(gitaly_config.Config.Storages) - backupDir, cleanup := testhelper.TempDir(t) - defer cleanup() + backupDir := testhelper.TempDir(t) gitaly_config.Config.Storages = append(gitaly_config.Config.Storages, gitaly_config.Storage{ Name: "backup", diff --git a/internal/praefect/repository_exists_test.go b/internal/praefect/repository_exists_test.go index 5eea4bd84..4bf760236 100644 --- a/internal/praefect/repository_exists_test.go +++ b/internal/praefect/repository_exists_test.go @@ -79,8 +79,7 @@ func TestRepositoryExistsStreamInterceptor(t *testing.T) { electionStrategy = config.ElectionStrategySQL } - tmp, cleanDir := testhelper.TempDir(t) - defer cleanDir() + tmp := testhelper.TempDir(t) ln, err := net.Listen("unix", filepath.Join(tmp, "praefect")) require.NoError(t, err) diff --git a/internal/praefect/server_factory_test.go b/internal/praefect/server_factory_test.go index e28561f08..40cc7d741 100644 --- a/internal/praefect/server_factory_test.go +++ b/internal/praefect/server_factory_test.go @@ -67,8 +67,7 @@ func TestServerFactory(t *testing.T) { gitalyAddr, err := starter.ComposeEndpoint(gitalyListener.Addr().Network(), gitalyListener.Addr().String()) require.NoError(t, err) - certFile, keyFile, remove := testhelper.GenerateTestCerts(t) - defer remove() + certFile, keyFile := testhelper.GenerateCerts(t) conf := config.Config{ TLS: gconfig.TLS{ diff --git a/internal/praefect/server_test.go b/internal/praefect/server_test.go index 1e3531510..c36e97d57 100644 --- a/internal/praefect/server_test.go +++ b/internal/praefect/server_test.go @@ -111,8 +111,7 @@ func TestGitalyServerInfo(t *testing.T) { require.NoError(t, err) t.Run("gitaly responds with ok", func(t *testing.T) { - tempDir, cleanupTempDir := testhelper.TempDir(t) - defer cleanupTempDir() + tempDir := testhelper.TempDir(t) cfg := gconfig.Config cfg.Storages = []gconfig.Storage{{Name: "praefect-internal-1"}, {Name: "praefect-internal-2"}} @@ -460,7 +459,6 @@ func TestRemoveRepository(t *testing.T) { for i, name := range []string{"gitaly-1", "gitaly-2", "gitaly-3"} { cfgBuilder := testcfg.NewGitalyCfgBuilder(testcfg.WithStorages(name)) - defer cfgBuilder.Cleanup() gitalyCfgs[i], repos[i] = cfgBuilder.BuildWithRepoAt(t, "test-repository") gitalyAddr := testserver.RunGitalyServer(t, gitalyCfgs[i], nil, setup.RegisterAll) @@ -549,7 +547,6 @@ func TestRenameRepository(t *testing.T) { const relativePath = "test-repository" cfgBuilder := testcfg.NewGitalyCfgBuilder(testcfg.WithStorages(storageName)) - defer cfgBuilder.Cleanup() gitalyCfg, repos := cfgBuilder.BuildWithRepoAt(t, relativePath) if repo == nil { repo = repos[0] diff --git a/internal/safe/file_writer_test.go b/internal/safe/file_writer_test.go index 308e3eb7a..7899fd0a9 100644 --- a/internal/safe/file_writer_test.go +++ b/internal/safe/file_writer_test.go @@ -15,8 +15,7 @@ import ( ) func TestFile(t *testing.T) { - dir, cleanup := testhelper.TempDir(t) - defer cleanup() + dir := testhelper.TempDir(t) filePath := filepath.Join(dir, "test_file_contents") fileContents := "very important contents" @@ -41,8 +40,7 @@ func TestFile(t *testing.T) { } func TestFileRace(t *testing.T) { - dir, cleanup := testhelper.TempDir(t) - defer cleanup() + dir := testhelper.TempDir(t) filePath := filepath.Join(dir, "test_file_contents") @@ -68,8 +66,7 @@ func TestFileRace(t *testing.T) { } func TestFileCloseBeforeCommit(t *testing.T) { - dir, cleanup := testhelper.TempDir(t) - defer cleanup() + dir := testhelper.TempDir(t) dstPath := filepath.Join(dir, "safety_meow") sf, err := safe.CreateFileWriter(dstPath) @@ -87,8 +84,7 @@ func TestFileCloseBeforeCommit(t *testing.T) { } func TestFileCommitBeforeClose(t *testing.T) { - dir, cleanup := testhelper.TempDir(t) - defer cleanup() + dir := testhelper.TempDir(t) dstPath := filepath.Join(dir, "safety_meow") sf, err := safe.CreateFileWriter(dstPath) diff --git a/internal/streamcache/cache_test.go b/internal/streamcache/cache_test.go index ac64955c8..9770c4e89 100644 --- a/internal/streamcache/cache_test.go +++ b/internal/streamcache/cache_test.go @@ -21,8 +21,7 @@ import ( ) func TestCache_writeOneReadMultiple(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) c := New(tmp, time.Minute, log.Default()) defer c.Stop() @@ -52,8 +51,7 @@ func TestCache_writeOneReadMultiple(t *testing.T) { } func TestCache_manyConcurrentWrites(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) c := New(tmp, time.Minute, log.Default()) defer c.Stop() @@ -132,8 +130,7 @@ func requireCacheEntries(t *testing.T, _c Cache, n int) { } func TestCache_deletedFile(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) c := New(tmp, time.Hour, log.Default()) defer c.Stop() @@ -170,8 +167,7 @@ func TestCache_deletedFile(t *testing.T) { } func TestCache_scope(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) const ( N = 100 @@ -247,8 +243,7 @@ func (cl *clock) advance() { } func TestCache_diskCleanup(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) const ( key = "test key" @@ -297,8 +292,7 @@ func TestCache_diskCleanup(t *testing.T) { } func TestCache_failedWrite(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) c := New(tmp, time.Hour, log.Default()) defer c.Stop() @@ -345,8 +339,7 @@ func TestCache_failedWrite(t *testing.T) { } func TestCache_failCreateFile(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) c := New(tmp, time.Hour, log.Default()) defer c.Stop() @@ -359,8 +352,7 @@ func TestCache_failCreateFile(t *testing.T) { } func TestCache_unWriteableFile(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) c := New(tmp, time.Hour, log.Default()) defer c.Stop() @@ -385,8 +377,7 @@ func TestCache_unWriteableFile(t *testing.T) { } func TestCache_unCloseableFile(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) c := New(tmp, time.Hour, log.Default()) defer c.Stop() @@ -412,8 +403,7 @@ func TestCache_unCloseableFile(t *testing.T) { } func TestCache_cannotOpenFileForReading(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) c := New(tmp, time.Hour, log.Default()) defer c.Stop() diff --git a/internal/streamcache/filestore_test.go b/internal/streamcache/filestore_test.go index efe1a245a..c4f6a4c41 100644 --- a/internal/streamcache/filestore_test.go +++ b/internal/streamcache/filestore_test.go @@ -15,8 +15,7 @@ import ( ) func TestFilestoreCreate(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) fs := newFilestore(tmp, 0, time.Sleep, log.Default()) defer fs.Stop() @@ -39,8 +38,7 @@ func TestFilestoreCreate(t *testing.T) { } func TestFilestoreCreate_concurrency(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) fs := newFilestore(tmp, time.Hour, time.Sleep, log.Default()) defer fs.Stop() @@ -74,8 +72,7 @@ func TestFilestoreCreate_concurrency(t *testing.T) { } func TestFilestoreCreate_uniqueness(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) const ( M = 10 @@ -103,8 +100,7 @@ func TestFilestoreCreate_uniqueness(t *testing.T) { } func TestFilestoreCleanwalk(t *testing.T) { - tmp, cleanTmp := testhelper.TempDir(t) - defer cleanTmp() + tmp := testhelper.TempDir(t) fs := newFilestore(tmp, time.Hour, time.Sleep, log.Default()) defer fs.Stop() diff --git a/internal/testhelper/testcfg/gitaly_builder.go b/internal/testhelper/testcfg/gitaly_builder.go index ea7ce0b75..ed2553730 100644 --- a/internal/testhelper/testcfg/gitaly_builder.go +++ b/internal/testhelper/testcfg/gitaly_builder.go @@ -54,31 +54,12 @@ func NewGitalyCfgBuilder(opts ...Option) GitalyCfgBuilder { // GitalyCfgBuilder automates creation of the gitaly configuration and filesystem structure required. type GitalyCfgBuilder struct { - cfg config.Cfg - cleanups []testhelper.Cleanup + cfg config.Cfg storages []string realLinguist bool } -func (gc *GitalyCfgBuilder) addCleanup(f testhelper.Cleanup) { - gc.cleanups = append(gc.cleanups, f) -} - -// Cleanup releases all resources allocated fot the created config. -// It should be called once the test is done. -func (gc *GitalyCfgBuilder) Cleanup() { - for i := len(gc.cleanups) - 1; i >= 0; i-- { - gc.cleanups[i]() - } -} - -func (gc *GitalyCfgBuilder) tempDir(t testing.TB) string { - tempDir, cleanupTempDir := testhelper.TempDir(t) - gc.addCleanup(cleanupTempDir) - return tempDir -} - // Build setups required filesystem structure, creates and returns configuration of the gitaly service. func (gc *GitalyCfgBuilder) Build(t testing.TB) config.Cfg { t.Helper() @@ -88,7 +69,7 @@ func (gc *GitalyCfgBuilder) Build(t testing.TB) config.Cfg { cfg.SocketPath = "it is a stub to bypass Validate method" } - root := gc.tempDir(t) + root := testhelper.TempDir(t) if cfg.BinDir == "" { cfg.BinDir = filepath.Join(root, "bin.d") @@ -166,7 +147,6 @@ func (gc *GitalyCfgBuilder) BuildWithRepoAt(t testing.TB, relativePath string) ( // Build creates a minimal configuration setup with no options and returns it with cleanup function. func Build(t testing.TB, opts ...Option) config.Cfg { cfgBuilder := NewGitalyCfgBuilder(opts...) - t.Cleanup(cfgBuilder.Cleanup) return cfgBuilder.Build(t) } @@ -175,7 +155,6 @@ func Build(t testing.TB, opts ...Option) config.Cfg { // It also clones test repository at the storage and returns it with the full path to the repository. func BuildWithRepo(t testing.TB, opts ...Option) (config.Cfg, *gitalypb.Repository, string) { cfgBuilder := NewGitalyCfgBuilder(opts...) - t.Cleanup(cfgBuilder.Cleanup) cfg, repos := cfgBuilder.BuildWithRepoAt(t, t.Name()) repoPath := filepath.Join(cfg.Storages[0].Path, repos[0].RelativePath) diff --git a/internal/testhelper/testhelper.go b/internal/testhelper/testhelper.go index cb576d678..342dc9610 100644 --- a/internal/testhelper/testhelper.go +++ b/internal/testhelper/testhelper.go @@ -288,15 +288,18 @@ func AssertPathNotExists(t testing.TB, path string) { } // TempDir is a wrapper around ioutil.TempDir that provides a cleanup function. -func TempDir(t testing.TB) (string, func()) { +func TempDir(t testing.TB) string { if testDirectory == "" { panic("you must call testhelper.Configure() before TempDir()") } tmpDir, err := ioutil.TempDir(testDirectory, "") require.NoError(t, err) + t.Cleanup(func() { + require.NoError(t, os.RemoveAll(tmpDir)) + }) - return tmpDir, func() { require.NoError(t, os.RemoveAll(tmpDir)) } + return tmpDir } // Cleanup functions should be called in a defer statement @@ -331,9 +334,9 @@ func ModifyEnvironment(t testing.TB, key string, value string) func() { } } -// GenerateTestCerts creates a certificate that can be used to establish TLS protected TCP connection. +// GenerateCerts creates a certificate that can be used to establish TLS protected TCP connection. // It returns paths to the file with the certificate and its private key. -func GenerateTestCerts(t *testing.T) (string, string, Cleanup) { +func GenerateCerts(t *testing.T) (string, string) { t.Helper() rootCA := &x509.Certificate{ @@ -366,6 +369,9 @@ func GenerateTestCerts(t *testing.T) (string, string, Cleanup) { certFile, err := ioutil.TempFile(testDirectory, "") require.NoError(t, err) defer MustClose(t, certFile) + t.Cleanup(func() { + require.NoError(t, os.Remove(certFile.Name())) + }) // create chained PEM file with CA and entity cert for _, cert := range [][]byte{entityCert, caCert} { @@ -380,6 +386,9 @@ func GenerateTestCerts(t *testing.T) (string, string, Cleanup) { keyFile, err := ioutil.TempFile(testDirectory, "") require.NoError(t, err) defer MustClose(t, keyFile) + t.Cleanup(func() { + require.NoError(t, os.Remove(keyFile.Name())) + }) entityKeyBytes, err := x509.MarshalECPrivateKey(entityKey) require.NoError(t, err) @@ -391,10 +400,5 @@ func GenerateTestCerts(t *testing.T) (string, string, Cleanup) { }), ) - cleanup := func() { - require.NoError(t, os.Remove(certFile.Name())) - require.NoError(t, os.Remove(keyFile.Name())) - } - - return certFile.Name(), keyFile.Name(), cleanup + return certFile.Name(), keyFile.Name() } diff --git a/internal/testhelper/testserver.go b/internal/testhelper/testserver.go index 906c7b9c7..9e76d157b 100644 --- a/internal/testhelper/testserver.go +++ b/internal/testhelper/testserver.go @@ -151,8 +151,7 @@ func (p *TestServer) Start(t testing.TB) { return } - tempDir, cleanup := TempDir(t) - defer cleanup() + tempDir := TempDir(t) praefectServerSocketPath := GetTemporaryGitalySocketFileName(t) @@ -889,7 +888,7 @@ func NewGitlabTestServer(t testing.TB, options GitlabTestServerOptions) (url str } func startSocketHTTPServer(t testing.TB, mux *http.ServeMux, tlsCfg *tls.Config) (string, func()) { - tempDir, cleanupDir := TempDir(t) + tempDir := TempDir(t) filename := filepath.Join(tempDir, "http-test-server") socketListener, err := net.Listen("unix", filename) @@ -905,7 +904,6 @@ func startSocketHTTPServer(t testing.TB, mux *http.ServeMux, tlsCfg *tls.Config) url := "http+unix://" + filename cleanup := func() { require.NoError(t, server.Close()) - cleanupDir() } return url, cleanup diff --git a/internal/testhelper/testserver/gitaly.go b/internal/testhelper/testserver/gitaly.go index 1d25b9b12..2a9559107 100644 --- a/internal/testhelper/testserver/gitaly.go +++ b/internal/testhelper/testserver/gitaly.go @@ -51,8 +51,7 @@ func RunGitalyServer(t testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server } func runPraefectProxy(t testing.TB, cfg config.Cfg, gitalyAddr, praefectBinPath string) (string, func()) { - tempDir, cleanup := testhelper.TempDir(t) - defer cleanup() + tempDir := testhelper.TempDir(t) praefectServerSocketPath := "unix://" + testhelper.GetTemporaryGitalySocketFileName(t) |