diff options
author | Patrick Steinhardt <psteinhardt@gitlab.com> | 2022-08-10 14:21:29 +0300 |
---|---|---|
committer | Patrick Steinhardt <psteinhardt@gitlab.com> | 2022-08-11 15:08:47 +0300 |
commit | a466659bb61ed28cfce9676c64fa0351e61c5ab7 (patch) | |
tree | efbf325c5a3400de51df3726a7dd9448f0a3918a | |
parent | 1946de54c07b881e072a0d8629a4ffe58ef65edb (diff) |
golangci-lint: Enforce consistent naming of `testing.TB` variables
Enforce consistent naming of `testing.TB` variables, which should be
called `tb`, and adapt tests that violate this rule.
82 files changed, 985 insertions, 982 deletions
diff --git a/.golangci.yml b/.golangci.yml index 3f4398b45..ba25ce105 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -80,7 +80,6 @@ linters-settings: benchmark: begin: false tb: - name: false begin: false issues: diff --git a/client/dial_test.go b/client/dial_test.go index 92b4aa0be..6430be714 100644 --- a/client/dial_test.go +++ b/client/dial_test.go @@ -526,9 +526,9 @@ func (*healthServer) Check(context.Context, *healthpb.HealthCheckRequest) (*heal } // startTCPListener will start a insecure TCP listener on a random unused port -func startTCPListener(t testing.TB, factory func(credentials.TransportCredentials) *grpc.Server) (func(), string) { +func startTCPListener(tb testing.TB, factory func(credentials.TransportCredentials) *grpc.Server) (func(), string) { listener, err := net.Listen("tcp", "localhost:0") - require.NoError(t, err) + require.NoError(tb, err) tcpPort := listener.Addr().(*net.TCPAddr).Port address := fmt.Sprintf("%d", tcpPort) @@ -542,11 +542,11 @@ func startTCPListener(t testing.TB, factory func(credentials.TransportCredential } // startUnixListener will start a unix socket listener using a temporary file -func startUnixListener(t testing.TB, factory func(credentials.TransportCredentials) *grpc.Server) (func(), string) { - serverSocketPath := testhelper.GetTemporaryGitalySocketFileName(t) +func startUnixListener(tb testing.TB, factory func(credentials.TransportCredentials) *grpc.Server) (func(), string) { + serverSocketPath := testhelper.GetTemporaryGitalySocketFileName(tb) listener, err := net.Listen("unix", serverSocketPath) - require.NoError(t, err) + require.NoError(tb, err) grpcServer := factory(insecure.NewCredentials()) go grpcServer.Serve(listener) @@ -558,15 +558,15 @@ func startUnixListener(t testing.TB, factory func(credentials.TransportCredentia // startTLSListener will start a secure TLS listener on a random unused port //go:generate openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -out testdata/gitalycert.pem -keyout testdata/gitalykey.pem -subj "/C=US/ST=California/L=San Francisco/O=GitLab/OU=GitLab-Shell/CN=localhost" -addext "subjectAltName = IP:127.0.0.1, DNS:localhost" -func startTLSListener(t testing.TB, factory func(credentials.TransportCredentials) *grpc.Server) (func(), string) { +func startTLSListener(tb testing.TB, factory func(credentials.TransportCredentials) *grpc.Server) (func(), string) { listener, err := net.Listen("tcp", "localhost:0") - require.NoError(t, err) + require.NoError(tb, err) tcpPort := listener.Addr().(*net.TCPAddr).Port address := fmt.Sprintf("%d", tcpPort) cert, err := tls.LoadX509KeyPair("testdata/gitalycert.pem", "testdata/gitalykey.pem") - require.NoError(t, err) + require.NoError(tb, err) grpcServer := factory( credentials.NewTLS(&tls.Config{ @@ -588,11 +588,11 @@ var listeners = map[string]func(testing.TB, func(credentials.TransportCredential } // startListeners will start all the different listeners used in this test -func startListeners(t testing.TB, factory func(credentials.TransportCredentials) *grpc.Server) (func(), map[string]string) { +func startListeners(tb testing.TB, factory func(credentials.TransportCredentials) *grpc.Server) (func(), map[string]string) { var closers []func() connectionMap := map[string]string{} for k, v := range listeners { - closer, address := v(t, factory) + closer, address := v(tb, factory) closers = append(closers, closer) connectionMap[k] = address } @@ -631,4 +631,6 @@ func TestHealthCheckDialer(t *testing.T) { require.NoError(t, cc.Close()) } -func newLogger(t testing.TB) *logrus.Entry { return logrus.NewEntry(testhelper.NewDiscardingLogger(t)) } +func newLogger(tb testing.TB) *logrus.Entry { + return logrus.NewEntry(testhelper.NewDiscardingLogger(tb)) +} diff --git a/cmd/gitaly-git2go/rebase_test.go b/cmd/gitaly-git2go/rebase_test.go index 54ca7b137..2ef76db62 100644 --- a/cmd/gitaly-git2go/rebase_test.go +++ b/cmd/gitaly-git2go/rebase_test.go @@ -115,17 +115,17 @@ func TestRebase_rebase(t *testing.T) { { desc: "Partially merged branch", branch: "branch-merged-plus-one", - setupRepo: func(t testing.TB, repo *git.Repository) { + setupRepo: func(tb testing.TB, repo *git.Repository) { head, err := lookupCommit(repo, "branch-merged") - require.NoError(t, err) + require.NoError(tb, err) other, err := lookupCommit(repo, "gitaly-rename-test") - require.NoError(t, err) + require.NoError(tb, err) tree, err := other.Tree() - require.NoError(t, err) + require.NoError(tb, err) newOid, err := repo.CreateCommitFromIds("refs/heads/branch-merged-plus-one", &DefaultAuthor, &DefaultAuthor, "Message", tree.Object.Id(), head.Object.Id()) - require.NoError(t, err) - require.Equal(t, "8665d9b4b56f6b8ab8c4128a5549d1820bf68bf5", newOid.String()) + require.NoError(tb, err) + require.Equal(tb, "8665d9b4b56f6b8ab8c4128a5549d1820bf68bf5", newOid.String()) }, commitsAhead: 1, expected: "56bafb70922008232d171b78930be6cdb722bb39", @@ -133,20 +133,20 @@ func TestRebase_rebase(t *testing.T) { { desc: "With upstream merged into", branch: "csv-plus-merge", - setupRepo: func(t testing.TB, repo *git.Repository) { + setupRepo: func(tb testing.TB, repo *git.Repository) { ours, err := lookupCommit(repo, "csv") - require.NoError(t, err) + require.NoError(tb, err) theirs, err := lookupCommit(repo, "b83d6e391c22777fca1ed3012fce84f633d7fed0") - require.NoError(t, err) + require.NoError(tb, err) index, err := repo.MergeCommits(ours, theirs, nil) - require.NoError(t, err) + require.NoError(tb, err) tree, err := index.WriteTreeTo(repo) - require.NoError(t, err) + require.NoError(tb, err) newOid, err := repo.CreateCommitFromIds("refs/heads/csv-plus-merge", &DefaultAuthor, &DefaultAuthor, "Message", tree, ours.Object.Id(), theirs.Object.Id()) - require.NoError(t, err) - require.Equal(t, "5b2d6bd7be0b1b9f7e46b64d02fe9882c133a128", newOid.String()) + require.NoError(tb, err) + require.Equal(tb, "5b2d6bd7be0b1b9f7e46b64d02fe9882c133a128", newOid.String()) }, commitsAhead: 5, // Same as "Multiple commits" expected: "2f8365edc69d3683e22c4209ae9641642d84dd4a", diff --git a/cmd/gitaly-git2go/revert_test.go b/cmd/gitaly-git2go/revert_test.go index cdd8bd6f9..aa3d8df37 100644 --- a/cmd/gitaly-git2go/revert_test.go +++ b/cmd/gitaly-git2go/revert_test.go @@ -77,7 +77,7 @@ func TestRevert_validation(t *testing.T) { func TestRevert_trees(t *testing.T) { testcases := []struct { desc string - setupRepo func(t testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) + setupRepo func(tb testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) expected map[string]string expectedCommitID string expectedErr string @@ -85,16 +85,16 @@ func TestRevert_trees(t *testing.T) { }{ { desc: "trivial revert succeeds", - setupRepo: func(t testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) { - baseOid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithTreeEntries( + setupRepo: func(tb testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) { + baseOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "apple", Mode: "100644"}, gittest.TreeEntry{Path: "b", Content: "banana", Mode: "100644"}, )) - revertOid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithParents(baseOid), gittest.WithTreeEntries( + revertOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithParents(baseOid), gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "apple", Mode: "100644"}, gittest.TreeEntry{Path: "b", Content: "pineapple", Mode: "100644"}, )) - oursOid := gittest.WriteCommit(t, cfg, repoPath, + oursOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithParents(revertOid), gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "apple", Mode: "100644"}, gittest.TreeEntry{Path: "b", Content: "pineapple", Mode: "100644"}, @@ -112,14 +112,14 @@ func TestRevert_trees(t *testing.T) { }, { desc: "conflicting revert fails", - setupRepo: func(t testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) { - baseOid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithTreeEntries( + setupRepo: func(tb testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) { + baseOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "apple", Mode: "100644"}, )) - revertOid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithParents(baseOid), gittest.WithTreeEntries( + revertOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithParents(baseOid), gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "pineapple", Mode: "100644"}, )) - oursOid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithParents(revertOid), gittest.WithTreeEntries( + oursOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithParents(revertOid), gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "carrot", Mode: "100644"}, )) @@ -130,14 +130,14 @@ func TestRevert_trees(t *testing.T) { }, { desc: "empty revert fails", - setupRepo: func(t testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) { - baseOid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithTreeEntries( + setupRepo: func(tb testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) { + baseOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "apple", Mode: "100644"}, )) - revertOid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithParents(baseOid), gittest.WithTreeEntries( + revertOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithParents(baseOid), gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "banana", Mode: "100644"}, )) - oursOid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithParents(revertOid), gittest.WithTreeEntries( + oursOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithParents(revertOid), gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "apple", Mode: "100644"}, )) @@ -148,8 +148,8 @@ func TestRevert_trees(t *testing.T) { }, { desc: "nonexistent ours fails", - setupRepo: func(t testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) { - revertOid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithTreeEntries( + setupRepo: func(tb testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) { + revertOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "apple", Mode: "100644"}, )) @@ -159,8 +159,8 @@ func TestRevert_trees(t *testing.T) { }, { desc: "nonexistent revert fails", - setupRepo: func(t testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) { - oursOid := gittest.WriteCommit(t, cfg, repoPath, gittest.WithTreeEntries( + setupRepo: func(tb testing.TB, cfg config.Cfg, repoPath string) (ours, revert string) { + oursOid := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithTreeEntries( gittest.TreeEntry{Path: "a", Content: "apple", Mode: "100644"}, )) diff --git a/cmd/gitaly-hooks/hooks_test.go b/cmd/gitaly-hooks/hooks_test.go index 949b7f6a4..b5479123c 100644 --- a/cmd/gitaly-hooks/hooks_test.go +++ b/cmd/gitaly-hooks/hooks_test.go @@ -58,13 +58,13 @@ func featureFlags(ctx context.Context) map[featureflag.FeatureFlag]bool { } // envForHooks generates a set of environment variables for gitaly hooks -func envForHooks(t testing.TB, ctx context.Context, cfg config.Cfg, repo *gitalypb.Repository, glHookValues glHookValues, proxyValues proxyValues, gitPushOptions ...string) []string { +func envForHooks(tb testing.TB, ctx context.Context, cfg config.Cfg, repo *gitalypb.Repository, glHookValues glHookValues, proxyValues proxyValues, gitPushOptions ...string) []string { payload, err := git.NewHooksPayload(cfg, repo, nil, &git.UserDetails{ UserID: glHookValues.GLID, Username: glHookValues.GLUsername, Protocol: glHookValues.GLProtocol, }, git.AllHooks, featureFlags(ctx)).Env() - require.NoError(t, err) + require.NoError(tb, err) env := append(command.AllowedEnvironment(os.Environ()), []string{ payload, diff --git a/cmd/gitaly-ssh/auth_test.go b/cmd/gitaly-ssh/auth_test.go index 6c460471d..8a5921432 100644 --- a/cmd/gitaly-ssh/auth_test.go +++ b/cmd/gitaly-ssh/auth_test.go @@ -49,9 +49,9 @@ func TestConnectivity(t *testing.T) { require.NoError(t, os.RemoveAll(relativeSocketPath)) require.NoError(t, os.Symlink(cfg.SocketPath, relativeSocketPath)) - runGitaly := func(t testing.TB, cfg config.Cfg) string { - t.Helper() - return testserver.RunGitalyServer(t, cfg, nil, setup.RegisterAll, testserver.WithDisablePraefect()) + runGitaly := func(tb testing.TB, cfg config.Cfg) string { + tb.Helper() + return testserver.RunGitalyServer(tb, cfg, nil, setup.RegisterAll, testserver.WithDisablePraefect()) } testCases := []struct { diff --git a/cmd/gitaly/check_test.go b/cmd/gitaly/check_test.go index 01df6c00e..f715b7661 100644 --- a/cmd/gitaly/check_test.go +++ b/cmd/gitaly/check_test.go @@ -106,14 +106,14 @@ func TestCheckBadCreds(t *testing.T) { // writeTemporaryGitalyConfigFile writes the given Gitaly configuration into a temporary file and // returns its path. -func writeTemporaryGitalyConfigFile(t testing.TB, cfg config.Cfg) string { - t.Helper() +func writeTemporaryGitalyConfigFile(tb testing.TB, cfg config.Cfg) string { + tb.Helper() - path := filepath.Join(testhelper.TempDir(t), "config.toml") + path := filepath.Join(testhelper.TempDir(tb), "config.toml") contents, err := toml.Marshal(cfg) - require.NoError(t, err) - require.NoError(t, os.WriteFile(path, contents, 0o644)) + require.NoError(tb, err) + require.NoError(tb, os.WriteFile(path, contents, 0o644)) return path } diff --git a/cmd/praefect/subcmd_remove_repository_test.go b/cmd/praefect/subcmd_remove_repository_test.go index 19e53a231..e42bde82e 100644 --- a/cmd/praefect/subcmd_remove_repository_test.go +++ b/cmd/praefect/subcmd_remove_repository_test.go @@ -109,11 +109,11 @@ func TestRemoveRepository_Exec(t *testing.T) { praefectStorage := conf.VirtualStorages[0].Name - repositoryExists := func(t testing.TB, repo *gitalypb.Repository) bool { + repositoryExists := func(tb testing.TB, repo *gitalypb.Repository) bool { response, err := gitalypb.NewRepositoryServiceClient(cc).RepositoryExists(ctx, &gitalypb.RepositoryExistsRequest{ Repository: repo, }) - require.NoError(t, err) + require.NoError(tb, err) return response.GetExists() } diff --git a/cmd/praefect/subcmd_test.go b/cmd/praefect/subcmd_test.go index d6d4883e2..1d506c857 100644 --- a/cmd/praefect/subcmd_test.go +++ b/cmd/praefect/subcmd_test.go @@ -33,13 +33,13 @@ func registerServerService(impl gitalypb.ServerServiceServer) svcRegistrar { } } -func listenAndServe(t testing.TB, svcs []svcRegistrar) (net.Listener, testhelper.Cleanup) { - t.Helper() +func listenAndServe(tb testing.TB, svcs []svcRegistrar) (net.Listener, testhelper.Cleanup) { + tb.Helper() - tmp := testhelper.TempDir(t) + tmp := testhelper.TempDir(tb) ln, err := net.Listen("unix", filepath.Join(tmp, "gitaly")) - require.NoError(t, err) + require.NoError(tb, err) srv := grpc.NewServer() @@ -47,14 +47,14 @@ func listenAndServe(t testing.TB, svcs []svcRegistrar) (net.Listener, testhelper s(srv) } - go func() { require.NoError(t, srv.Serve(ln)) }() - ctx := testhelper.Context(t) + go func() { require.NoError(tb, srv.Serve(ln)) }() + ctx := testhelper.Context(tb) // verify the service is up addr := fmt.Sprintf("%s://%s", ln.Addr().Network(), ln.Addr()) cc, err := grpc.DialContext(ctx, addr, grpc.WithBlock(), grpc.WithTransportCredentials(insecure.NewCredentials())) - require.NoError(t, err) - require.NoError(t, cc.Close()) + require.NoError(tb, err) + require.NoError(tb, cc.Close()) return ln, func() { srv.Stop() diff --git a/internal/backup/backup_test.go b/internal/backup/backup_test.go index 99c52683c..d66fa6902 100644 --- a/internal/backup/backup_test.go +++ b/internal/backup/backup_test.go @@ -36,15 +36,15 @@ func TestManager_Create(t *testing.T) { for _, tc := range []struct { desc string - setup func(t testing.TB) (*gitalypb.Repository, string) + setup func(tb testing.TB) (*gitalypb.Repository, string) createsBundle bool createsCustomHooks bool err error }{ { desc: "no hooks", - setup: func(t testing.TB) (*gitalypb.Repository, string) { - noHooksRepo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + setup: func(tb testing.TB) (*gitalypb.Repository, string) { + noHooksRepo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ RelativePath: "no-hooks", Seed: gittest.SeedGitLabTest, }) @@ -55,13 +55,13 @@ func TestManager_Create(t *testing.T) { }, { desc: "hooks", - setup: func(t testing.TB) (*gitalypb.Repository, string) { - hooksRepo, hooksRepoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + setup: func(tb testing.TB) (*gitalypb.Repository, string) { + hooksRepo, hooksRepoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ RelativePath: "hooks", Seed: gittest.SeedGitLabTest, }) - require.NoError(t, os.Mkdir(filepath.Join(hooksRepoPath, "custom_hooks"), os.ModePerm)) - require.NoError(t, os.WriteFile(filepath.Join(hooksRepoPath, "custom_hooks/pre-commit.sample"), []byte("Some hooks"), os.ModePerm)) + require.NoError(tb, os.Mkdir(filepath.Join(hooksRepoPath, "custom_hooks"), os.ModePerm)) + require.NoError(tb, os.WriteFile(filepath.Join(hooksRepoPath, "custom_hooks/pre-commit.sample"), []byte("Some hooks"), os.ModePerm)) return hooksRepo, hooksRepoPath }, createsBundle: true, @@ -69,8 +69,8 @@ func TestManager_Create(t *testing.T) { }, { desc: "empty repo", - setup: func(t testing.TB) (*gitalypb.Repository, string) { - emptyRepo, repoPath := gittest.CreateRepository(ctx, t, cfg) + setup: func(tb testing.TB) (*gitalypb.Repository, string) { + emptyRepo, repoPath := gittest.CreateRepository(ctx, tb, cfg) return emptyRepo, repoPath }, createsBundle: false, @@ -79,8 +79,8 @@ func TestManager_Create(t *testing.T) { }, { desc: "nonexistent repo", - setup: func(t testing.TB) (*gitalypb.Repository, string) { - emptyRepo, repoPath := gittest.CreateRepository(ctx, t, cfg) + setup: func(tb testing.TB) (*gitalypb.Repository, string) { + emptyRepo, repoPath := gittest.CreateRepository(ctx, tb, cfg) nonexistentRepo := proto.Clone(emptyRepo).(*gitalypb.Repository) nonexistentRepo.RelativePath = "nonexistent" return nonexistentRepo, repoPath @@ -164,8 +164,8 @@ func TestManager_Create_incremental(t *testing.T) { }{ { desc: "no previous backup", - setup: func(t testing.TB, backupRoot string) (*gitalypb.Repository, string) { - repo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + setup: func(tb testing.TB, backupRoot string) (*gitalypb.Repository, string) { + repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ RelativePath: "repo", Seed: gittest.SeedGitLabTest, }) @@ -175,8 +175,8 @@ func TestManager_Create_incremental(t *testing.T) { }, { desc: "previous backup, no updates", - setup: func(t testing.TB, backupRoot string) (*gitalypb.Repository, string) { - repo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + setup: func(tb testing.TB, backupRoot string) (*gitalypb.Repository, string) { + repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ RelativePath: "repo", Seed: gittest.SeedGitLabTest, }) @@ -186,14 +186,14 @@ func TestManager_Create_incremental(t *testing.T) { bundlePath := filepath.Join(backupPath, "001.bundle") refsPath := filepath.Join(backupPath, "001.refs") - require.NoError(t, os.MkdirAll(backupPath, os.ModePerm)) - gittest.Exec(t, cfg, "-C", repoPath, "bundle", "create", bundlePath, "--all") + require.NoError(tb, os.MkdirAll(backupPath, os.ModePerm)) + gittest.Exec(tb, cfg, "-C", repoPath, "bundle", "create", bundlePath, "--all") - refs := gittest.Exec(t, cfg, "-C", repoPath, "show-ref", "--head") - require.NoError(t, os.WriteFile(refsPath, refs, os.ModePerm)) + refs := gittest.Exec(tb, cfg, "-C", repoPath, "show-ref", "--head") + require.NoError(tb, os.WriteFile(refsPath, refs, os.ModePerm)) - require.NoError(t, os.WriteFile(filepath.Join(backupRepoPath, "LATEST"), []byte(backupID), os.ModePerm)) - require.NoError(t, os.WriteFile(filepath.Join(backupPath, "LATEST"), []byte("001"), os.ModePerm)) + require.NoError(tb, os.WriteFile(filepath.Join(backupRepoPath, "LATEST"), []byte(backupID), os.ModePerm)) + require.NoError(tb, os.WriteFile(filepath.Join(backupPath, "LATEST"), []byte("001"), os.ModePerm)) return repo, repoPath }, @@ -201,8 +201,8 @@ func TestManager_Create_incremental(t *testing.T) { }, { desc: "previous backup, updates", - setup: func(t testing.TB, backupRoot string) (*gitalypb.Repository, string) { - repo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + setup: func(tb testing.TB, backupRoot string) (*gitalypb.Repository, string) { + repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ RelativePath: "repo", Seed: gittest.SeedGitLabTest, }) @@ -212,16 +212,16 @@ func TestManager_Create_incremental(t *testing.T) { bundlePath := filepath.Join(backupPath, "001.bundle") refsPath := filepath.Join(backupPath, "001.refs") - require.NoError(t, os.MkdirAll(backupPath, os.ModePerm)) - gittest.Exec(t, cfg, "-C", repoPath, "bundle", "create", bundlePath, "--all") + require.NoError(tb, os.MkdirAll(backupPath, os.ModePerm)) + gittest.Exec(tb, cfg, "-C", repoPath, "bundle", "create", bundlePath, "--all") - refs := gittest.Exec(t, cfg, "-C", repoPath, "show-ref", "--head") - require.NoError(t, os.WriteFile(refsPath, refs, os.ModePerm)) + refs := gittest.Exec(tb, cfg, "-C", repoPath, "show-ref", "--head") + require.NoError(tb, os.WriteFile(refsPath, refs, os.ModePerm)) - require.NoError(t, os.WriteFile(filepath.Join(backupRepoPath, "LATEST"), []byte(backupID), os.ModePerm)) - require.NoError(t, os.WriteFile(filepath.Join(backupPath, "LATEST"), []byte("001"), os.ModePerm)) + require.NoError(tb, os.WriteFile(filepath.Join(backupRepoPath, "LATEST"), []byte(backupID), os.ModePerm)) + require.NoError(tb, os.WriteFile(filepath.Join(backupPath, "LATEST"), []byte("001"), os.ModePerm)) - gittest.WriteCommit(t, cfg, repoPath, gittest.WithBranch("master")) + gittest.WriteCommit(tb, cfg, repoPath, gittest.WithBranch("master")) return repo, repoPath }, @@ -284,21 +284,21 @@ func testManagerRestore(t *testing.T, ctx context.Context) { repoClient := gitalypb.NewRepositoryServiceClient(cc) - createRepo := func(t testing.TB) *gitalypb.Repository { - t.Helper() + createRepo := func(tb testing.TB) *gitalypb.Repository { + tb.Helper() repo := &gitalypb.Repository{ StorageName: "default", - RelativePath: gittest.NewRepositoryName(t, false), + RelativePath: gittest.NewRepositoryName(tb, false), } _, err := repoClient.CreateRepository(ctx, &gitalypb.CreateRepositoryRequest{Repository: repo}) - require.NoError(t, err) + require.NoError(tb, err) // The repository might be created through Praefect and the tests reach into the repository directly // on the filesystem. To ensure the test accesses correct directory, we need to rewrite the relative // path if the repository creation went through Praefect. - repo.RelativePath = gittest.GetReplicaPath(ctx, t, cfg, repo) + repo.RelativePath = gittest.GetReplicaPath(ctx, tb, cfg, repo) return repo } @@ -313,7 +313,7 @@ func testManagerRestore(t *testing.T, ctx context.Context) { for _, tc := range []struct { desc string locators []string - setup func(t testing.TB) (*gitalypb.Repository, *git.Checksum) + setup func(tb testing.TB) (*gitalypb.Repository, *git.Checksum) alwaysCreate bool expectExists bool expectedPaths []string @@ -322,11 +322,11 @@ func testManagerRestore(t *testing.T, ctx context.Context) { { desc: "existing repo, without hooks", locators: []string{"legacy", "pointer"}, - setup: func(t testing.TB) (*gitalypb.Repository, *git.Checksum) { - repo := createRepo(t) - require.NoError(t, os.MkdirAll(filepath.Join(path, repo.RelativePath), os.ModePerm)) + setup: func(tb testing.TB) (*gitalypb.Repository, *git.Checksum) { + repo := createRepo(tb) + require.NoError(tb, os.MkdirAll(filepath.Join(path, repo.RelativePath), os.ModePerm)) bundlePath := filepath.Join(path, repo.RelativePath+".bundle") - gittest.BundleRepo(t, cfg, repoPath, bundlePath) + gittest.BundleRepo(tb, cfg, repoPath, bundlePath) return repo, repoChecksum }, @@ -335,13 +335,13 @@ func testManagerRestore(t *testing.T, ctx context.Context) { { desc: "existing repo, with hooks", locators: []string{"legacy", "pointer"}, - setup: func(t testing.TB) (*gitalypb.Repository, *git.Checksum) { - repo := createRepo(t) + setup: func(tb testing.TB) (*gitalypb.Repository, *git.Checksum) { + repo := createRepo(tb) bundlePath := filepath.Join(path, repo.RelativePath+".bundle") customHooksPath := filepath.Join(path, repo.RelativePath, "custom_hooks.tar") - require.NoError(t, os.MkdirAll(filepath.Join(path, repo.RelativePath), os.ModePerm)) - gittest.BundleRepo(t, cfg, repoPath, bundlePath) - testhelper.CopyFile(t, "../gitaly/service/repository/testdata/custom_hooks.tar", customHooksPath) + require.NoError(tb, os.MkdirAll(filepath.Join(path, repo.RelativePath), os.ModePerm)) + gittest.BundleRepo(tb, cfg, repoPath, bundlePath) + testhelper.CopyFile(tb, "../gitaly/service/repository/testdata/custom_hooks.tar", customHooksPath) return repo, repoChecksum }, @@ -355,8 +355,8 @@ func testManagerRestore(t *testing.T, ctx context.Context) { { desc: "missing bundle", locators: []string{"legacy", "pointer"}, - setup: func(t testing.TB) (*gitalypb.Repository, *git.Checksum) { - repo := createRepo(t) + setup: func(tb testing.TB) (*gitalypb.Repository, *git.Checksum) { + repo := createRepo(tb) return repo, nil }, expectedErrAs: ErrSkipped, @@ -364,8 +364,8 @@ func testManagerRestore(t *testing.T, ctx context.Context) { { desc: "missing bundle, always create", locators: []string{"legacy", "pointer"}, - setup: func(t testing.TB) (*gitalypb.Repository, *git.Checksum) { - repo := createRepo(t) + setup: func(tb testing.TB) (*gitalypb.Repository, *git.Checksum) { + repo := createRepo(tb) return repo, new(git.Checksum) }, alwaysCreate: true, @@ -374,15 +374,15 @@ func testManagerRestore(t *testing.T, ctx context.Context) { { desc: "nonexistent repo", locators: []string{"legacy", "pointer"}, - setup: func(t testing.TB) (*gitalypb.Repository, *git.Checksum) { + setup: func(tb testing.TB) (*gitalypb.Repository, *git.Checksum) { repo := &gitalypb.Repository{ StorageName: "default", - RelativePath: gittest.NewRepositoryName(t, false), + RelativePath: gittest.NewRepositoryName(tb, false), } - require.NoError(t, os.MkdirAll(filepath.Dir(filepath.Join(path, repo.RelativePath)), os.ModePerm)) + require.NoError(tb, os.MkdirAll(filepath.Dir(filepath.Join(path, repo.RelativePath)), os.ModePerm)) bundlePath := filepath.Join(path, repo.RelativePath+".bundle") - gittest.BundleRepo(t, cfg, repoPath, bundlePath) + gittest.BundleRepo(tb, cfg, repoPath, bundlePath) return repo, repoChecksum }, @@ -391,16 +391,16 @@ func testManagerRestore(t *testing.T, ctx context.Context) { { desc: "single incremental", locators: []string{"pointer"}, - setup: func(t testing.TB) (*gitalypb.Repository, *git.Checksum) { + setup: func(tb testing.TB) (*gitalypb.Repository, *git.Checksum) { const backupID = "abc123" - repo := createRepo(t) + repo := createRepo(tb) repoBackupPath := filepath.Join(path, repo.RelativePath) backupPath := filepath.Join(repoBackupPath, backupID) - require.NoError(t, os.MkdirAll(backupPath, os.ModePerm)) - require.NoError(t, os.WriteFile(filepath.Join(repoBackupPath, "LATEST"), []byte(backupID), os.ModePerm)) - require.NoError(t, os.WriteFile(filepath.Join(backupPath, "LATEST"), []byte("001"), os.ModePerm)) + require.NoError(tb, os.MkdirAll(backupPath, os.ModePerm)) + require.NoError(tb, os.WriteFile(filepath.Join(repoBackupPath, "LATEST"), []byte(backupID), os.ModePerm)) + require.NoError(tb, os.WriteFile(filepath.Join(backupPath, "LATEST"), []byte("001"), os.ModePerm)) bundlePath := filepath.Join(backupPath, "001.bundle") - gittest.BundleRepo(t, cfg, repoPath, bundlePath) + gittest.BundleRepo(tb, cfg, repoPath, bundlePath) return repo, repoChecksum }, @@ -409,44 +409,44 @@ func testManagerRestore(t *testing.T, ctx context.Context) { { desc: "many incrementals", locators: []string{"pointer"}, - setup: func(t testing.TB) (*gitalypb.Repository, *git.Checksum) { + setup: func(tb testing.TB) (*gitalypb.Repository, *git.Checksum) { const backupID = "abc123" - expected := createRepo(t) + expected := createRepo(tb) expectedRepoPath := filepath.Join(cfg.Storages[0].Path, expected.RelativePath) - repo := createRepo(t) + repo := createRepo(tb) repoBackupPath := filepath.Join(path, repo.RelativePath) backupPath := filepath.Join(repoBackupPath, backupID) - require.NoError(t, os.MkdirAll(backupPath, os.ModePerm)) - require.NoError(t, os.WriteFile(filepath.Join(repoBackupPath, "LATEST"), []byte(backupID), os.ModePerm)) - require.NoError(t, os.WriteFile(filepath.Join(backupPath, "LATEST"), []byte("002"), os.ModePerm)) + require.NoError(tb, os.MkdirAll(backupPath, os.ModePerm)) + require.NoError(tb, os.WriteFile(filepath.Join(repoBackupPath, "LATEST"), []byte(backupID), os.ModePerm)) + require.NoError(tb, os.WriteFile(filepath.Join(backupPath, "LATEST"), []byte("002"), os.ModePerm)) - root := gittest.WriteCommit(t, cfg, expectedRepoPath, + root := gittest.WriteCommit(tb, cfg, expectedRepoPath, gittest.WithBranch("master"), ) - master1 := gittest.WriteCommit(t, cfg, expectedRepoPath, + master1 := gittest.WriteCommit(tb, cfg, expectedRepoPath, gittest.WithBranch("master"), gittest.WithParents(root), ) - other := gittest.WriteCommit(t, cfg, expectedRepoPath, + other := gittest.WriteCommit(tb, cfg, expectedRepoPath, gittest.WithBranch("other"), gittest.WithParents(root), ) - gittest.Exec(t, cfg, "-C", expectedRepoPath, "symbolic-ref", "HEAD", "refs/heads/master") + gittest.Exec(tb, cfg, "-C", expectedRepoPath, "symbolic-ref", "HEAD", "refs/heads/master") bundlePath1 := filepath.Join(backupPath, "001.bundle") - gittest.Exec(t, cfg, "-C", expectedRepoPath, "bundle", "create", bundlePath1, + gittest.Exec(tb, cfg, "-C", expectedRepoPath, "bundle", "create", bundlePath1, "HEAD", "refs/heads/master", "refs/heads/other", ) - master2 := gittest.WriteCommit(t, cfg, expectedRepoPath, + master2 := gittest.WriteCommit(tb, cfg, expectedRepoPath, gittest.WithBranch("master"), gittest.WithParents(master1), ) bundlePath2 := filepath.Join(backupPath, "002.bundle") - gittest.Exec(t, cfg, "-C", expectedRepoPath, "bundle", "create", bundlePath2, + gittest.Exec(tb, cfg, "-C", expectedRepoPath, "bundle", "create", bundlePath2, "HEAD", "^"+master1.String(), "^"+other.String(), diff --git a/internal/backup/locator_test.go b/internal/backup/locator_test.go index cb19830ae..0f2665c4e 100644 --- a/internal/backup/locator_test.go +++ b/internal/backup/locator_test.go @@ -103,7 +103,7 @@ func TestPointerLocator(t *testing.T) { for _, tc := range []struct { desc string - setup func(t testing.TB, ctx context.Context, sink Sink) + setup func(tb testing.TB, ctx context.Context, sink Sink) expectedBackupID string expectedOffset int }{ @@ -115,9 +115,9 @@ func TestPointerLocator(t *testing.T) { desc: "with previous backup", expectedBackupID: "abc123", expectedOffset: 1, - setup: func(t testing.TB, ctx context.Context, sink Sink) { - require.NoError(t, sink.Write(ctx, filepath.Join(repo.RelativePath, "LATEST"), strings.NewReader("abc123"))) - require.NoError(t, sink.Write(ctx, filepath.Join(repo.RelativePath, "abc123", "LATEST"), strings.NewReader("001"))) + setup: func(tb testing.TB, ctx context.Context, sink Sink) { + require.NoError(tb, sink.Write(ctx, filepath.Join(repo.RelativePath, "LATEST"), strings.NewReader("abc123"))) + require.NoError(tb, sink.Write(ctx, filepath.Join(repo.RelativePath, "abc123", "LATEST"), strings.NewReader("001"))) }, }, } { diff --git a/internal/cache/walker_test.go b/internal/cache/walker_test.go index d76dfdba6..dc4f55f39 100644 --- a/internal/cache/walker_test.go +++ b/internal/cache/walker_test.go @@ -137,10 +137,10 @@ func TestCleanWalkEmptyDirs(t *testing.T) { require.Equal(t, expect, actual) } -func findFiles(t testing.TB, path string) string { +func findFiles(tb testing.TB, path string) string { cmd := exec.Command("find", ".") cmd.Dir = path out, err := cmd.Output() - require.NoError(t, err) + require.NoError(tb, err) return string(out) } diff --git a/internal/git/gittest/command.go b/internal/git/gittest/command.go index 997e2905f..376f928b4 100644 --- a/internal/git/gittest/command.go +++ b/internal/git/gittest/command.go @@ -24,26 +24,26 @@ type ExecConfig struct { } // Exec runs a git command and returns the standard output, or fails. -func Exec(t testing.TB, cfg config.Cfg, args ...string) []byte { - t.Helper() - return ExecOpts(t, cfg, ExecConfig{}, args...) +func Exec(tb testing.TB, cfg config.Cfg, args ...string) []byte { + tb.Helper() + return ExecOpts(tb, cfg, ExecConfig{}, args...) } // ExecOpts runs a git command with the given configuration. -func ExecOpts(t testing.TB, cfg config.Cfg, execCfg ExecConfig, args ...string) []byte { - t.Helper() +func ExecOpts(tb testing.TB, cfg config.Cfg, execCfg ExecConfig, args ...string) []byte { + tb.Helper() - cmd := createCommand(t, cfg, execCfg, args...) + cmd := createCommand(tb, cfg, execCfg, args...) // If the caller has passed an stdout writer to us we cannot use `cmd.Output()`. So // we detect this case and call `cmd.Run()` instead. if execCfg.Stdout != nil { if err := cmd.Run(); err != nil { - t.Log(cfg.Git.BinPath, args) + tb.Log(cfg.Git.BinPath, args) if ee, ok := err.(*exec.ExitError); ok { - t.Logf("%s\n", ee.Stderr) + tb.Logf("%s\n", ee.Stderr) } - t.Fatal(err) + tb.Fatal(err) } return nil @@ -51,28 +51,28 @@ func ExecOpts(t testing.TB, cfg config.Cfg, execCfg ExecConfig, args ...string) output, err := cmd.Output() if err != nil { - t.Log(cfg.Git.BinPath, args) + tb.Log(cfg.Git.BinPath, args) if ee, ok := err.(*exec.ExitError); ok { - t.Logf("%s: %s\n", ee.Stderr, output) + tb.Logf("%s: %s\n", ee.Stderr, output) } - t.Fatal(err) + tb.Fatal(err) } return output } // NewCommand creates a new Git command ready for execution. -func NewCommand(t testing.TB, cfg config.Cfg, args ...string) *exec.Cmd { - t.Helper() - return createCommand(t, cfg, ExecConfig{}, args...) +func NewCommand(tb testing.TB, cfg config.Cfg, args ...string) *exec.Cmd { + tb.Helper() + return createCommand(tb, cfg, ExecConfig{}, args...) } -func createCommand(t testing.TB, cfg config.Cfg, execCfg ExecConfig, args ...string) *exec.Cmd { - t.Helper() +func createCommand(tb testing.TB, cfg config.Cfg, execCfg ExecConfig, args ...string) *exec.Cmd { + tb.Helper() - ctx := testhelper.Context(t) + ctx := testhelper.Context(tb) - execEnv := NewCommandFactory(t, cfg).GetExecutionEnvironment(ctx) + execEnv := NewCommandFactory(tb, cfg).GetExecutionEnvironment(ctx) cmd := exec.CommandContext(ctx, execEnv.BinaryPath, args...) cmd.Env = command.AllowedEnvironment(os.Environ()) diff --git a/internal/git/gittest/commit.go b/internal/git/gittest/commit.go index fe0b0a914..7e2adbc25 100644 --- a/internal/git/gittest/commit.go +++ b/internal/git/gittest/commit.go @@ -145,8 +145,8 @@ func WithAlternateObjectDirectory(alternateObjectDir string) WriteCommitOption { } // WriteCommit writes a new commit into the target repository. -func WriteCommit(t testing.TB, cfg config.Cfg, repoPath string, opts ...WriteCommitOption) git.ObjectID { - t.Helper() +func WriteCommit(tb testing.TB, cfg config.Cfg, repoPath string, opts ...WriteCommitOption) git.ObjectID { + tb.Helper() var writeCommitConfig writeCommitConfig for _, opt := range opts { @@ -160,12 +160,12 @@ func WriteCommit(t testing.TB, cfg config.Cfg, repoPath string, opts ...WriteCom stdin := bytes.NewBufferString(message) if len(writeCommitConfig.treeEntries) > 0 && writeCommitConfig.treeID != "" { - require.FailNow(t, "cannot set tree entries and tree ID at the same time") + require.FailNow(tb, "cannot set tree entries and tree ID at the same time") } var tree string if len(writeCommitConfig.treeEntries) > 0 { - tree = WriteTree(t, cfg, repoPath, writeCommitConfig.treeEntries).String() + tree = WriteTree(tb, cfg, repoPath, writeCommitConfig.treeEntries).String() } else if writeCommitConfig.treeID != "" { tree = writeCommitConfig.treeID.String() } else if len(writeCommitConfig.parents) == 0 { @@ -203,9 +203,9 @@ func WriteCommit(t testing.TB, cfg config.Cfg, repoPath string, opts ...WriteCom var env []string if writeCommitConfig.alternateObjectDir != "" { - require.True(t, filepath.IsAbs(writeCommitConfig.alternateObjectDir), + require.True(tb, filepath.IsAbs(writeCommitConfig.alternateObjectDir), "alternate object directory must be an absolute path") - require.NoError(t, os.MkdirAll(writeCommitConfig.alternateObjectDir, 0o755)) + require.NoError(tb, os.MkdirAll(writeCommitConfig.alternateObjectDir, 0o755)) env = append(env, fmt.Sprintf("GIT_OBJECT_DIRECTORY=%s", writeCommitConfig.alternateObjectDir), @@ -226,15 +226,15 @@ func WriteCommit(t testing.TB, cfg config.Cfg, repoPath string, opts ...WriteCom commitArgs = append(commitArgs, "-p", parent.String()) } - stdout := ExecOpts(t, cfg, ExecConfig{ + stdout := ExecOpts(tb, cfg, ExecConfig{ Stdin: stdin, Env: env, }, commitArgs...) oid, err := DefaultObjectHash.FromHex(text.ChompBytes(stdout)) - require.NoError(t, err) + require.NoError(tb, err) if writeCommitConfig.reference != "" { - ExecOpts(t, cfg, ExecConfig{ + ExecOpts(tb, cfg, ExecConfig{ Env: env, }, "-C", repoPath, "update-ref", writeCommitConfig.reference, oid.String()) } @@ -242,20 +242,20 @@ func WriteCommit(t testing.TB, cfg config.Cfg, repoPath string, opts ...WriteCom return oid } -func authorEqualIgnoringDate(t testing.TB, expected *gitalypb.CommitAuthor, actual *gitalypb.CommitAuthor) { - t.Helper() - require.Equal(t, expected.GetName(), actual.GetName(), "author name does not match") - require.Equal(t, expected.GetEmail(), actual.GetEmail(), "author mail does not match") +func authorEqualIgnoringDate(tb testing.TB, expected *gitalypb.CommitAuthor, actual *gitalypb.CommitAuthor) { + tb.Helper() + require.Equal(tb, expected.GetName(), actual.GetName(), "author name does not match") + require.Equal(tb, expected.GetEmail(), actual.GetEmail(), "author mail does not match") } // CommitEqual tests if two `GitCommit`s are equal -func CommitEqual(t testing.TB, expected, actual *gitalypb.GitCommit) { - t.Helper() - - authorEqualIgnoringDate(t, expected.GetAuthor(), actual.GetAuthor()) - authorEqualIgnoringDate(t, expected.GetCommitter(), actual.GetCommitter()) - require.Equal(t, expected.GetBody(), actual.GetBody(), "body does not match") - require.Equal(t, expected.GetSubject(), actual.GetSubject(), "subject does not match") - require.Equal(t, expected.GetId(), actual.GetId(), "object ID does not match") - require.Equal(t, expected.GetParentIds(), actual.GetParentIds(), "parent IDs do not match") +func CommitEqual(tb testing.TB, expected, actual *gitalypb.GitCommit) { + tb.Helper() + + authorEqualIgnoringDate(tb, expected.GetAuthor(), actual.GetAuthor()) + authorEqualIgnoringDate(tb, expected.GetCommitter(), actual.GetCommitter()) + require.Equal(tb, expected.GetBody(), actual.GetBody(), "body does not match") + require.Equal(tb, expected.GetSubject(), actual.GetSubject(), "subject does not match") + require.Equal(tb, expected.GetId(), actual.GetId(), "object ID does not match") + require.Equal(tb, expected.GetParentIds(), actual.GetParentIds(), "parent IDs do not match") } diff --git a/internal/git/gittest/hooks.go b/internal/git/gittest/hooks.go index 82c1d1358..7bf13f260 100644 --- a/internal/git/gittest/hooks.go +++ b/internal/git/gittest/hooks.go @@ -11,13 +11,13 @@ import ( ) // WriteEnvToCustomHook dumps the env vars that the custom hooks receives to a file -func WriteEnvToCustomHook(t testing.TB, repoPath, hookName string) string { - tempDir := testhelper.TempDir(t) +func WriteEnvToCustomHook(tb testing.TB, repoPath, hookName string) string { + tempDir := testhelper.TempDir(tb) outputPath := filepath.Join(tempDir, "hook.env") hookContent := fmt.Sprintf("#!/bin/sh\n/usr/bin/env >%s\n", outputPath) - WriteCustomHook(t, repoPath, hookName, []byte(hookContent)) + WriteCustomHook(tb, repoPath, hookName, []byte(hookContent)) return outputPath } @@ -26,8 +26,8 @@ func WriteEnvToCustomHook(t testing.TB, repoPath, hookName string) string { // if it can find the object in the quarantine directory. if // GIT_OBJECT_DIRECTORY and GIT_ALTERNATE_OBJECT_DIRECTORIES were not passed // through correctly to the hooks, it will fail -func WriteCheckNewObjectExistsHook(t testing.TB, repoPath string) { - WriteCustomHook(t, repoPath, "pre-receive", []byte( +func WriteCheckNewObjectExistsHook(tb testing.TB, repoPath string) { + WriteCustomHook(tb, repoPath, "pre-receive", []byte( `#!/bin/sh while read oldrev newrev reference do @@ -37,23 +37,23 @@ func WriteCheckNewObjectExistsHook(t testing.TB, repoPath string) { } // WriteCustomHook writes a hook in the repo/path.git/custom_hooks directory -func WriteCustomHook(t testing.TB, repoPath, name string, content []byte) string { +func WriteCustomHook(tb testing.TB, repoPath, name string, content []byte) string { fullPath := filepath.Join(repoPath, "custom_hooks", name) - testhelper.WriteExecutable(t, fullPath, content) + testhelper.WriteExecutable(tb, fullPath, content) return fullPath } // CaptureHookEnv creates a Git command factory which injects a bogus 'update' Git hook to sniff out // what environment variables get set for hooks. -func CaptureHookEnv(t testing.TB, cfg config.Cfg) (git.CommandFactory, string) { - hooksPath := testhelper.TempDir(t) +func CaptureHookEnv(tb testing.TB, cfg config.Cfg) (git.CommandFactory, string) { + hooksPath := testhelper.TempDir(tb) hookOutputFile := filepath.Join(hooksPath, "hook.env") - testhelper.WriteExecutable(t, filepath.Join(hooksPath, "update"), []byte(fmt.Sprintf( + testhelper.WriteExecutable(tb, filepath.Join(hooksPath, "update"), []byte(fmt.Sprintf( `#!/usr/bin/env bash env | grep -e ^GIT -e ^GL_ >%q `, hookOutputFile))) - return NewCommandFactory(t, cfg, git.WithHooksPath(hooksPath)), hookOutputFile + return NewCommandFactory(tb, cfg, git.WithHooksPath(hooksPath)), hookOutputFile } diff --git a/internal/git/gittest/http_server.go b/internal/git/gittest/http_server.go index 7619cdcb2..d55f2987a 100644 --- a/internal/git/gittest/http_server.go +++ b/internal/git/gittest/http_server.go @@ -16,11 +16,11 @@ import ( // HTTPServer starts an HTTP server with git-http-backend(1) as CGI handler. The repository is // prepared such that git-http-backend(1) will serve it by creating the "git-daemon-export-ok" magic // file. -func HTTPServer(ctx context.Context, t testing.TB, gitCmdFactory git.CommandFactory, repoPath string, middleware func(http.ResponseWriter, *http.Request, http.Handler)) (int, func() error) { - require.NoError(t, os.WriteFile(filepath.Join(repoPath, "git-daemon-export-ok"), nil, 0o644)) +func HTTPServer(ctx context.Context, tb testing.TB, gitCmdFactory git.CommandFactory, repoPath string, middleware func(http.ResponseWriter, *http.Request, http.Handler)) (int, func() error) { + require.NoError(tb, os.WriteFile(filepath.Join(repoPath, "git-daemon-export-ok"), nil, 0o644)) listener, err := net.Listen("tcp", "127.0.0.1:0") - require.NoError(t, err) + require.NoError(tb, err) gitExecEnv := gitCmdFactory.GetExecutionEnvironment(ctx) diff --git a/internal/git/gittest/objects.go b/internal/git/gittest/objects.go index 0a740326e..d7499868f 100644 --- a/internal/git/gittest/objects.go +++ b/internal/git/gittest/objects.go @@ -22,67 +22,67 @@ func ObjectHashIsSHA256() bool { // RequireObjectExists asserts that the given repository does contain an object with the specified // object ID. -func RequireObjectExists(t testing.TB, cfg config.Cfg, repoPath string, objectID git.ObjectID) { - requireObjectExists(t, cfg, repoPath, objectID, true) +func RequireObjectExists(tb testing.TB, cfg config.Cfg, repoPath string, objectID git.ObjectID) { + requireObjectExists(tb, cfg, repoPath, objectID, true) } // RequireObjectNotExists asserts that the given repository does not contain an object with the // specified object ID. -func RequireObjectNotExists(t testing.TB, cfg config.Cfg, repoPath string, objectID git.ObjectID) { - requireObjectExists(t, cfg, repoPath, objectID, false) +func RequireObjectNotExists(tb testing.TB, cfg config.Cfg, repoPath string, objectID git.ObjectID) { + requireObjectExists(tb, cfg, repoPath, objectID, false) } -func requireObjectExists(t testing.TB, cfg config.Cfg, repoPath string, objectID git.ObjectID, exists bool) { - cmd := NewCommand(t, cfg, "-C", repoPath, "cat-file", "-e", objectID.String()) +func requireObjectExists(tb testing.TB, cfg config.Cfg, repoPath string, objectID git.ObjectID, exists bool) { + cmd := NewCommand(tb, cfg, "-C", repoPath, "cat-file", "-e", objectID.String()) cmd.Env = []string{ "GIT_ALLOW_PROTOCOL=", // To prevent partial clone reaching remote repo over SSH } if exists { - require.NoError(t, cmd.Run(), "checking for object should succeed") + require.NoError(tb, cmd.Run(), "checking for object should succeed") return } - require.Error(t, cmd.Run(), "checking for object should fail") + require.Error(tb, cmd.Run(), "checking for object should fail") } // GetGitPackfileDirSize gets the number of 1k blocks of a git object directory -func GetGitPackfileDirSize(t testing.TB, repoPath string) int64 { - return getGitDirSize(t, repoPath, "objects", "pack") +func GetGitPackfileDirSize(tb testing.TB, repoPath string) int64 { + return getGitDirSize(tb, repoPath, "objects", "pack") } -func getGitDirSize(t testing.TB, repoPath string, subdirs ...string) int64 { +func getGitDirSize(tb testing.TB, repoPath string, subdirs ...string) int64 { cmd := exec.Command("du", "-s", "-k", filepath.Join(append([]string{repoPath}, subdirs...)...)) output, err := cmd.Output() - require.NoError(t, err) + require.NoError(tb, err) if len(output) < 2 { - t.Error("invalid output of du -s -k") + tb.Error("invalid output of du -s -k") } outputSplit := strings.SplitN(string(output), "\t", 2) blocks, err := strconv.ParseInt(outputSplit[0], 10, 64) - require.NoError(t, err) + require.NoError(tb, err) return blocks } // WriteBlobs writes n distinct blobs into the git repository's object // database. Each object has the current time in nanoseconds as contents. -func WriteBlobs(t testing.TB, cfg config.Cfg, testRepoPath string, n int) []string { +func WriteBlobs(tb testing.TB, cfg config.Cfg, testRepoPath string, n int) []string { var blobIDs []string for i := 0; i < n; i++ { contents := []byte(strconv.Itoa(time.Now().Nanosecond())) - blobIDs = append(blobIDs, WriteBlob(t, cfg, testRepoPath, contents).String()) + blobIDs = append(blobIDs, WriteBlob(tb, cfg, testRepoPath, contents).String()) } return blobIDs } // WriteBlob writes the given contents as a blob into the repository and returns its OID. -func WriteBlob(t testing.TB, cfg config.Cfg, testRepoPath string, contents []byte) git.ObjectID { - hex := text.ChompBytes(ExecOpts(t, cfg, ExecConfig{Stdin: bytes.NewReader(contents)}, +func WriteBlob(tb testing.TB, cfg config.Cfg, testRepoPath string, contents []byte) git.ObjectID { + hex := text.ChompBytes(ExecOpts(tb, cfg, ExecConfig{Stdin: bytes.NewReader(contents)}, "-C", testRepoPath, "hash-object", "-w", "--stdin", )) oid, err := DefaultObjectHash.FromHex(hex) - require.NoError(t, err) + require.NoError(tb, err) return oid } diff --git a/internal/git/gittest/protocol.go b/internal/git/gittest/protocol.go index ed44ef0b5..a47f33ec1 100644 --- a/internal/git/gittest/protocol.go +++ b/internal/git/gittest/protocol.go @@ -21,10 +21,10 @@ type ProtocolDetectingCommandFactory struct { } // NewProtocolDetectingCommandFactory returns a new ProtocolDetectingCommandFactory. -func NewProtocolDetectingCommandFactory(ctx context.Context, t testing.TB, cfg config.Cfg) ProtocolDetectingCommandFactory { - envPath := filepath.Join(testhelper.TempDir(t), "git-env") +func NewProtocolDetectingCommandFactory(ctx context.Context, tb testing.TB, cfg config.Cfg) ProtocolDetectingCommandFactory { + envPath := filepath.Join(testhelper.TempDir(tb), "git-env") - gitCmdFactory := NewInterceptingCommandFactory(ctx, t, cfg, func(execEnv git.ExecutionEnvironment) string { + gitCmdFactory := NewInterceptingCommandFactory(ctx, tb, cfg, func(execEnv git.ExecutionEnvironment) string { return fmt.Sprintf( `#!/usr/bin/env bash env | grep ^GIT_PROTOCOL= >>%q diff --git a/internal/git/gittest/ref.go b/internal/git/gittest/ref.go index 9d9687089..cf9757fde 100644 --- a/internal/git/gittest/ref.go +++ b/internal/git/gittest/ref.go @@ -10,15 +10,15 @@ import ( ) // WriteRef writes a reference into the repository pointing to the given object ID. -func WriteRef(t testing.TB, cfg config.Cfg, repoPath string, ref git.ReferenceName, oid git.ObjectID) { - Exec(t, cfg, "-C", repoPath, "update-ref", ref.String(), oid.String()) +func WriteRef(tb testing.TB, cfg config.Cfg, repoPath string, ref git.ReferenceName, oid git.ObjectID) { + Exec(tb, cfg, "-C", repoPath, "update-ref", ref.String(), oid.String()) } // ResolveRevision resolves the revision to an object ID. -func ResolveRevision(t testing.TB, cfg config.Cfg, repoPath string, revision string) git.ObjectID { - t.Helper() - output := Exec(t, cfg, "-C", repoPath, "rev-parse", "--verify", revision) +func ResolveRevision(tb testing.TB, cfg config.Cfg, repoPath string, revision string) git.ObjectID { + tb.Helper() + output := Exec(tb, cfg, "-C", repoPath, "rev-parse", "--verify", revision) objectID, err := DefaultObjectHash.FromHex(text.ChompBytes(output)) - require.NoError(t, err) + require.NoError(tb, err) return objectID } diff --git a/internal/git/gittest/remote.go b/internal/git/gittest/remote.go index 524be9be6..c3d5ea8e4 100644 --- a/internal/git/gittest/remote.go +++ b/internal/git/gittest/remote.go @@ -8,12 +8,12 @@ import ( ) // RemoteExists tests if the repository at repoPath has a Git remote named remoteName. -func RemoteExists(t testing.TB, cfg config.Cfg, repoPath string, remoteName string) bool { +func RemoteExists(tb testing.TB, cfg config.Cfg, repoPath string, remoteName string) bool { if remoteName == "" { - t.Fatal("empty remote name") + tb.Fatal("empty remote name") } - remotes := Exec(t, cfg, "-C", repoPath, "remote") + remotes := Exec(tb, cfg, "-C", repoPath, "remote") for _, r := range strings.Split(string(remotes), "\n") { if r == remoteName { return true diff --git a/internal/git/gittest/repo.go b/internal/git/gittest/repo.go index a2c62f9c0..6438f0a6b 100644 --- a/internal/git/gittest/repo.go +++ b/internal/git/gittest/repo.go @@ -41,9 +41,9 @@ const ( ) // InitRepoDir creates a temporary directory for a repo, without initializing it -func InitRepoDir(t testing.TB, storagePath, relativePath string) *gitalypb.Repository { +func InitRepoDir(tb testing.TB, storagePath, relativePath string) *gitalypb.Repository { repoPath := filepath.Join(storagePath, relativePath, "..") - require.NoError(t, os.MkdirAll(repoPath, 0o755), "making repo parent dir") + require.NoError(tb, os.MkdirAll(repoPath, 0o755), "making repo parent dir") return &gitalypb.Repository{ StorageName: "default", RelativePath: relativePath, @@ -54,29 +54,29 @@ func InitRepoDir(t testing.TB, storagePath, relativePath string) *gitalypb.Repos // NewObjectPoolName returns a random pool repository name in format // '@pools/[0-9a-z]{2}/[0-9a-z]{2}/[0-9a-z]{64}.git'. -func NewObjectPoolName(t testing.TB) string { - return filepath.Join("@pools", newDiskHash(t)+".git") +func NewObjectPoolName(tb testing.TB) string { + return filepath.Join("@pools", newDiskHash(tb)+".git") } // NewRepositoryName returns a random repository hash // in format '@hashed/[0-9a-f]{2}/[0-9a-f]{2}/[0-9a-f]{64}(.git)?'. -func NewRepositoryName(t testing.TB, bare bool) string { +func NewRepositoryName(tb testing.TB, bare bool) string { suffix := "" if bare { suffix = ".git" } - return filepath.Join("@hashed", newDiskHash(t)+suffix) + return filepath.Join("@hashed", newDiskHash(tb)+suffix) } // newDiskHash generates a random directory path following the Rails app's // approach in the hashed storage module, formatted as '[0-9a-f]{2}/[0-9a-f]{2}/[0-9a-f]{64}'. // https://gitlab.com/gitlab-org/gitlab/-/blob/f5c7d8eb1dd4eee5106123e04dec26d277ff6a83/app/models/storage/hashed.rb#L38-43 -func newDiskHash(t testing.TB) string { +func newDiskHash(tb testing.TB) string { // rails app calculates a sha256 and uses its hex representation // as the directory path b, err := text.RandomHex(sha256.Size) - require.NoError(t, err) + require.NoError(tb, err) return filepath.Join(b[0:2], b[2:4], b) } @@ -103,22 +103,22 @@ type CreateRepositoryConfig struct { ObjectFormat string } -func dialService(ctx context.Context, t testing.TB, cfg config.Cfg) *grpc.ClientConn { +func dialService(ctx context.Context, tb testing.TB, cfg config.Cfg) *grpc.ClientConn { dialOptions := []grpc.DialOption{} if cfg.Auth.Token != "" { dialOptions = append(dialOptions, grpc.WithPerRPCCredentials(gitalyauth.RPCCredentialsV2(cfg.Auth.Token))) } conn, err := client.DialContext(ctx, cfg.SocketPath, dialOptions) - require.NoError(t, err) + require.NoError(tb, err) return conn } // CreateRepository creates a new repository and returns it and its absolute path. -func CreateRepository(ctx context.Context, t testing.TB, cfg config.Cfg, configs ...CreateRepositoryConfig) (*gitalypb.Repository, string) { - t.Helper() +func CreateRepository(ctx context.Context, tb testing.TB, cfg config.Cfg, configs ...CreateRepositoryConfig) (*gitalypb.Repository, string) { + tb.Helper() - require.Less(t, len(configs), 2, "you must either pass no or exactly one option") + require.Less(tb, len(configs), 2, "you must either pass no or exactly one option") opts := CreateRepositoryConfig{} if len(configs) == 1 { @@ -126,8 +126,8 @@ func CreateRepository(ctx context.Context, t testing.TB, cfg config.Cfg, configs } if ObjectHashIsSHA256() || opts.ObjectFormat != "" { - require.Empty(t, opts.Seed, "seeded repository creation not supported with non-default object format") - require.True(t, opts.SkipCreationViaService, "repository creation via service not supported with non-default object format") + require.Empty(tb, opts.Seed, "seeded repository creation not supported with non-default object format") + require.True(tb, opts.SkipCreationViaService, "repository creation via service not supported with non-default object format") } storage := cfg.Storages[0] @@ -135,7 +135,7 @@ func CreateRepository(ctx context.Context, t testing.TB, cfg config.Cfg, configs storage = opts.Storage } - relativePath := NewRepositoryName(t, true) + relativePath := NewRepositoryName(tb, true) if opts.RelativePath != "" { relativePath = opts.RelativePath } @@ -151,26 +151,26 @@ func CreateRepository(ctx context.Context, t testing.TB, cfg config.Cfg, configs if !opts.SkipCreationViaService { conn := opts.ClientConn if conn == nil { - conn = dialService(ctx, t, cfg) - t.Cleanup(func() { testhelper.MustClose(t, conn) }) + conn = dialService(ctx, tb, cfg) + tb.Cleanup(func() { testhelper.MustClose(tb, conn) }) } client := gitalypb.NewRepositoryServiceClient(conn) if opts.Seed != "" { _, err := client.CreateRepositoryFromURL(ctx, &gitalypb.CreateRepositoryFromURLRequest{ Repository: repository, - Url: testRepositoryPath(t, opts.Seed), + Url: testRepositoryPath(tb, opts.Seed), Mirror: true, }) - require.NoError(t, err) + require.NoError(tb, err) } else { _, err := client.CreateRepository(ctx, &gitalypb.CreateRepositoryRequest{ Repository: repository, }) - require.NoError(t, err) + require.NoError(tb, err) } - t.Cleanup(func() { + tb.Cleanup(func() { // The ctx parameter would be canceled by now as the tests defer the cancellation. _, err := client.RemoveRepository(context.TODO(), &gitalypb.RemoveRepositoryRequest{ Repository: repository, @@ -181,16 +181,16 @@ func CreateRepository(ctx context.Context, t testing.TB, cfg config.Cfg, configs return } - require.NoError(t, err) + require.NoError(tb, err) }) - repoPath = filepath.Join(storage.Path, getReplicaPath(ctx, t, conn, repository)) + repoPath = filepath.Join(storage.Path, getReplicaPath(ctx, tb, conn, repository)) } else { repoPath = filepath.Join(storage.Path, repository.RelativePath) if opts.Seed != "" { - Exec(t, cfg, "clone", "--no-hardlinks", "--dissociate", "--bare", testRepositoryPath(t, opts.Seed), repoPath) - Exec(t, cfg, "-C", repoPath, "remote", "remove", "origin") + Exec(tb, cfg, "clone", "--no-hardlinks", "--dissociate", "--bare", testRepositoryPath(tb, opts.Seed), repoPath) + Exec(tb, cfg, "-C", repoPath, "remote", "remove", "origin") } else { args := []string{"init", "--bare"} args = append(args, initRepoExtraArgs...) @@ -199,10 +199,10 @@ func CreateRepository(ctx context.Context, t testing.TB, cfg config.Cfg, configs args = append(args, "--object-format", opts.ObjectFormat) } - Exec(t, cfg, args...) + Exec(tb, cfg, args...) } - t.Cleanup(func() { require.NoError(t, os.RemoveAll(repoPath)) }) + tb.Cleanup(func() { require.NoError(tb, os.RemoveAll(repoPath)) }) } // Return a cloned repository so the above clean up function still targets the correct repository @@ -223,8 +223,8 @@ type GetReplicaPathConfig struct { // run with Praefect in front of it. This is necessary if the test creates a repository // through Praefect and peeks into the filesystem afterwards. Conn should be pointing to // Praefect. -func GetReplicaPath(ctx context.Context, t testing.TB, cfg config.Cfg, repo repository.GitRepo, opts ...GetReplicaPathConfig) string { - require.Less(t, len(opts), 2, "you must either pass no or exactly one option") +func GetReplicaPath(ctx context.Context, tb testing.TB, cfg config.Cfg, repo repository.GitRepo, opts ...GetReplicaPathConfig) string { + require.Less(tb, len(opts), 2, "you must either pass no or exactly one option") var opt GetReplicaPathConfig if len(opts) > 0 { @@ -233,14 +233,14 @@ func GetReplicaPath(ctx context.Context, t testing.TB, cfg config.Cfg, repo repo conn := opt.ClientConn if conn == nil { - conn = dialService(ctx, t, cfg) + conn = dialService(ctx, tb, cfg) defer conn.Close() } - return getReplicaPath(ctx, t, conn, repo) + return getReplicaPath(ctx, tb, conn, repo) } -func getReplicaPath(ctx context.Context, t testing.TB, conn *grpc.ClientConn, repo repository.GitRepo) string { +func getReplicaPath(ctx context.Context, tb testing.TB, conn *grpc.ClientConn, repo repository.GitRepo) string { metadata, err := gitalypb.NewPraefectInfoServiceClient(conn).GetRepositoryMetadata( ctx, &gitalypb.GetRepositoryMetadataRequest{ Query: &gitalypb.GetRepositoryMetadataRequest_Path_{ @@ -254,7 +254,7 @@ func getReplicaPath(ctx context.Context, t testing.TB, conn *grpc.ClientConn, re // The repository is stored at relative path if the test is running without Praefect in front. return repo.GetRelativePath() } - require.NoError(t, err) + require.NoError(tb, err) return metadata.ReplicaPath } @@ -262,26 +262,26 @@ func getReplicaPath(ctx context.Context, t testing.TB, conn *grpc.ClientConn, re // RewrittenRepository returns the repository as it would be received by a Gitaly after being rewritten by Praefect. // This should be used when the repository is being accessed through the filesystem to ensure the access path is // correct. If the test is not running with Praefect in front, it returns the an unaltered copy of repository. -func RewrittenRepository(ctx context.Context, t testing.TB, cfg config.Cfg, repository *gitalypb.Repository) *gitalypb.Repository { - // Don't modify the original repository. +func RewrittenRepository(ctx context.Context, tb testing.TB, cfg config.Cfg, repository *gitalypb.Repository) *gitalypb.Repository { + // Don'tb modify the original repository. rewritten := proto.Clone(repository).(*gitalypb.Repository) - rewritten.RelativePath = GetReplicaPath(ctx, t, cfg, repository) + rewritten.RelativePath = GetReplicaPath(ctx, tb, cfg, repository) return rewritten } // BundleRepo creates a bundle of a repository. `patterns` define the bundle contents as per // `git-rev-list-args`. If there are no patterns then `--all` is assumed. -func BundleRepo(t testing.TB, cfg config.Cfg, repoPath, bundlePath string, patterns ...string) { +func BundleRepo(tb testing.TB, cfg config.Cfg, repoPath, bundlePath string, patterns ...string) { if len(patterns) == 0 { patterns = []string{"--all"} } - Exec(t, cfg, append([]string{"-C", repoPath, "bundle", "create", bundlePath}, patterns...)...) + Exec(tb, cfg, append([]string{"-C", repoPath, "bundle", "create", bundlePath}, patterns...)...) } // ChecksumRepo calculates the checksum of a repository. -func ChecksumRepo(t testing.TB, cfg config.Cfg, repoPath string) *git.Checksum { +func ChecksumRepo(tb testing.TB, cfg config.Cfg, repoPath string) *git.Checksum { var checksum git.Checksum - lines := bytes.Split(Exec(t, cfg, "-C", repoPath, "show-ref", "--head"), []byte("\n")) + lines := bytes.Split(Exec(tb, cfg, "-C", repoPath, "show-ref", "--head"), []byte("\n")) for _, line := range lines { checksum.AddBytes(line) } @@ -290,10 +290,10 @@ func ChecksumRepo(t testing.TB, cfg config.Cfg, repoPath string) *git.Checksum { // testRepositoryPath returns the absolute path of local 'gitlab-org/gitlab-test.git' clone. // It is cloned under the path by the test preparing step of make. -func testRepositoryPath(t testing.TB, repo string) string { +func testRepositoryPath(tb testing.TB, repo string) string { _, currentFile, _, ok := runtime.Caller(0) if !ok { - require.Fail(t, "could not get caller info") + require.Fail(tb, "could not get caller info") } path := filepath.Join(filepath.Dir(currentFile), "..", "..", "..", "_build", "testrepos", repo) @@ -301,7 +301,7 @@ func testRepositoryPath(t testing.TB, repo string) string { makePath := filepath.Join(filepath.Dir(currentFile), "..", "..", "..") makeTarget := "prepare-test-repos" log.Printf("local clone of test repository %q not found in %q, running `make %v`", repo, path, makeTarget) - testhelper.MustRunCommand(t, nil, "make", "-C", makePath, makeTarget) + testhelper.MustRunCommand(tb, nil, "make", "-C", makePath, makeTarget) } return path @@ -323,8 +323,8 @@ func AddWorktreeArgs(repoPath, worktreeName string) []string { } // AddWorktree creates a worktree in the repository path for tests -func AddWorktree(t testing.TB, cfg config.Cfg, repoPath string, worktreeName string) { - Exec(t, cfg, AddWorktreeArgs(repoPath, worktreeName)...) +func AddWorktree(tb testing.TB, cfg config.Cfg, repoPath string, worktreeName string) { + Exec(tb, cfg, AddWorktreeArgs(repoPath, worktreeName)...) } // FixGitLabTestRepoForCommitGraphs fixes the "gitlab-test.git" repository so that it can be used in diff --git a/internal/git/gittest/tag.go b/internal/git/gittest/tag.go index 047d952b3..a5691b3f4 100644 --- a/internal/git/gittest/tag.go +++ b/internal/git/gittest/tag.go @@ -25,14 +25,14 @@ type WriteTagConfig struct { // created. Takes either no WriteTagConfig, in which case the default values will be used, or // exactly one. func WriteTag( - t testing.TB, + tb testing.TB, cfg config.Cfg, repoPath string, tagName string, targetRevision git.Revision, optionalConfig ...WriteTagConfig, ) git.ObjectID { - require.Less(t, len(optionalConfig), 2, "only a single config may be passed") + require.Less(tb, len(optionalConfig), 2, "only a single config may be passed") var config WriteTagConfig if len(optionalConfig) == 1 { @@ -57,12 +57,12 @@ func WriteTag( } args = append(args, tagName, targetRevision.String()) - ExecOpts(t, cfg, ExecConfig{Stdin: stdin}, args...) + ExecOpts(tb, cfg, ExecConfig{Stdin: stdin}, args...) - tagID := Exec(t, cfg, "-C", repoPath, "show-ref", "-s", tagName) + tagID := Exec(tb, cfg, "-C", repoPath, "show-ref", "-s", tagName) objectID, err := DefaultObjectHash.FromHex(text.ChompBytes(tagID)) - require.NoError(t, err) + require.NoError(tb, err) return objectID } diff --git a/internal/git/gittest/testhelper_test.go b/internal/git/gittest/testhelper_test.go index a39c196f6..a477adc66 100644 --- a/internal/git/gittest/testhelper_test.go +++ b/internal/git/gittest/testhelper_test.go @@ -18,12 +18,12 @@ func TestMain(m *testing.M) { // setup sets up a test configuration and repository. Ideally we'd use our central test helpers to // do this, but because of an import cycle we can't. -func setup(t testing.TB) (config.Cfg, *gitalypb.Repository, string) { - t.Helper() +func setup(tb testing.TB) (config.Cfg, *gitalypb.Repository, string) { + tb.Helper() - rootDir := testhelper.TempDir(t) + rootDir := testhelper.TempDir(tb) - ctx := testhelper.Context(t) + ctx := testhelper.Context(tb) var cfg config.Cfg cfg.SocketPath = "it is a stub to bypass Validate method" @@ -35,25 +35,25 @@ func setup(t testing.TB) (config.Cfg, *gitalypb.Repository, string) { Path: filepath.Join(rootDir, "storage.d"), }, } - require.NoError(t, os.Mkdir(cfg.Storages[0].Path, 0o755)) + require.NoError(tb, os.Mkdir(cfg.Storages[0].Path, 0o755)) _, currentFile, _, ok := runtime.Caller(0) - require.True(t, ok, "could not get caller info") + require.True(tb, ok, "could not get caller info") cfg.Ruby.Dir = filepath.Join(filepath.Dir(currentFile), "../../../ruby") cfg.GitlabShell.Dir = filepath.Join(rootDir, "shell.d") - require.NoError(t, os.Mkdir(cfg.GitlabShell.Dir, 0o755)) + require.NoError(tb, os.Mkdir(cfg.GitlabShell.Dir, 0o755)) cfg.BinDir = filepath.Join(rootDir, "bin.d") - require.NoError(t, os.Mkdir(cfg.BinDir, 0o755)) + require.NoError(tb, os.Mkdir(cfg.BinDir, 0o755)) cfg.RuntimeDir = filepath.Join(rootDir, "run.d") - require.NoError(t, os.Mkdir(cfg.RuntimeDir, 0o700)) - require.NoError(t, os.Mkdir(cfg.InternalSocketDir(), 0o700)) + require.NoError(tb, os.Mkdir(cfg.RuntimeDir, 0o700)) + require.NoError(tb, os.Mkdir(cfg.InternalSocketDir(), 0o700)) - require.NoError(t, cfg.Validate()) + require.NoError(tb, cfg.Validate()) - repo, repoPath := CreateRepository(ctx, t, cfg, CreateRepositoryConfig{ + repo, repoPath := CreateRepository(ctx, tb, cfg, CreateRepositoryConfig{ SkipCreationViaService: true, }) diff --git a/internal/git/gittest/tree.go b/internal/git/gittest/tree.go index 8485d32c1..6a45a99b2 100644 --- a/internal/git/gittest/tree.go +++ b/internal/git/gittest/tree.go @@ -26,8 +26,8 @@ type TreeEntry struct { // RequireTree looks up the given treeish and asserts that its entries match // the given expected entries. Tree entries are checked recursively. -func RequireTree(t testing.TB, cfg config.Cfg, repoPath, treeish string, expectedEntries []TreeEntry) { - t.Helper() +func RequireTree(tb testing.TB, cfg config.Cfg, repoPath, treeish string, expectedEntries []TreeEntry) { + tb.Helper() for i, entry := range expectedEntries { if entry.OID != "" { @@ -38,45 +38,45 @@ func RequireTree(t testing.TB, cfg config.Cfg, repoPath, treeish string, expecte hasher := DefaultObjectHash.Hash() _, err := hasher.Write([]byte(blob)) - require.NoError(t, err) + require.NoError(tb, err) expectedEntries[i].OID = git.ObjectID(hex.EncodeToString(hasher.Sum(nil))) } var actualEntries []TreeEntry - output := bytes.TrimSpace(Exec(t, cfg, "-C", repoPath, "ls-tree", "-r", treeish)) + output := bytes.TrimSpace(Exec(tb, cfg, "-C", repoPath, "ls-tree", "-r", treeish)) if len(output) > 0 { for _, line := range bytes.Split(output, []byte("\n")) { // Format: <mode> SP <type> SP <object> TAB <file> tabSplit := bytes.Split(line, []byte("\t")) - require.Len(t, tabSplit, 2) + require.Len(tb, tabSplit, 2) spaceSplit := bytes.Split(tabSplit[0], []byte(" ")) - require.Len(t, spaceSplit, 3) + require.Len(tb, spaceSplit, 3) path := string(tabSplit[1]) objectID, err := DefaultObjectHash.FromHex(string(spaceSplit[2])) - require.NoError(t, err) + require.NoError(tb, err) actualEntries = append(actualEntries, TreeEntry{ OID: objectID, Mode: string(spaceSplit[0]), Path: path, - Content: string(Exec(t, cfg, "-C", repoPath, "show", treeish+":"+path)), + Content: string(Exec(tb, cfg, "-C", repoPath, "show", treeish+":"+path)), }) } } - require.Equal(t, expectedEntries, actualEntries) + require.Equal(tb, expectedEntries, actualEntries) } // WriteTree writes a new tree object to the given path. This function does not verify whether OIDs // referred to by tree entries actually exist in the repository. -func WriteTree(t testing.TB, cfg config.Cfg, repoPath string, entries []TreeEntry) git.ObjectID { - t.Helper() +func WriteTree(tb testing.TB, cfg config.Cfg, repoPath string, entries []TreeEntry) git.ObjectID { + tb.Helper() var tree bytes.Buffer for _, entry := range entries { @@ -91,29 +91,29 @@ func WriteTree(t testing.TB, cfg config.Cfg, repoPath string, entries []TreeEntr case "160000": entryType = "commit" default: - t.Fatalf("invalid entry type %q", entry.Mode) + tb.Fatalf("invalid entry type %q", entry.Mode) } - require.False(t, len(entry.OID) > 0 && len(entry.Content) > 0, + require.False(tb, len(entry.OID) > 0 && len(entry.Content) > 0, "entry cannot have both OID and content") - require.False(t, len(entry.OID) == 0 && len(entry.Content) == 0, + require.False(tb, len(entry.OID) == 0 && len(entry.Content) == 0, "entry must have either an OID or content") oid := entry.OID if len(entry.Content) > 0 { - oid = WriteBlob(t, cfg, repoPath, []byte(entry.Content)) + oid = WriteBlob(tb, cfg, repoPath, []byte(entry.Content)) } formattedEntry := fmt.Sprintf("%s %s %s\t%s\000", entry.Mode, entryType, oid.String(), entry.Path) _, err := tree.WriteString(formattedEntry) - require.NoError(t, err) + require.NoError(tb, err) } - stdout := ExecOpts(t, cfg, ExecConfig{Stdin: &tree}, + stdout := ExecOpts(tb, cfg, ExecConfig{Stdin: &tree}, "-C", repoPath, "mktree", "-z", "--missing", ) treeOID, err := DefaultObjectHash.FromHex(text.ChompBytes(stdout)) - require.NoError(t, err) + require.NoError(tb, err) return treeOID } diff --git a/internal/git/localrepo/objects_test.go b/internal/git/localrepo/objects_test.go index a4cd9b95c..6bc6056b1 100644 --- a/internal/git/localrepo/objects_test.go +++ b/internal/git/localrepo/objects_test.go @@ -441,26 +441,26 @@ func TestRepo_IsAncestor(t *testing.T) { desc: "parent is not valid commit", parent: gittest.DefaultObjectHash.ZeroOID.Revision(), child: childCommitID.Revision(), - errorMatcher: func(t testing.TB, err error) { - require.Equal(t, InvalidCommitError(gittest.DefaultObjectHash.ZeroOID), err) + errorMatcher: func(tb testing.TB, err error) { + require.Equal(tb, InvalidCommitError(gittest.DefaultObjectHash.ZeroOID), err) }, }, { desc: "child is not valid commit", parent: childCommitID.Revision(), child: gittest.DefaultObjectHash.ZeroOID.Revision(), - errorMatcher: func(t testing.TB, err error) { - require.Equal(t, InvalidCommitError(gittest.DefaultObjectHash.ZeroOID), err) + errorMatcher: func(tb testing.TB, err error) { + require.Equal(tb, InvalidCommitError(gittest.DefaultObjectHash.ZeroOID), err) }, }, { desc: "child points to a tree", parent: childCommitID.Revision(), child: childCommitID.Revision() + "^{tree}", - errorMatcher: func(t testing.TB, actualErr error) { + errorMatcher: func(tb testing.TB, actualErr error) { treeOID, err := repo.ResolveRevision(ctx, childCommitID.Revision()+"^{tree}") - require.NoError(t, err) - require.EqualError(t, actualErr, fmt.Sprintf( + require.NoError(tb, err) + require.EqualError(tb, actualErr, fmt.Sprintf( `determine ancestry: exit status 128, stderr: "error: object %s is a tree, not a commit\nfatal: Not a valid commit name %s^{tree}\n"`, treeOID, childCommitID, )) diff --git a/internal/git/localrepo/remote_test.go b/internal/git/localrepo/remote_test.go index 47dd57a21..00208b461 100644 --- a/internal/git/localrepo/remote_test.go +++ b/internal/git/localrepo/remote_test.go @@ -230,10 +230,10 @@ func TestRepo_FetchRemote(t *testing.T) { // captureGitSSHCommand creates a new intercepting command factory which captures the // GIT_SSH_COMMAND environment variable. The returned function can be used to read the variable's // value. -func captureGitSSHCommand(ctx context.Context, t testing.TB, cfg config.Cfg) (git.CommandFactory, func() ([]byte, error)) { - envPath := filepath.Join(testhelper.TempDir(t), "GIT_SSH_PATH") +func captureGitSSHCommand(ctx context.Context, tb testing.TB, cfg config.Cfg) (git.CommandFactory, func() ([]byte, error)) { + envPath := filepath.Join(testhelper.TempDir(tb), "GIT_SSH_PATH") - gitCmdFactory := gittest.NewInterceptingCommandFactory(ctx, t, cfg, func(execEnv git.ExecutionEnvironment) string { + gitCmdFactory := gittest.NewInterceptingCommandFactory(ctx, tb, cfg, func(execEnv git.ExecutionEnvironment) string { return fmt.Sprintf( `#!/usr/bin/env bash if test -z "${GIT_SSH_COMMAND+x}" @@ -268,32 +268,32 @@ func TestRepo_Push(t *testing.T) { gittest.WriteCommit(t, cfg, sourceRepoPath, gittest.WithBranch("master")) gittest.WriteCommit(t, cfg, sourceRepoPath, gittest.WithBranch("feature")) - setupPushRepo := func(t testing.TB) (*Repo, string, []git.ConfigPair) { - repoProto, repopath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + setupPushRepo := func(tb testing.TB) (*Repo, string, []git.ConfigPair) { + repoProto, repopath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ SkipCreationViaService: true, }) return New(locator, gitCmdFactory, catfileCache, repoProto), repopath, nil } - setupDivergedRepo := func(t testing.TB) (*Repo, string, []git.ConfigPair) { - repoProto, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + setupDivergedRepo := func(tb testing.TB) (*Repo, string, []git.ConfigPair) { + repoProto, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ SkipCreationViaService: true, }) repo := New(locator, gitCmdFactory, catfileCache, repoProto) // set up master as a diverging ref in push repo sourceMaster, err := sourceRepo.GetReference(ctx, "refs/heads/master") - require.NoError(t, err) + require.NoError(tb, err) - require.NoError(t, sourceRepo.Push(ctx, repoPath, []string{"refs/*"}, PushOptions{})) - divergedMaster := gittest.WriteCommit(t, cfg, repoPath, + require.NoError(tb, sourceRepo.Push(ctx, repoPath, []string{"refs/*"}, PushOptions{})) + divergedMaster := gittest.WriteCommit(tb, cfg, repoPath, gittest.WithBranch("master"), gittest.WithParents(git.ObjectID(sourceMaster.Target)), ) master, err := repo.GetReference(ctx, "refs/heads/master") - require.NoError(t, err) - require.Equal(t, master.Target, divergedMaster.String()) + require.NoError(tb, err) + require.Equal(tb, master.Target, divergedMaster.String()) return repo, repoPath, nil } @@ -351,8 +351,8 @@ func TestRepo_Push(t *testing.T) { }, { desc: "invalid remote", - setupPushRepo: func(t testing.TB) (*Repo, string, []git.ConfigPair) { - repoProto, _ := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + setupPushRepo: func(tb testing.TB) (*Repo, string, []git.ConfigPair) { + repoProto, _ := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ SkipCreationViaService: true, }) return New(locator, gitCmdFactory, catfileCache, repoProto), "", nil @@ -362,8 +362,8 @@ func TestRepo_Push(t *testing.T) { }, { desc: "in-memory remote", - setupPushRepo: func(testing.TB) (*Repo, string, []git.ConfigPair) { - repoProto, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + setupPushRepo: func(tb testing.TB) (*Repo, string, []git.ConfigPair) { + repoProto, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ SkipCreationViaService: true, }) return New(locator, gitCmdFactory, catfileCache, repoProto), "inmemory", []git.ConfigPair{ diff --git a/internal/git/localrepo/repo.go b/internal/git/localrepo/repo.go index 26e097350..ccd4db37e 100644 --- a/internal/git/localrepo/repo.go +++ b/internal/git/localrepo/repo.go @@ -49,11 +49,11 @@ func New(locator storage.Locator, gitCmdFactory git.CommandFactory, catfileCache // NewTestRepo constructs a Repo. It is intended as a helper function for tests which assembles // dependencies ad-hoc from the given config. -func NewTestRepo(t testing.TB, cfg config.Cfg, repo repository.GitRepo, factoryOpts ...git.ExecCommandFactoryOption) *Repo { - t.Helper() +func NewTestRepo(tb testing.TB, cfg config.Cfg, repo repository.GitRepo, factoryOpts ...git.ExecCommandFactoryOption) *Repo { + tb.Helper() if cfg.SocketPath != testcfg.UnconfiguredSocketPath { - repo = gittest.RewrittenRepository(testhelper.Context(t), t, cfg, &gitalypb.Repository{ + repo = gittest.RewrittenRepository(testhelper.Context(tb), tb, cfg, &gitalypb.Repository{ StorageName: repo.GetStorageName(), RelativePath: repo.GetRelativePath(), GitObjectDirectory: repo.GetGitObjectDirectory(), @@ -62,11 +62,11 @@ func NewTestRepo(t testing.TB, cfg config.Cfg, repo repository.GitRepo, factoryO } gitCmdFactory, cleanup, err := git.NewExecCommandFactory(cfg, factoryOpts...) - t.Cleanup(cleanup) - require.NoError(t, err) + tb.Cleanup(cleanup) + require.NoError(tb, err) catfileCache := catfile.NewCache(cfg) - t.Cleanup(catfileCache.Stop) + tb.Cleanup(catfileCache.Stop) locator := config.NewLocator(cfg) diff --git a/internal/git/localrepo/repo_test.go b/internal/git/localrepo/repo_test.go index 4a13c0922..7f26136f2 100644 --- a/internal/git/localrepo/repo_test.go +++ b/internal/git/localrepo/repo_test.go @@ -22,16 +22,16 @@ import ( func TestRepo(t *testing.T) { cfg := testcfg.Build(t) - gittest.TestRepository(t, cfg, func(ctx context.Context, t testing.TB) (git.Repository, string) { - t.Helper() + gittest.TestRepository(t, cfg, func(ctx context.Context, tb testing.TB) (git.Repository, string) { + tb.Helper() - repoProto, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + repoProto, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ SkipCreationViaService: true, }) - gitCmdFactory := gittest.NewCommandFactory(t, cfg) + gitCmdFactory := gittest.NewCommandFactory(tb, cfg) catfileCache := catfile.NewCache(cfg) - t.Cleanup(catfileCache.Stop) + tb.Cleanup(catfileCache.Stop) return New(config.NewLocator(cfg), gitCmdFactory, catfileCache, repoProto), repoPath }) } diff --git a/internal/git/remoterepo/repository_test.go b/internal/git/remoterepo/repository_test.go index 7057718bb..f7b3f5345 100644 --- a/internal/git/remoterepo/repository_test.go +++ b/internal/git/remoterepo/repository_test.go @@ -55,16 +55,16 @@ func TestRepository(t *testing.T) { pool := client.NewPool() defer pool.Close() - gittest.TestRepository(t, cfg, func(ctx context.Context, t testing.TB) (git.Repository, string) { - t.Helper() + gittest.TestRepository(t, cfg, func(ctx context.Context, tb testing.TB) (git.Repository, string) { + tb.Helper() ctx, err := storage.InjectGitalyServers(ctx, "default", cfg.SocketPath, cfg.Auth.Token) - require.NoError(t, err) + require.NoError(tb, err) - repoProto, repoPath := gittest.CreateRepository(ctx, t, cfg) + repoProto, repoPath := gittest.CreateRepository(ctx, tb, cfg) repo, err := remoterepo.New(metadata.OutgoingToIncoming(ctx), repoProto, pool) - require.NoError(t, err) + require.NoError(tb, err) return repo, repoPath }) } diff --git a/internal/git2go/apply_test.go b/internal/git2go/apply_test.go index c225f02b8..2888dab8b 100644 --- a/internal/git2go/apply_test.go +++ b/internal/git2go/apply_test.go @@ -98,9 +98,9 @@ func TestExecutor_Apply(t *testing.T) { }) require.NoError(t, err) - diffBetween := func(t testing.TB, fromCommit, toCommit git.ObjectID) []byte { - t.Helper() - return gittest.Exec(t, cfg, "-C", repoPath, "format-patch", "--stdout", fromCommit.String()+".."+toCommit.String()) + diffBetween := func(tb testing.TB, fromCommit, toCommit git.ObjectID) []byte { + tb.Helper() + return gittest.Exec(tb, cfg, "-C", repoPath, "format-patch", "--stdout", fromCommit.String()+".."+toCommit.String()) } for _, tc := range []struct { diff --git a/internal/git2go/commit_test.go b/internal/git2go/commit_test.go index 4999d668f..0fef58310 100644 --- a/internal/git2go/commit_test.go +++ b/internal/git2go/commit_test.go @@ -492,11 +492,11 @@ func TestExecutor_Commit(t *testing.T) { } } -func getCommit(t testing.TB, ctx context.Context, repo *localrepo.Repo, oid git.ObjectID) commit { - t.Helper() +func getCommit(tb testing.TB, ctx context.Context, repo *localrepo.Repo, oid git.ObjectID) commit { + tb.Helper() data, err := repo.ReadObject(ctx, oid) - require.NoError(t, err) + require.NoError(tb, err) var commit commit lines := strings.Split(string(data), "\n") @@ -507,19 +507,19 @@ func getCommit(t testing.TB, ctx context.Context, repo *localrepo.Repo, oid git. } split := strings.SplitN(line, " ", 2) - require.Len(t, split, 2, "invalid commit: %q", data) + require.Len(tb, split, 2, "invalid commit: %q", data) field, value := split[0], split[1] switch field { case "parent": - require.Empty(t, commit.Parent, "multi parent parsing not implemented") + require.Empty(tb, commit.Parent, "multi parent parsing not implemented") commit.Parent = git.ObjectID(value) case "author": - require.Empty(t, commit.Author, "commit contained multiple authors") - commit.Author = unmarshalSignature(t, value) + require.Empty(tb, commit.Author, "commit contained multiple authors") + commit.Author = unmarshalSignature(tb, value) case "committer": - require.Empty(t, commit.Committer, "commit contained multiple committers") - commit.Committer = unmarshalSignature(t, value) + require.Empty(tb, commit.Committer, "commit contained multiple committers") + commit.Committer = unmarshalSignature(tb, value) default: } } @@ -527,21 +527,21 @@ func getCommit(t testing.TB, ctx context.Context, repo *localrepo.Repo, oid git. return commit } -func unmarshalSignature(t testing.TB, data string) Signature { - t.Helper() +func unmarshalSignature(tb testing.TB, data string) Signature { + tb.Helper() // Format: NAME <EMAIL> DATE_UNIX DATE_TIMEZONE split1 := strings.Split(data, " <") - require.Len(t, split1, 2, "invalid signature: %q", data) + require.Len(tb, split1, 2, "invalid signature: %q", data) split2 := strings.Split(split1[1], "> ") - require.Len(t, split2, 2, "invalid signature: %q", data) + require.Len(tb, split2, 2, "invalid signature: %q", data) split3 := strings.Split(split2[1], " ") - require.Len(t, split3, 2, "invalid signature: %q", data) + require.Len(tb, split3, 2, "invalid signature: %q", data) timestamp, err := strconv.ParseInt(split3[0], 10, 64) - require.NoError(t, err) + require.NoError(tb, err) return Signature{ Name: split1[0], diff --git a/internal/gitaly/diff/diff_test.go b/internal/gitaly/diff/diff_test.go index 04d3bc3f6..59a38d6f4 100644 --- a/internal/gitaly/diff/diff_test.go +++ b/internal/gitaly/diff/diff_test.go @@ -487,8 +487,8 @@ func TestDiffLimitsBeingEnforcedByUpperBound(t *testing.T) { require.Equal(t, diffParser.limits.MaxPatchBytes, 0) } -func getDiffs(t testing.TB, rawDiff string, limits Limits) []*Diff { - t.Helper() +func getDiffs(tb testing.TB, rawDiff string, limits Limits) []*Diff { + tb.Helper() diffParser := NewDiffParser(strings.NewReader(rawDiff), limits) @@ -502,7 +502,7 @@ func getDiffs(t testing.TB, rawDiff string, limits Limits) []*Diff { diffs = append(diffs, &d) } - require.NoError(t, diffParser.Err()) + require.NoError(tb, diffParser.Err()) return diffs } diff --git a/internal/gitaly/hook/testhelper_test.go b/internal/gitaly/hook/testhelper_test.go index 0a1a4210d..683fb2790 100644 --- a/internal/gitaly/hook/testhelper_test.go +++ b/internal/gitaly/hook/testhelper_test.go @@ -23,9 +23,9 @@ func TestMain(m *testing.M) { testhelper.Run(m) } -func getExpectedEnv(ctx context.Context, t testing.TB, locator storage.Locator, gitCmdFactory git.CommandFactory, repo *gitalypb.Repository) []string { +func getExpectedEnv(ctx context.Context, tb testing.TB, locator storage.Locator, gitCmdFactory git.CommandFactory, repo *gitalypb.Repository) []string { repoPath, err := locator.GetPath(repo) - require.NoError(t, err) + require.NoError(tb, err) expectedEnv := map[string]string{ "GIT_DIR": repoPath, @@ -44,7 +44,7 @@ func getExpectedEnv(ctx context.Context, t testing.TB, locator storage.Locator, // we need to deduplicate environment variables here. for _, allowedEnvVar := range append(command.AllowedEnvironment(os.Environ()), execEnv.EnvironmentVariables...) { kv := strings.SplitN(allowedEnvVar, "=", 2) - require.Len(t, kv, 2) + require.Len(tb, kv, 2) expectedEnv[kv[0]] = kv[1] } diff --git a/internal/gitaly/rubyserver/concurrency_test.go b/internal/gitaly/rubyserver/concurrency_test.go index 21ba5496c..af6bd5c58 100644 --- a/internal/gitaly/rubyserver/concurrency_test.go +++ b/internal/gitaly/rubyserver/concurrency_test.go @@ -80,8 +80,8 @@ func BenchmarkConcurrency(b *testing.B) { }) } -func makeRequest(t testing.TB, s *Server) error { - ctx := testhelper.Context(t) +func makeRequest(tb testing.TB, s *Server) error { + ctx := testhelper.Context(tb) conn, err := s.getConnection(ctx) if err != nil { diff --git a/internal/gitaly/server/auth_test.go b/internal/gitaly/server/auth_test.go index 464feecc5..7cd8d9efa 100644 --- a/internal/gitaly/server/auth_test.go +++ b/internal/gitaly/server/auth_test.go @@ -169,8 +169,8 @@ func dial(serverSocketPath string, opts []grpc.DialOption) (*grpc.ClientConn, er return grpc.Dial(serverSocketPath, opts...) } -func healthCheck(t testing.TB, conn *grpc.ClientConn) error { - ctx := testhelper.Context(t) +func healthCheck(tb testing.TB, conn *grpc.ClientConn) error { + ctx := testhelper.Context(tb) _, err := healthpb.NewHealthClient(conn).Check(ctx, &healthpb.HealthCheckRequest{}) return err diff --git a/internal/gitaly/service/commit/testhelper_test.go b/internal/gitaly/service/commit/testhelper_test.go index 7d6734978..e3bf2327c 100644 --- a/internal/gitaly/service/commit/testhelper_test.go +++ b/internal/gitaly/service/commit/testhelper_test.go @@ -28,8 +28,8 @@ func TestMain(m *testing.M) { } // setupCommitService makes a basic configuration and starts the service with the client. -func setupCommitService(ctx context.Context, t testing.TB) (config.Cfg, gitalypb.CommitServiceClient) { - cfg, _, _, client := setupCommitServiceCreateRepo(ctx, t, func(ctx context.Context, tb testing.TB, cfg config.Cfg) (*gitalypb.Repository, string) { +func setupCommitService(ctx context.Context, tb testing.TB) (config.Cfg, gitalypb.CommitServiceClient) { + cfg, _, _, client := setupCommitServiceCreateRepo(ctx, tb, func(ctx context.Context, tb testing.TB, cfg config.Cfg) (*gitalypb.Repository, string) { return nil, "" }) return cfg, client @@ -37,9 +37,9 @@ func setupCommitService(ctx context.Context, t testing.TB) (config.Cfg, gitalypb // setupCommitServiceWithRepo makes a basic configuration, creates a test repository and starts the service with the client. func setupCommitServiceWithRepo( - ctx context.Context, t testing.TB, + ctx context.Context, tb testing.TB, ) (config.Cfg, *gitalypb.Repository, string, gitalypb.CommitServiceClient) { - return setupCommitServiceCreateRepo(ctx, t, func(ctx context.Context, tb testing.TB, cfg config.Cfg) (*gitalypb.Repository, string) { + return setupCommitServiceCreateRepo(ctx, tb, func(ctx context.Context, tb testing.TB, cfg config.Cfg) (*gitalypb.Repository, string) { repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ Seed: gittest.SeedGitLabTest, }) @@ -49,22 +49,22 @@ func setupCommitServiceWithRepo( func setupCommitServiceCreateRepo( ctx context.Context, - t testing.TB, + tb testing.TB, createRepo func(context.Context, testing.TB, config.Cfg) (*gitalypb.Repository, string), ) (config.Cfg, *gitalypb.Repository, string, gitalypb.CommitServiceClient) { - cfg := testcfg.Build(t) + cfg := testcfg.Build(tb) - cfg.SocketPath = startTestServices(t, cfg) - client := newCommitServiceClient(t, cfg.SocketPath) + cfg.SocketPath = startTestServices(tb, cfg) + client := newCommitServiceClient(tb, cfg.SocketPath) - repo, repoPath := createRepo(ctx, t, cfg) + repo, repoPath := createRepo(ctx, tb, cfg) return cfg, repo, repoPath, client } -func startTestServices(t testing.TB, cfg config.Cfg) string { - t.Helper() - return testserver.RunGitalyServer(t, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { +func startTestServices(tb testing.TB, cfg config.Cfg) string { + tb.Helper() + return testserver.RunGitalyServer(tb, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { gitalypb.RegisterCommitServiceServer(srv, NewServer( deps.GetLocator(), deps.GetGitCmdFactory(), @@ -85,15 +85,15 @@ func startTestServices(t testing.TB, cfg config.Cfg) string { }) } -func newCommitServiceClient(t testing.TB, serviceSocketPath string) gitalypb.CommitServiceClient { - t.Helper() +func newCommitServiceClient(tb testing.TB, serviceSocketPath string) gitalypb.CommitServiceClient { + tb.Helper() connOpts := []grpc.DialOption{ grpc.WithTransportCredentials(insecure.NewCredentials()), } conn, err := grpc.Dial(serviceSocketPath, connOpts...) - require.NoError(t, err) - t.Cleanup(func() { conn.Close() }) + require.NoError(tb, err) + tb.Cleanup(func() { conn.Close() }) return gitalypb.NewCommitServiceClient(conn) } @@ -111,14 +111,14 @@ type gitCommitsGetter interface { GetCommits() []*gitalypb.GitCommit } -func createCommits(t testing.TB, cfg config.Cfg, repoPath, branch string, commitCount int, parent git.ObjectID) git.ObjectID { +func createCommits(tb testing.TB, cfg config.Cfg, repoPath, branch string, commitCount int, parent git.ObjectID) git.ObjectID { for i := 0; i < commitCount; i++ { var parents []git.ObjectID if parent != "" { parents = append(parents, parent) } - parent = gittest.WriteCommit(t, cfg, repoPath, + parent = gittest.WriteCommit(tb, cfg, repoPath, gittest.WithBranch(branch), gittest.WithMessage(fmt.Sprintf("%s branch Empty commit %d", branch, i)), gittest.WithParents(parents...), @@ -128,8 +128,8 @@ func createCommits(t testing.TB, cfg config.Cfg, repoPath, branch string, commit return parent } -func getAllCommits(t testing.TB, getter func() (gitCommitsGetter, error)) []*gitalypb.GitCommit { - t.Helper() +func getAllCommits(tb testing.TB, getter func() (gitCommitsGetter, error)) []*gitalypb.GitCommit { + tb.Helper() var commits []*gitalypb.GitCommit for { @@ -137,7 +137,7 @@ func getAllCommits(t testing.TB, getter func() (gitCommitsGetter, error)) []*git if err == io.EOF { return commits } - require.NoError(t, err) + require.NoError(tb, err) commits = append(commits, resp.GetCommits()...) } diff --git a/internal/gitaly/service/conflicts/resolve_conflicts_test.go b/internal/gitaly/service/conflicts/resolve_conflicts_test.go index a8dddf7aa..d1b0ed41f 100644 --- a/internal/gitaly/service/conflicts/resolve_conflicts_test.go +++ b/internal/gitaly/service/conflicts/resolve_conflicts_test.go @@ -58,7 +58,7 @@ var ( ) func TestSuccessfulResolveConflictsRequestHelper(t *testing.T) { - var verifyFunc func(t testing.TB, pushOptions []string, stdin io.Reader) + var verifyFunc func(tb testing.TB, pushOptions []string, stdin io.Reader) verifyFuncProxy := func(t *testing.T, ctx context.Context, repo *gitalypb.Repository, pushOptions, env []string, stdin io.Reader, stdout, stderr io.Writer) error { // We use a proxy func here as we need to provide the hookManager dependency while creating the service but we only // know the commit IDs after the service is created. The proxy allows us to modify the verifyFunc after the service @@ -139,12 +139,12 @@ func TestSuccessfulResolveConflictsRequestHelper(t *testing.T) { theirCommitOID = commitConflict(theirCommitOID, targetBranch, "content-2") hookCount := 0 - verifyFunc = func(t testing.TB, pushOptions []string, stdin io.Reader) { + verifyFunc = func(tb testing.TB, pushOptions []string, stdin io.Reader) { changes, err := io.ReadAll(stdin) - require.NoError(t, err) + require.NoError(tb, err) pattern := fmt.Sprintf("%s .* refs/heads/%s\n", ourCommitOID, sourceBranch) - require.Regexp(t, regexp.MustCompile(pattern), string(changes)) - require.Empty(t, pushOptions) + require.Regexp(tb, regexp.MustCompile(pattern), string(changes)) + require.Empty(tb, pushOptions) hookCount++ } diff --git a/internal/gitaly/service/conflicts/testhelper_test.go b/internal/gitaly/service/conflicts/testhelper_test.go index fcfafc55b..b399e2f69 100644 --- a/internal/gitaly/service/conflicts/testhelper_test.go +++ b/internal/gitaly/service/conflicts/testhelper_test.go @@ -26,26 +26,26 @@ func TestMain(m *testing.M) { testhelper.Run(m) } -func setupConflictsService(ctx context.Context, t testing.TB, hookManager hook.Manager) (config.Cfg, *gitalypb.Repository, string, gitalypb.ConflictsServiceClient) { - cfg := testcfg.Build(t) +func setupConflictsService(ctx context.Context, tb testing.TB, hookManager hook.Manager) (config.Cfg, *gitalypb.Repository, string, gitalypb.ConflictsServiceClient) { + cfg := testcfg.Build(tb) - testcfg.BuildGitalyGit2Go(t, cfg) + testcfg.BuildGitalyGit2Go(tb, cfg) - serverSocketPath := runConflictsServer(t, cfg, hookManager) + serverSocketPath := runConflictsServer(tb, cfg, hookManager) cfg.SocketPath = serverSocketPath - client, conn := NewConflictsClient(t, serverSocketPath) - t.Cleanup(func() { conn.Close() }) + client, conn := NewConflictsClient(tb, serverSocketPath) + tb.Cleanup(func() { conn.Close() }) - repo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ Seed: gittest.SeedGitLabTest, }) return cfg, repo, repoPath, client } -func runConflictsServer(t testing.TB, cfg config.Cfg, hookManager hook.Manager) string { - return testserver.RunGitalyServer(t, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { +func runConflictsServer(tb testing.TB, cfg config.Cfg, hookManager hook.Manager) string { + return testserver.RunGitalyServer(tb, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { gitalypb.RegisterConflictsServiceServer(srv, NewServer( deps.GetHookManager(), deps.GetLocator(), @@ -81,14 +81,14 @@ func runConflictsServer(t testing.TB, cfg config.Cfg, hookManager hook.Manager) }, testserver.WithHookManager(hookManager)) } -func NewConflictsClient(t testing.TB, serverSocketPath string) (gitalypb.ConflictsServiceClient, *grpc.ClientConn) { +func NewConflictsClient(tb testing.TB, serverSocketPath string) (gitalypb.ConflictsServiceClient, *grpc.ClientConn) { connOpts := []grpc.DialOption{ grpc.WithTransportCredentials(insecure.NewCredentials()), } conn, err := grpc.Dial(serverSocketPath, connOpts...) if err != nil { - t.Fatal(err) + tb.Fatal(err) } return gitalypb.NewConflictsServiceClient(conn), conn diff --git a/internal/gitaly/service/diff/testhelper_test.go b/internal/gitaly/service/diff/testhelper_test.go index 25570c4ae..fe1c4db28 100644 --- a/internal/gitaly/service/diff/testhelper_test.go +++ b/internal/gitaly/service/diff/testhelper_test.go @@ -23,10 +23,10 @@ func TestMain(m *testing.M) { testhelper.Run(m) } -func setupDiffService(ctx context.Context, t testing.TB, opt ...testserver.GitalyServerOpt) (config.Cfg, *gitalypb.Repository, string, gitalypb.DiffServiceClient) { - cfg := testcfg.Build(t) +func setupDiffService(ctx context.Context, tb testing.TB, opt ...testserver.GitalyServerOpt) (config.Cfg, *gitalypb.Repository, string, gitalypb.DiffServiceClient) { + cfg := testcfg.Build(tb) - addr := testserver.RunGitalyServer(t, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { + addr := testserver.RunGitalyServer(tb, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { gitalypb.RegisterDiffServiceServer(srv, NewServer( deps.GetLocator(), deps.GetGitCmdFactory(), @@ -47,10 +47,10 @@ func setupDiffService(ctx context.Context, t testing.TB, opt ...testserver.Gital cfg.SocketPath = addr conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) - require.NoError(t, err) - t.Cleanup(func() { testhelper.MustClose(t, conn) }) + require.NoError(tb, err) + tb.Cleanup(func() { testhelper.MustClose(tb, conn) }) - repo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ Seed: gittest.SeedGitLabTest, }) diff --git a/internal/gitaly/service/hook/testhelper_test.go b/internal/gitaly/service/hook/testhelper_test.go index 33e3debe2..926d16ca4 100644 --- a/internal/gitaly/service/hook/testhelper_test.go +++ b/internal/gitaly/service/hook/testhelper_test.go @@ -23,30 +23,30 @@ func TestMain(m *testing.M) { testhelper.Run(m) } -func setupHookService(ctx context.Context, t testing.TB) (config.Cfg, *gitalypb.Repository, string, gitalypb.HookServiceClient) { - t.Helper() +func setupHookService(ctx context.Context, tb testing.TB) (config.Cfg, *gitalypb.Repository, string, gitalypb.HookServiceClient) { + tb.Helper() - cfg := testcfg.Build(t) - cfg.SocketPath = runHooksServer(t, cfg, nil) - client, conn := newHooksClient(t, cfg.SocketPath) - t.Cleanup(func() { conn.Close() }) + cfg := testcfg.Build(tb) + cfg.SocketPath = runHooksServer(tb, cfg, nil) + client, conn := newHooksClient(tb, cfg.SocketPath) + tb.Cleanup(func() { conn.Close() }) - repo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ Seed: gittest.SeedGitLabTest, }) return cfg, repo, repoPath, client } -func newHooksClient(t testing.TB, serverSocketPath string) (gitalypb.HookServiceClient, *grpc.ClientConn) { - t.Helper() +func newHooksClient(tb testing.TB, serverSocketPath string) (gitalypb.HookServiceClient, *grpc.ClientConn) { + tb.Helper() connOpts := []grpc.DialOption{ grpc.WithTransportCredentials(insecure.NewCredentials()), } conn, err := grpc.Dial(serverSocketPath, connOpts...) if err != nil { - t.Fatal(err) + tb.Fatal(err) } return gitalypb.NewHookServiceClient(conn), conn @@ -54,12 +54,12 @@ func newHooksClient(t testing.TB, serverSocketPath string) (gitalypb.HookService type serverOption func(*server) -func runHooksServer(t testing.TB, cfg config.Cfg, opts []serverOption, serverOpts ...testserver.GitalyServerOpt) string { - t.Helper() +func runHooksServer(tb testing.TB, cfg config.Cfg, opts []serverOption, serverOpts ...testserver.GitalyServerOpt) string { + tb.Helper() serverOpts = append(serverOpts, testserver.WithDisablePraefect()) - return testserver.RunGitalyServer(t, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { + return testserver.RunGitalyServer(tb, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { hookServer := NewServer( gitalyhook.NewManager(deps.GetCfg(), deps.GetLocator(), deps.GetGitCmdFactory(), deps.GetTxManager(), deps.GetGitlabClient()), deps.GetGitCmdFactory(), diff --git a/internal/gitaly/service/namespace/testhelper_test.go b/internal/gitaly/service/namespace/testhelper_test.go index 6323a164b..2fba9813b 100644 --- a/internal/gitaly/service/namespace/testhelper_test.go +++ b/internal/gitaly/service/namespace/testhelper_test.go @@ -16,17 +16,17 @@ import ( "google.golang.org/grpc/credentials/insecure" ) -func setupNamespaceService(t testing.TB, opts ...testserver.GitalyServerOpt) (config.Cfg, gitalypb.NamespaceServiceClient) { +func setupNamespaceService(tb testing.TB, opts ...testserver.GitalyServerOpt) (config.Cfg, gitalypb.NamespaceServiceClient) { cfgBuilder := testcfg.NewGitalyCfgBuilder(testcfg.WithStorages("default", "other")) - cfg := cfgBuilder.Build(t) + cfg := cfgBuilder.Build(tb) - addr := testserver.RunGitalyServer(t, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { + addr := testserver.RunGitalyServer(tb, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { gitalypb.RegisterNamespaceServiceServer(srv, NewServer(deps.GetLocator())) }, opts...) conn, err := grpc.Dial(addr, grpc.WithTransportCredentials(insecure.NewCredentials())) - require.NoError(t, err) - t.Cleanup(func() { testhelper.MustClose(t, conn) }) + require.NoError(tb, err) + tb.Cleanup(func() { testhelper.MustClose(tb, conn) }) return cfg, gitalypb.NewNamespaceServiceClient(conn) } diff --git a/internal/gitaly/service/objectpool/testhelper_test.go b/internal/gitaly/service/objectpool/testhelper_test.go index 39bbfbb78..0d37c3f23 100644 --- a/internal/gitaly/service/objectpool/testhelper_test.go +++ b/internal/gitaly/service/objectpool/testhelper_test.go @@ -101,46 +101,46 @@ func runObjectPoolServer(t *testing.T, cfg config.Cfg, locator storage.Locator, }, append(opts, testserver.WithLocator(locator), testserver.WithLogger(logger))...) } -func newObjectPool(t testing.TB, cfg config.Cfg, storage, relativePath string) *objectpool.ObjectPool { +func newObjectPool(tb testing.TB, cfg config.Cfg, storage, relativePath string) *objectpool.ObjectPool { catfileCache := catfile.NewCache(cfg) - t.Cleanup(catfileCache.Stop) + tb.Cleanup(catfileCache.Stop) txManager := transaction.NewManager(cfg, backchannel.NewRegistry()) pool, err := objectpool.NewObjectPool( config.NewLocator(cfg), - gittest.NewCommandFactory(t, cfg), + gittest.NewCommandFactory(tb, cfg), catfileCache, txManager, housekeeping.NewManager(cfg.Prometheus, txManager), storage, relativePath, ) - require.NoError(t, err) + require.NoError(tb, err) return pool } // initObjectPool creates a new empty object pool in the given storage. -func initObjectPool(t testing.TB, cfg config.Cfg, storage config.Storage) *objectpool.ObjectPool { - t.Helper() +func initObjectPool(tb testing.TB, cfg config.Cfg, storage config.Storage) *objectpool.ObjectPool { + tb.Helper() - relativePath := gittest.NewObjectPoolName(t) - gittest.InitRepoDir(t, storage.Path, relativePath) + relativePath := gittest.NewObjectPoolName(tb) + gittest.InitRepoDir(tb, storage.Path, relativePath) catfileCache := catfile.NewCache(cfg) - t.Cleanup(catfileCache.Stop) + tb.Cleanup(catfileCache.Stop) - pool := newObjectPool(t, cfg, storage.Name, relativePath) + pool := newObjectPool(tb, cfg, storage.Name, relativePath) poolPath := filepath.Join(storage.Path, relativePath) - t.Cleanup(func() { require.NoError(t, os.RemoveAll(poolPath)) }) + tb.Cleanup(func() { require.NoError(tb, os.RemoveAll(poolPath)) }) return pool } // rewrittenObjectPool returns a pool that is rewritten as if it was passed through Praefect. This should be used // to access the pool on the disk if the tests are running with Praefect in front of them. -func rewrittenObjectPool(ctx context.Context, t testing.TB, cfg config.Cfg, pool *objectpool.ObjectPool) *objectpool.ObjectPool { - replicaPath := gittest.GetReplicaPath(ctx, t, cfg, pool) - return newObjectPool(t, cfg, pool.GetStorageName(), replicaPath) +func rewrittenObjectPool(ctx context.Context, tb testing.TB, cfg config.Cfg, pool *objectpool.ObjectPool) *objectpool.ObjectPool { + replicaPath := gittest.GetReplicaPath(ctx, tb, cfg, pool) + return newObjectPool(tb, cfg, pool.GetStorageName(), replicaPath) } diff --git a/internal/gitaly/service/operations/apply_patch_test.go b/internal/gitaly/service/operations/apply_patch_test.go index f4d34318e..285977485 100644 --- a/internal/gitaly/service/operations/apply_patch_test.go +++ b/internal/gitaly/service/operations/apply_patch_test.go @@ -42,18 +42,18 @@ func TestUserApplyPatch(t *testing.T) { type actionFunc func(testing.TB, *localrepo.Repo) git2go.Action createFile := func(filepath string, content string) actionFunc { - return func(t testing.TB, repo *localrepo.Repo) git2go.Action { + return func(tb testing.TB, repo *localrepo.Repo) git2go.Action { fileOID, err := repo.WriteBlob(ctx, filepath, strings.NewReader(content)) - require.NoError(t, err) + require.NoError(tb, err) return git2go.CreateFile{Path: filepath, OID: fileOID.String()} } } updateFile := func(filepath string, content string) actionFunc { - return func(t testing.TB, repo *localrepo.Repo) git2go.Action { + return func(tb testing.TB, repo *localrepo.Repo) git2go.Action { fileOID, err := repo.WriteBlob(ctx, filepath, strings.NewReader(content)) - require.NoError(t, err) + require.NoError(tb, err) return git2go.UpdateFile{Path: filepath, OID: fileOID.String()} } diff --git a/internal/gitaly/service/operations/merge_test.go b/internal/gitaly/service/operations/merge_test.go index 22dbc32f8..7e7ab424b 100644 --- a/internal/gitaly/service/operations/merge_test.go +++ b/internal/gitaly/service/operations/merge_test.go @@ -1217,8 +1217,8 @@ func TestUserMergeToRef_conflicts(t *testing.T) { }) } -func buildUserMergeToRefRequest(t testing.TB, cfg config.Cfg, repo *gitalypb.Repository, repoPath string, sourceSha string, targetSha string, mergeBranchName string) *gitalypb.UserMergeToRefRequest { - gittest.Exec(t, cfg, "-C", repoPath, "branch", mergeBranchName, targetSha) +func buildUserMergeToRefRequest(tb testing.TB, cfg config.Cfg, repo *gitalypb.Repository, repoPath string, sourceSha string, targetSha string, mergeBranchName string) *gitalypb.UserMergeToRefRequest { + gittest.Exec(tb, cfg, "-C", repoPath, "branch", mergeBranchName, targetSha) return &gitalypb.UserMergeToRefRequest{ Repository: repo, diff --git a/internal/gitaly/service/operations/testhelper_test.go b/internal/gitaly/service/operations/testhelper_test.go index 9d5be410f..09908e809 100644 --- a/internal/gitaly/service/operations/testhelper_test.go +++ b/internal/gitaly/service/operations/testhelper_test.go @@ -38,29 +38,29 @@ func TestMain(m *testing.M) { testhelper.Run(m) } -func setupOperationsService(t testing.TB, ctx context.Context, options ...testserver.GitalyServerOpt) (context.Context, config.Cfg, *gitalypb.Repository, string, gitalypb.OperationServiceClient) { - cfg := testcfg.Build(t) - ctx, cfg, repo, repoPath, client := setupOperationsServiceWithCfg(t, ctx, cfg, options...) +func setupOperationsService(tb testing.TB, ctx context.Context, options ...testserver.GitalyServerOpt) (context.Context, config.Cfg, *gitalypb.Repository, string, gitalypb.OperationServiceClient) { + cfg := testcfg.Build(tb) + ctx, cfg, repo, repoPath, client := setupOperationsServiceWithCfg(tb, ctx, cfg, options...) return ctx, cfg, repo, repoPath, client } func setupOperationsServiceWithCfg( - t testing.TB, ctx context.Context, cfg config.Cfg, options ...testserver.GitalyServerOpt, + tb testing.TB, ctx context.Context, cfg config.Cfg, options ...testserver.GitalyServerOpt, ) (context.Context, config.Cfg, *gitalypb.Repository, string, gitalypb.OperationServiceClient) { - testcfg.BuildGitalySSH(t, cfg) - testcfg.BuildGitalyGit2Go(t, cfg) - testcfg.BuildGitalyHooks(t, cfg) + testcfg.BuildGitalySSH(tb, cfg) + testcfg.BuildGitalyGit2Go(tb, cfg) + testcfg.BuildGitalyHooks(tb, cfg) - serverSocketPath := runOperationServiceServer(t, cfg, options...) + serverSocketPath := runOperationServiceServer(tb, cfg, options...) cfg.SocketPath = serverSocketPath - client, conn := newOperationClient(t, serverSocketPath) - t.Cleanup(func() { conn.Close() }) + client, conn := newOperationClient(tb, serverSocketPath) + tb.Cleanup(func() { conn.Close() }) - md := testcfg.GitalyServersMetadataFromCfg(t, cfg) + md := testcfg.GitalyServersMetadataFromCfg(tb, cfg) ctx = testhelper.MergeOutgoingMetadata(ctx, md) - repo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ Seed: gittest.SeedGitLabTest, }) @@ -68,30 +68,30 @@ func setupOperationsServiceWithCfg( } func setupOperationsServiceWithoutRepo( - t testing.TB, ctx context.Context, options ...testserver.GitalyServerOpt, + tb testing.TB, ctx context.Context, options ...testserver.GitalyServerOpt, ) (context.Context, config.Cfg, gitalypb.OperationServiceClient) { - cfg := testcfg.Build(t) + cfg := testcfg.Build(tb) - testcfg.BuildGitalySSH(t, cfg) - testcfg.BuildGitalyGit2Go(t, cfg) - testcfg.BuildGitalyHooks(t, cfg) + testcfg.BuildGitalySSH(tb, cfg) + testcfg.BuildGitalyGit2Go(tb, cfg) + testcfg.BuildGitalyHooks(tb, cfg) - serverSocketPath := runOperationServiceServer(t, cfg, options...) + serverSocketPath := runOperationServiceServer(tb, cfg, options...) cfg.SocketPath = serverSocketPath - client, conn := newOperationClient(t, serverSocketPath) - t.Cleanup(func() { conn.Close() }) + client, conn := newOperationClient(tb, serverSocketPath) + tb.Cleanup(func() { conn.Close() }) - md := testcfg.GitalyServersMetadataFromCfg(t, cfg) + md := testcfg.GitalyServersMetadataFromCfg(tb, cfg) ctx = testhelper.MergeOutgoingMetadata(ctx, md) return ctx, cfg, client } -func runOperationServiceServer(t testing.TB, cfg config.Cfg, options ...testserver.GitalyServerOpt) string { - t.Helper() +func runOperationServiceServer(tb testing.TB, cfg config.Cfg, options ...testserver.GitalyServerOpt) string { + tb.Helper() - return testserver.RunGitalyServer(t, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { + return testserver.RunGitalyServer(tb, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { operationServer := NewServer( deps.GetHookManager(), deps.GetTxManager(), @@ -136,13 +136,13 @@ func runOperationServiceServer(t testing.TB, cfg config.Cfg, options ...testserv }, options...) } -func newOperationClient(t testing.TB, serverSocketPath string) (gitalypb.OperationServiceClient, *grpc.ClientConn) { +func newOperationClient(tb testing.TB, serverSocketPath string) (gitalypb.OperationServiceClient, *grpc.ClientConn) { connOpts := []grpc.DialOption{ grpc.WithTransportCredentials(insecure.NewCredentials()), } conn, err := grpc.Dial(serverSocketPath, connOpts...) if err != nil { - t.Fatal(err) + tb.Fatal(err) } return gitalypb.NewOperationServiceClient(conn), conn @@ -155,8 +155,8 @@ func newMuxedOperationClient(t *testing.T, ctx context.Context, serverSocketPath return gitalypb.NewOperationServiceClient(conn) } -func setupAndStartGitlabServer(t testing.TB, glID, glRepository string, cfg config.Cfg, gitPushOptions ...string) string { - url, cleanup := gitlab.SetupAndStartGitlabServer(t, cfg.GitlabShell.Dir, &gitlab.TestServerOptions{ +func setupAndStartGitlabServer(tb testing.TB, glID, glRepository string, cfg config.Cfg, gitPushOptions ...string) string { + url, cleanup := gitlab.SetupAndStartGitlabServer(tb, cfg.GitlabShell.Dir, &gitlab.TestServerOptions{ SecretToken: "secretToken", GLID: glID, GLRepository: glRepository, @@ -165,7 +165,7 @@ func setupAndStartGitlabServer(t testing.TB, glID, glRepository string, cfg conf GitPushOptions: gitPushOptions, }) - t.Cleanup(cleanup) + tb.Cleanup(cleanup) return url } diff --git a/internal/gitaly/service/ref/testhelper_test.go b/internal/gitaly/service/ref/testhelper_test.go index 7ae83ffed..0f94412dc 100644 --- a/internal/gitaly/service/ref/testhelper_test.go +++ b/internal/gitaly/service/ref/testhelper_test.go @@ -37,30 +37,30 @@ func TestMain(m *testing.M) { })) } -func setupRefService(ctx context.Context, t testing.TB) (config.Cfg, *gitalypb.Repository, string, gitalypb.RefServiceClient) { - cfg, client := setupRefServiceWithoutRepo(t) - repo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ +func setupRefService(ctx context.Context, tb testing.TB) (config.Cfg, *gitalypb.Repository, string, gitalypb.RefServiceClient) { + cfg, client := setupRefServiceWithoutRepo(tb) + repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ Seed: gittest.SeedGitLabTest, }) return cfg, repo, repoPath, client } -func setupRefServiceWithoutRepo(t testing.TB) (config.Cfg, gitalypb.RefServiceClient) { - cfg := testcfg.Build(t) +func setupRefServiceWithoutRepo(tb testing.TB) (config.Cfg, gitalypb.RefServiceClient) { + cfg := testcfg.Build(tb) - testcfg.BuildGitalyHooks(t, cfg) + testcfg.BuildGitalyHooks(tb, cfg) - serverSocketPath := runRefServiceServer(t, cfg) + serverSocketPath := runRefServiceServer(tb, cfg) cfg.SocketPath = serverSocketPath - client, conn := newRefServiceClient(t, serverSocketPath) - t.Cleanup(func() { conn.Close() }) + client, conn := newRefServiceClient(tb, serverSocketPath) + tb.Cleanup(func() { conn.Close() }) return cfg, client } -func runRefServiceServer(t testing.TB, cfg config.Cfg) string { - return testserver.RunGitalyServer(t, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { +func runRefServiceServer(tb testing.TB, cfg config.Cfg) string { + return testserver.RunGitalyServer(tb, cfg, nil, func(srv *grpc.Server, deps *service.Dependencies) { gitalypb.RegisterRefServiceServer(srv, NewServer( deps.GetLocator(), deps.GetGitCmdFactory(), @@ -82,12 +82,12 @@ func runRefServiceServer(t testing.TB, cfg config.Cfg) string { }) } -func newRefServiceClient(t testing.TB, serverSocketPath string) (gitalypb.RefServiceClient, *grpc.ClientConn) { +func newRefServiceClient(tb testing.TB, serverSocketPath string) (gitalypb.RefServiceClient, *grpc.ClientConn) { connOpts := []grpc.DialOption{ grpc.WithTransportCredentials(insecure.NewCredentials()), } conn, err := grpc.Dial(serverSocketPath, connOpts...) - require.NoError(t, err) + require.NoError(tb, err) return gitalypb.NewRefServiceClient(conn), conn } diff --git a/internal/gitaly/service/remote/update_remote_mirror_test.go b/internal/gitaly/service/remote/update_remote_mirror_test.go index b3a3ff0cc..8b74dd858 100644 --- a/internal/gitaly/service/remote/update_remote_mirror_test.go +++ b/internal/gitaly/service/remote/update_remote_mirror_test.go @@ -326,13 +326,13 @@ func TestUpdateRemoteMirror(t *testing.T) { "refs/heads/non-diverging": {"commit-3"}, }, keepDivergentRefs: true, - wrapCommandFactory: func(t testing.TB, original git.CommandFactory) git.CommandFactory { + wrapCommandFactory: func(tb testing.TB, original git.CommandFactory) git.CommandFactory { return commandFactoryWrapper{ CommandFactory: original, newFunc: func(ctx context.Context, repo repository.GitRepo, sc git.Cmd, opts ...git.CmdOpt) (*command.Command, error) { if sc.Subcommand() == "push" { subCmd, ok := sc.(git.SubCmd) - require.True(t, ok) + require.True(tb, ok) // This is really hacky: we extract the // remote name from the subcommands @@ -340,7 +340,7 @@ func TestUpdateRemoteMirror(t *testing.T) { // how we hijack the command factory is kind // of hacky in the first place. remoteName := subCmd.Args[0] - require.Contains(t, remoteName, "inmemory-") + require.Contains(tb, remoteName, "inmemory-") // Make the branch diverge on the remote before actually performing the pushes the RPC // is attempting to perform to simulate a ref diverging after the RPC has performed @@ -350,10 +350,10 @@ func TestUpdateRemoteMirror(t *testing.T) { Flags: []git.Option{git.Flag{Name: "--force"}}, Args: []string{remoteName, "refs/heads/non-diverging:refs/heads/diverging"}, }, opts...) - if !assert.NoError(t, err) { + if !assert.NoError(tb, err) { return nil, err } - assert.NoError(t, cmd.Wait()) + assert.NoError(tb, cmd.Wait()) } return original.New(ctx, repo, sc, opts...) @@ -427,7 +427,7 @@ func TestUpdateRemoteMirror(t *testing.T) { }, { desc: "pushes default branch in the first batch", - wrapCommandFactory: func(t testing.TB, original git.CommandFactory) git.CommandFactory { + wrapCommandFactory: func(tb testing.TB, original git.CommandFactory) git.CommandFactory { firstPush := true return commandFactoryWrapper{ CommandFactory: original, @@ -435,8 +435,8 @@ func TestUpdateRemoteMirror(t *testing.T) { if sc.Subcommand() == "push" && firstPush { firstPush = false args, err := sc.CommandArgs() - assert.NoError(t, err) - assert.Contains(t, args, "refs/heads/master", "first push should contain the default branch") + assert.NoError(tb, err) + assert.Contains(tb, args, "refs/heads/master", "first push should contain the default branch") } return original.New(ctx, repo, sc, opts...) diff --git a/internal/gitaly/service/repository/commit_graph_test.go b/internal/gitaly/service/repository/commit_graph_test.go index 2da765bf2..3d59dd272 100644 --- a/internal/gitaly/service/repository/commit_graph_test.go +++ b/internal/gitaly/service/repository/commit_graph_test.go @@ -206,21 +206,21 @@ func TestUpdateCommitGraph(t *testing.T) { assertModTimeAfter(t, mt, chainPath) } -func requireBloomFilterUsed(t testing.TB, repoPath string) { - t.Helper() +func requireBloomFilterUsed(tb testing.TB, repoPath string) { + tb.Helper() commitGraphsPath := filepath.Join(repoPath, stats.CommitGraphChainRelPath) - ids := bytes.Split(testhelper.MustReadFile(t, commitGraphsPath), []byte{'\n'}) + ids := bytes.Split(testhelper.MustReadFile(tb, commitGraphsPath), []byte{'\n'}) for _, id := range ids { if len(id) == 0 { continue } graphFilePath := filepath.Join(repoPath, filepath.Dir(stats.CommitGraphChainRelPath), fmt.Sprintf("graph-%s.graph", id)) - graphFileData := testhelper.MustReadFile(t, graphFilePath) + graphFileData := testhelper.MustReadFile(tb, graphFilePath) - require.True(t, bytes.HasPrefix(graphFileData, []byte("CGPH")), "4-byte signature of the commit graph file") - require.True(t, bytes.Contains(graphFileData, []byte("BIDX")), "Bloom Filter Index") - require.True(t, bytes.Contains(graphFileData, []byte("BDAT")), "Bloom Filter Data") + require.True(tb, bytes.HasPrefix(graphFileData, []byte("CGPH")), "4-byte signature of the commit graph file") + require.True(tb, bytes.Contains(graphFileData, []byte("BIDX")), "Bloom Filter Index") + require.True(tb, bytes.Contains(graphFileData, []byte("BDAT")), "Bloom Filter Data") } } diff --git a/internal/gitaly/service/repository/create_fork_test.go b/internal/gitaly/service/repository/create_fork_test.go index cf140b9ae..a9f6d99cb 100644 --- a/internal/gitaly/service/repository/create_fork_test.go +++ b/internal/gitaly/service/repository/create_fork_test.go @@ -291,8 +291,8 @@ func injectCustomCATestCerts(t *testing.T) (*x509.CertPool, config.TLS) { return pool, config.TLS{CertPath: certFile, KeyPath: keyFile} } -func newSecureRepoClient(t testing.TB, addr, token string, pool *x509.CertPool) (gitalypb.RepositoryServiceClient, *grpc.ClientConn) { - t.Helper() +func newSecureRepoClient(tb testing.TB, addr, token string, pool *x509.CertPool) (gitalypb.RepositoryServiceClient, *grpc.ClientConn) { + tb.Helper() connOpts := []grpc.DialOption{ grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{ @@ -303,7 +303,7 @@ func newSecureRepoClient(t testing.TB, addr, token string, pool *x509.CertPool) } conn, err := client.Dial(addr, connOpts) - require.NoError(t, err) + require.NoError(tb, err) return gitalypb.NewRepositoryServiceClient(conn), conn } diff --git a/internal/gitaly/service/repository/create_repository_from_url_test.go b/internal/gitaly/service/repository/create_repository_from_url_test.go index 764f0a12d..b2274bd27 100644 --- a/internal/gitaly/service/repository/create_repository_from_url_test.go +++ b/internal/gitaly/service/repository/create_repository_from_url_test.go @@ -310,16 +310,16 @@ func TestServer_CloneFromURLCommand_withMirror(t *testing.T) { require.Error(t, cmd.Wait()) } -func gitServerWithBasicAuth(ctx context.Context, t testing.TB, gitCmdFactory git.CommandFactory, user, pass, repoPath string) (int, func() error) { - return gittest.HTTPServer(ctx, t, gitCmdFactory, repoPath, basicAuthMiddleware(t, user, pass)) +func gitServerWithBasicAuth(ctx context.Context, tb testing.TB, gitCmdFactory git.CommandFactory, user, pass, repoPath string) (int, func() error) { + return gittest.HTTPServer(ctx, tb, gitCmdFactory, repoPath, basicAuthMiddleware(tb, user, pass)) } -func basicAuthMiddleware(t testing.TB, user, pass string) func(http.ResponseWriter, *http.Request, http.Handler) { +func basicAuthMiddleware(tb testing.TB, user, pass string) func(http.ResponseWriter, *http.Request, http.Handler) { return func(w http.ResponseWriter, r *http.Request, next http.Handler) { authUser, authPass, ok := r.BasicAuth() - require.True(t, ok, "should contain basic auth") - require.Equal(t, user, authUser, "username should match") - require.Equal(t, pass, authPass, "password should match") + require.True(tb, ok, "should contain basic auth") + require.Equal(tb, user, authUser, "username should match") + require.Equal(tb, pass, authPass, "password should match") next.ServeHTTP(w, r) } } diff --git a/internal/gitaly/service/repository/gc_test.go b/internal/gitaly/service/repository/gc_test.go index 3dcdb3a02..b3fd470d5 100644 --- a/internal/gitaly/service/repository/gc_test.go +++ b/internal/gitaly/service/repository/gc_test.go @@ -522,12 +522,12 @@ func TestCleanupInvalidKeepAroundRefs(t *testing.T) { } } -func mustCreateFileWithTimes(t testing.TB, path string, mTime time.Time) { - t.Helper() +func mustCreateFileWithTimes(tb testing.TB, path string, mTime time.Time) { + tb.Helper() - require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) - require.NoError(t, os.WriteFile(path, nil, 0o644)) - require.NoError(t, os.Chtimes(path, mTime, mTime)) + require.NoError(tb, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(tb, os.WriteFile(path, nil, 0o644)) + require.NoError(tb, os.Chtimes(path, mTime, mTime)) } func TestGarbageCollectDeltaIslands(t *testing.T) { diff --git a/internal/gitaly/service/repository/repack_test.go b/internal/gitaly/service/repository/repack_test.go index eb3d8b912..fb42f8d04 100644 --- a/internal/gitaly/service/repository/repack_test.go +++ b/internal/gitaly/service/repository/repack_test.go @@ -219,23 +219,23 @@ func TestRepackFullCollectLogStatistics(t *testing.T) { mustCountObjectLog(t, hook.AllEntries()...) } -func mustCountObjectLog(t testing.TB, entries ...*logrus.Entry) { - t.Helper() +func mustCountObjectLog(tb testing.TB, entries ...*logrus.Entry) { + tb.Helper() const key = "count_objects" for _, entry := range entries { if entry.Message == "git repo statistic" { - require.Contains(t, entry.Data, "grpc.request.glProjectPath") - require.Contains(t, entry.Data, "grpc.request.glRepository") - require.Contains(t, entry.Data, key, "statistics not found") + require.Contains(tb, entry.Data, "grpc.request.glProjectPath") + require.Contains(tb, entry.Data, "grpc.request.glRepository") + require.Contains(tb, entry.Data, key, "statistics not found") objectStats, ok := entry.Data[key].(map[string]interface{}) - require.True(t, ok, "expected count_objects to be a map") - require.Contains(t, objectStats, "count") + require.True(tb, ok, "expected count_objects to be a map") + require.Contains(tb, objectStats, "count") return } } - require.FailNow(t, "no info about statistics") + require.FailNow(tb, "no info about statistics") } func doBitmapsContainHashCache(t *testing.T, bitmapPaths []string) { diff --git a/internal/gitaly/service/repository/replicate_test.go b/internal/gitaly/service/repository/replicate_test.go index b35123e7a..89ca307b8 100644 --- a/internal/gitaly/service/repository/replicate_test.go +++ b/internal/gitaly/service/repository/replicate_test.go @@ -394,16 +394,16 @@ func TestReplicateRepository_BadRepository(t *testing.T) { { desc: "source invalid", invalidSource: true, - error: func(t testing.TB, actual error) { - testhelper.RequireGrpcError(t, ErrInvalidSourceRepository, actual) + error: func(tb testing.TB, actual error) { + testhelper.RequireGrpcError(tb, ErrInvalidSourceRepository, actual) }, }, { desc: "both invalid", invalidSource: true, invalidTarget: true, - error: func(t testing.TB, actual error) { - testhelper.RequireGrpcError(t, ErrInvalidSourceRepository, actual) + error: func(tb testing.TB, actual error) { + testhelper.RequireGrpcError(tb, ErrInvalidSourceRepository, actual) }, }, } { diff --git a/internal/gitaly/service/repository/snapshot_test.go b/internal/gitaly/service/repository/snapshot_test.go index ecc32563c..c10b9a7f8 100644 --- a/internal/gitaly/service/repository/snapshot_test.go +++ b/internal/gitaly/service/repository/snapshot_test.go @@ -24,8 +24,8 @@ import ( "google.golang.org/grpc/codes" ) -func getSnapshot(t testing.TB, client gitalypb.RepositoryServiceClient, req *gitalypb.GetSnapshotRequest) ([]byte, error) { - ctx := testhelper.Context(t) +func getSnapshot(tb testing.TB, client gitalypb.RepositoryServiceClient, req *gitalypb.GetSnapshotRequest) ([]byte, error) { + ctx := testhelper.Context(tb) stream, err := client.GetSnapshot(ctx, req) if err != nil { diff --git a/internal/gitaly/service/repository/testhelper_test.go b/internal/gitaly/service/repository/testhelper_test.go index 47845092c..24dc0d365 100644 --- a/internal/gitaly/service/repository/testhelper_test.go +++ b/internal/gitaly/service/repository/testhelper_test.go @@ -66,22 +66,22 @@ func TestWithRubySidecar(t *testing.T) { } } -func newRepositoryClient(t testing.TB, cfg config.Cfg, serverSocketPath string) gitalypb.RepositoryServiceClient { +func newRepositoryClient(tb testing.TB, cfg config.Cfg, serverSocketPath string) gitalypb.RepositoryServiceClient { var connOpts []grpc.DialOption if cfg.Auth.Token != "" { connOpts = append(connOpts, grpc.WithPerRPCCredentials(gitalyauth.RPCCredentialsV2(cfg.Auth.Token))) } conn, err := gclient.Dial(serverSocketPath, connOpts) - require.NoError(t, err) - t.Cleanup(func() { require.NoError(t, conn.Close()) }) + require.NoError(tb, err) + tb.Cleanup(func() { require.NoError(tb, conn.Close()) }) return gitalypb.NewRepositoryServiceClient(conn) } -func newObjectPoolClient(t testing.TB, cfg config.Cfg, serverSocketPath string) gitalypb.ObjectPoolServiceClient { +func newObjectPoolClient(tb testing.TB, cfg config.Cfg, serverSocketPath string) gitalypb.ObjectPoolServiceClient { conn, err := gclient.Dial(serverSocketPath, nil) - require.NoError(t, err) - t.Cleanup(func() { require.NoError(t, conn.Close()) }) + require.NoError(tb, err) + tb.Cleanup(func() { require.NoError(tb, conn.Close()) }) return gitalypb.NewObjectPoolServiceClient(conn) } @@ -111,8 +111,8 @@ func assertModTimeAfter(t *testing.T, afterTime time.Time, paths ...string) bool return t.Failed() } -func runRepositoryService(t testing.TB, cfg config.Cfg, rubySrv *rubyserver.Server, opts ...testserver.GitalyServerOpt) (gitalypb.RepositoryServiceClient, string) { - serverSocketPath := testserver.RunGitalyServer(t, cfg, rubySrv, func(srv *grpc.Server, deps *service.Dependencies) { +func runRepositoryService(tb testing.TB, cfg config.Cfg, rubySrv *rubyserver.Server, opts ...testserver.GitalyServerOpt) (gitalypb.RepositoryServiceClient, string) { + serverSocketPath := testserver.RunGitalyServer(tb, cfg, rubySrv, func(srv *grpc.Server, deps *service.Dependencies) { gitalypb.RegisterRepositoryServiceServer(srv, NewServer( cfg, deps.GetRubyServer(), @@ -158,35 +158,35 @@ func runRepositoryService(t testing.TB, cfg config.Cfg, rubySrv *rubyserver.Serv )) }, opts...) - return newRepositoryClient(t, cfg, serverSocketPath), serverSocketPath + return newRepositoryClient(tb, cfg, serverSocketPath), serverSocketPath } -func setupRepositoryService(ctx context.Context, t testing.TB, opts ...testserver.GitalyServerOpt) (config.Cfg, *gitalypb.Repository, string, gitalypb.RepositoryServiceClient) { - cfg, client := setupRepositoryServiceWithoutRepo(t, opts...) +func setupRepositoryService(ctx context.Context, tb testing.TB, opts ...testserver.GitalyServerOpt) (config.Cfg, *gitalypb.Repository, string, gitalypb.RepositoryServiceClient) { + cfg, client := setupRepositoryServiceWithoutRepo(tb, opts...) - repo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ Seed: gittest.SeedGitLabTest, }) return cfg, repo, repoPath, client } // Sets up a repository that has been cloned using `--mirror` which contains GitLab internal references -func setupRepositoryServiceFromMirror(ctx context.Context, t testing.TB, opts ...testserver.GitalyServerOpt) (config.Cfg, *gitalypb.Repository, string, gitalypb.RepositoryServiceClient) { - cfg, client := setupRepositoryServiceWithoutRepo(t, opts...) +func setupRepositoryServiceFromMirror(ctx context.Context, tb testing.TB, opts ...testserver.GitalyServerOpt) (config.Cfg, *gitalypb.Repository, string, gitalypb.RepositoryServiceClient) { + cfg, client := setupRepositoryServiceWithoutRepo(tb, opts...) - repo, repoPath := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + repo, repoPath := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ Seed: gittest.SeedGitLabTestMirror, }) return cfg, repo, repoPath, client } -func setupRepositoryServiceWithoutRepo(t testing.TB, opts ...testserver.GitalyServerOpt) (config.Cfg, gitalypb.RepositoryServiceClient) { - cfg := testcfg.Build(t) +func setupRepositoryServiceWithoutRepo(tb testing.TB, opts ...testserver.GitalyServerOpt) (config.Cfg, gitalypb.RepositoryServiceClient) { + cfg := testcfg.Build(tb) - testcfg.BuildGitalyHooks(t, cfg) - testcfg.BuildGitalySSH(t, cfg) + testcfg.BuildGitalyHooks(tb, cfg) + testcfg.BuildGitalySSH(tb, cfg) - client, serverSocketPath := runRepositoryService(t, cfg, nil, opts...) + client, serverSocketPath := runRepositoryService(tb, cfg, nil, opts...) cfg.SocketPath = serverSocketPath return cfg, client diff --git a/internal/gitaly/service/smarthttp/inforefs_test.go b/internal/gitaly/service/smarthttp/inforefs_test.go index ef47aabb0..cc72902ef 100644 --- a/internal/gitaly/service/smarthttp/inforefs_test.go +++ b/internal/gitaly/service/smarthttp/inforefs_test.go @@ -527,25 +527,25 @@ func withInfoRefCache(cache infoRefCache) ServerOpt { } } -func createInvalidRepo(t testing.TB, repoDir string) func() { +func createInvalidRepo(tb testing.TB, repoDir string) func() { for _, subDir := range []string{"objects", "refs", "HEAD"} { - require.NoError(t, os.MkdirAll(filepath.Join(repoDir, subDir), 0o755)) + require.NoError(tb, os.MkdirAll(filepath.Join(repoDir, subDir), 0o755)) } - return func() { require.NoError(t, os.RemoveAll(repoDir)) } + return func() { require.NoError(tb, os.RemoveAll(repoDir)) } } -func replaceCachedResponse(t testing.TB, ctx context.Context, cache *cache.DiskCache, req *gitalypb.InfoRefsRequest, newContents string) { - path := pathToCachedResponse(t, ctx, cache, req) - require.NoError(t, os.WriteFile(path, []byte(newContents), 0o644)) +func replaceCachedResponse(tb testing.TB, ctx context.Context, cache *cache.DiskCache, req *gitalypb.InfoRefsRequest, newContents string) { + path := pathToCachedResponse(tb, ctx, cache, req) + require.NoError(tb, os.WriteFile(path, []byte(newContents), 0o644)) } func setInfoRefsUploadPackMethod(ctx context.Context) context.Context { return testhelper.SetCtxGrpcMethod(ctx, "/gitaly.SmartHTTPService/InfoRefsUploadPack") } -func pathToCachedResponse(t testing.TB, ctx context.Context, cache *cache.DiskCache, req *gitalypb.InfoRefsRequest) string { +func pathToCachedResponse(tb testing.TB, ctx context.Context, cache *cache.DiskCache, req *gitalypb.InfoRefsRequest) string { ctx = setInfoRefsUploadPackMethod(ctx) path, err := cache.KeyPath(ctx, req.GetRepository(), req) - require.NoError(t, err) + require.NoError(tb, err) return path } diff --git a/internal/gitaly/service/smarthttp/receive_pack_test.go b/internal/gitaly/service/smarthttp/receive_pack_test.go index df6e855ed..b78ef4467 100644 --- a/internal/gitaly/service/smarthttp/receive_pack_test.go +++ b/internal/gitaly/service/smarthttp/receive_pack_test.go @@ -957,8 +957,8 @@ func drainPostReceivePackResponse(stream gitalypb.SmartHTTPService_PostReceivePa // requireSideband compares the actual sideband data to expected sideband data. This function is // required to filter out any keep-alive packets which Git may send over the sideband and which are // kind of unpredictable for us. -func requireSideband(t testing.TB, expectedSidebandMessages []string, actualInput string) { - t.Helper() +func requireSideband(tb testing.TB, expectedSidebandMessages []string, actualInput string) { + tb.Helper() scanner := pktline.NewScanner(strings.NewReader(actualInput)) @@ -969,7 +969,7 @@ func requireSideband(t testing.TB, expectedSidebandMessages []string, actualInpu // Flush packets terminate the communication via side-channels, so we expect them to // come. if pktline.IsFlush(payload) { - require.Equal(t, expectedSidebandMessages, actualSidebandMessages) + require.Equal(tb, expectedSidebandMessages, actualSidebandMessages) return } @@ -983,5 +983,5 @@ func requireSideband(t testing.TB, expectedSidebandMessages []string, actualInpu actualSidebandMessages = append(actualSidebandMessages, string(payload)) } - require.FailNow(t, "expected to receive a flush to terminate the protocol") + require.FailNow(tb, "expected to receive a flush to terminate the protocol") } diff --git a/internal/gitaly/service/wiki/testhelper_test.go b/internal/gitaly/service/wiki/testhelper_test.go index 3d024241f..0dda852a7 100644 --- a/internal/gitaly/service/wiki/testhelper_test.go +++ b/internal/gitaly/service/wiki/testhelper_test.go @@ -73,8 +73,8 @@ func TestWithRubySidecar(t *testing.T) { } } -func setupWikiService(t testing.TB, cfg config.Cfg, rubySrv *rubyserver.Server) (gitalypb.WikiServiceClient, string) { - addr := testserver.RunGitalyServer(t, cfg, rubySrv, func(srv *grpc.Server, deps *service.Dependencies) { +func setupWikiService(tb testing.TB, cfg config.Cfg, rubySrv *rubyserver.Server) (gitalypb.WikiServiceClient, string) { + addr := testserver.RunGitalyServer(tb, cfg, rubySrv, func(srv *grpc.Server, deps *service.Dependencies) { gitalypb.RegisterHookServiceServer(srv, hook.NewServer( deps.GetHookManager(), deps.GetGitCmdFactory(), @@ -92,17 +92,17 @@ func setupWikiService(t testing.TB, cfg config.Cfg, rubySrv *rubyserver.Server) deps.GetHousekeepingManager(), )) }) - testcfg.BuildGitalyHooks(t, cfg) - client := newWikiClient(t, addr) + testcfg.BuildGitalyHooks(tb, cfg) + client := newWikiClient(tb, addr) return client, addr } -func newWikiClient(t testing.TB, serverSocketPath string) gitalypb.WikiServiceClient { - t.Helper() +func newWikiClient(tb testing.TB, serverSocketPath string) gitalypb.WikiServiceClient { + tb.Helper() conn, err := grpc.Dial(serverSocketPath, grpc.WithTransportCredentials(insecure.NewCredentials())) - require.NoError(t, err) - t.Cleanup(func() { conn.Close() }) + require.NoError(tb, err) + tb.Cleanup(func() { conn.Close() }) return gitalypb.NewWikiServiceClient(conn) } diff --git a/internal/gitlab/test_server.go b/internal/gitlab/test_server.go index 4a3f62d35..b23e4b251 100644 --- a/internal/gitlab/test_server.go +++ b/internal/gitlab/test_server.go @@ -25,12 +25,12 @@ var changeLineRegex = regexp.MustCompile("^[a-f0-9]{40} [a-f0-9]{40} refs/[^ ]+$ const secretHeaderName = "Gitlab-Shared-Secret" // WriteShellSecretFile writes a .gitlab_shell_secret file in the specified directory -func WriteShellSecretFile(t testing.TB, dir, secretToken string) string { - t.Helper() +func WriteShellSecretFile(tb testing.TB, dir, secretToken string) string { + tb.Helper() - require.NoError(t, os.MkdirAll(dir, os.ModeDir)) + require.NoError(tb, os.MkdirAll(dir, os.ModeDir)) filePath := filepath.Join(dir, ".gitlab_shell_secret") - require.NoError(t, os.WriteFile(filePath, []byte(secretToken), 0o644)) + require.NoError(tb, os.WriteFile(filePath, []byte(secretToken), 0o644)) return filePath } @@ -60,27 +60,27 @@ type TestServerOptions struct { } // NewTestServer returns a mock gitlab server that responds to the hook api endpoints -func NewTestServer(t testing.TB, options TestServerOptions) (url string, cleanup func()) { - t.Helper() +func NewTestServer(tb testing.TB, options TestServerOptions) (url string, cleanup func()) { + tb.Helper() mux := http.NewServeMux() prefix := strings.TrimRight(options.RelativeURLRoot, "/") + "/api/v4/internal" - mux.Handle(prefix+"/allowed", http.HandlerFunc(handleAllowed(t, options))) - mux.Handle(prefix+"/pre_receive", http.HandlerFunc(handlePreReceive(t, options))) + mux.Handle(prefix+"/allowed", http.HandlerFunc(handleAllowed(tb, options))) + mux.Handle(prefix+"/pre_receive", http.HandlerFunc(handlePreReceive(tb, options))) mux.Handle(prefix+"/post_receive", http.HandlerFunc(handlePostReceive(options))) - mux.Handle(prefix+"/check", http.HandlerFunc(handleCheck(t, options))) - mux.Handle(prefix+"/lfs", http.HandlerFunc(handleLfs(t, options))) + mux.Handle(prefix+"/check", http.HandlerFunc(handleCheck(tb, options))) + mux.Handle(prefix+"/lfs", http.HandlerFunc(handleLfs(tb, options))) var tlsCfg *tls.Config if options.ClientCACertPath != "" { caCertPEM, err := os.ReadFile(options.ClientCACertPath) - require.NoError(t, err) + require.NoError(tb, err) certPool := x509.NewCertPool() - require.True(t, certPool.AppendCertsFromPEM(caCertPEM)) + require.True(tb, certPool.AppendCertsFromPEM(caCertPEM)) serverCert, err := tls.LoadX509KeyPair(options.ServerCertPath, options.ServerKeyPath) - require.NoError(t, err) + require.NoError(tb, err) tlsCfg = &tls.Config{ ClientCAs: certPool, @@ -91,7 +91,7 @@ func NewTestServer(t testing.TB, options TestServerOptions) (url string, cleanup } if options.UnixSocket { - return startSocketHTTPServer(t, mux, tlsCfg) + return startSocketHTTPServer(tb, mux, tlsCfg) } var server *httptest.Server @@ -137,7 +137,7 @@ func parsePostReceiveForm(u url.Values) postReceiveForm { } } -func handleAllowed(t testing.TB, options TestServerOptions) func(w http.ResponseWriter, r *http.Request) { +func handleAllowed(tb testing.TB, options TestServerOptions) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "could not parse form", http.StatusBadRequest) @@ -260,7 +260,7 @@ func handleAllowed(t testing.TB, options TestServerOptions) func(w http.Response } if relObjectDir != gitVars.GitObjectDirRel { _, err := w.Write([]byte(`{"status":false}`)) - require.NoError(t, err) + require.NoError(tb, err) return } } @@ -280,7 +280,7 @@ func handleAllowed(t testing.TB, options TestServerOptions) func(w http.Response if relAltObjectDir != gitVars.GitAlternateObjectDirsRel[i] { _, err := w.Write([]byte(`{"status":false}`)) - require.NoError(t, err) + require.NoError(tb, err) return } } @@ -300,17 +300,17 @@ func handleAllowed(t testing.TB, options TestServerOptions) func(w http.Response if authenticated { _, err := w.Write([]byte(`{"status":true}`)) - require.NoError(t, err) + require.NoError(tb, err) return } w.WriteHeader(http.StatusUnauthorized) _, err = w.Write([]byte(`{"message":"401 Unauthorized\n"}`)) - require.NoError(t, err) + require.NoError(tb, err) } } -func handlePreReceive(t testing.TB, options TestServerOptions) func(w http.ResponseWriter, r *http.Request) { +func handlePreReceive(tb testing.TB, options TestServerOptions) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "could not parse form", http.StatusBadRequest) @@ -387,7 +387,7 @@ func handlePreReceive(t testing.TB, options TestServerOptions) func(w http.Respo w.WriteHeader(http.StatusOK) _, err = w.Write([]byte(`{"reference_counter_increased": true}`)) - require.NoError(t, err) + require.NoError(tb, err) } } @@ -502,12 +502,12 @@ func handlePostReceive(options TestServerOptions) func(w http.ResponseWriter, r } } -func handleCheck(t testing.TB, options TestServerOptions) func(w http.ResponseWriter, r *http.Request) { +func handleCheck(tb testing.TB, options TestServerOptions) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { u, p, ok := r.BasicAuth() if !ok || u != options.User || p != options.Password { w.WriteHeader(http.StatusUnauthorized) - require.NoError(t, json.NewEncoder(w).Encode(struct { + require.NoError(tb, json.NewEncoder(w).Encode(struct { Message string `json:"message"` }{Message: "authorization failed"})) return @@ -518,7 +518,7 @@ func handleCheck(t testing.TB, options TestServerOptions) func(w http.ResponseWr } } -func handleLfs(t testing.TB, options TestServerOptions) func(w http.ResponseWriter, r *http.Request) { +func handleLfs(tb testing.TB, options TestServerOptions) func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, "couldn't parse form", http.StatusBadRequest) @@ -552,17 +552,17 @@ func handleLfs(t testing.TB, options TestServerOptions) func(w http.ResponseWrit if options.LfsBody != "" { _, err := w.Write([]byte(options.LfsBody)) - require.NoError(t, err) + require.NoError(tb, err) } } } -func startSocketHTTPServer(t testing.TB, mux *http.ServeMux, tlsCfg *tls.Config) (string, func()) { - tempDir := testhelper.TempDir(t) +func startSocketHTTPServer(tb testing.TB, mux *http.ServeMux, tlsCfg *tls.Config) (string, func()) { + tempDir := testhelper.TempDir(tb) filename := filepath.Join(tempDir, "http-test-server") socketListener, err := net.Listen("unix", filename) - require.NoError(t, err) + require.NoError(tb, err) server := http.Server{ Handler: mux, @@ -573,7 +573,7 @@ func startSocketHTTPServer(t testing.TB, mux *http.ServeMux, tlsCfg *tls.Config) url := "http+unix://" + filename cleanup := func() { - require.NoError(t, server.Close()) + require.NoError(tb, server.Close()) } return url, cleanup @@ -581,10 +581,10 @@ func startSocketHTTPServer(t testing.TB, mux *http.ServeMux, tlsCfg *tls.Config) // SetupAndStartGitlabServer creates a new GitlabTestServer, starts it and sets // up the gitlab-shell secret. -func SetupAndStartGitlabServer(t testing.TB, shellDir string, c *TestServerOptions) (string, func()) { - url, cleanup := NewTestServer(t, *c) +func SetupAndStartGitlabServer(tb testing.TB, shellDir string, c *TestServerOptions) (string, func()) { + url, cleanup := NewTestServer(tb, *c) - WriteShellSecretFile(t, shellDir, c.SecretToken) + WriteShellSecretFile(tb, shellDir, c.SecretToken) return url, cleanup } diff --git a/internal/middleware/cache/cache_test.go b/internal/middleware/cache/cache_test.go index 38d8cad01..1b5b78240 100644 --- a/internal/middleware/cache/cache_test.go +++ b/internal/middleware/cache/cache_test.go @@ -173,7 +173,7 @@ func (mc *mockCache) StartLease(repo *gitalypb.Repository) (diskcache.LeaseEnder return mc, nil } -func newTestSvc(t testing.TB, ctx context.Context, srvr *grpc.Server, svc testdata.TestServiceServer) (testdata.TestServiceClient, *grpc.ClientConn, func()) { +func newTestSvc(tb testing.TB, ctx context.Context, srvr *grpc.Server, svc testdata.TestServiceServer) (testdata.TestServiceClient, *grpc.ClientConn, func()) { healthSrvr := health.NewServer() grpc_health_v1.RegisterHealthServer(srvr, healthSrvr) healthSrvr.SetServingStatus("TestService", grpc_health_v1.HealthCheckResponse_SERVING) @@ -181,7 +181,7 @@ func newTestSvc(t testing.TB, ctx context.Context, srvr *grpc.Server, svc testda testdata.RegisterInterceptedServiceServer(srvr, &testdata.UnimplementedInterceptedServiceServer{}) lis, err := net.Listen("tcp", ":0") - require.NoError(t, err) + require.NoError(tb, err) errQ := make(chan error) @@ -191,7 +191,7 @@ func newTestSvc(t testing.TB, ctx context.Context, srvr *grpc.Server, svc testda cleanup := func() { srvr.Stop() - require.NoError(t, <-errQ) + require.NoError(tb, <-errQ) } cc, err := grpc.DialContext( @@ -200,7 +200,7 @@ func newTestSvc(t testing.TB, ctx context.Context, srvr *grpc.Server, svc testda grpc.WithBlock(), grpc.WithTransportCredentials(insecure.NewCredentials()), ) - require.NoError(t, err) + require.NoError(tb, err) return testdata.NewTestServiceClient(cc), cc, cleanup } diff --git a/internal/praefect/coordinator_test.go b/internal/praefect/coordinator_test.go index 37e495ad5..5722e8abc 100644 --- a/internal/praefect/coordinator_test.go +++ b/internal/praefect/coordinator_test.go @@ -2610,17 +2610,17 @@ func TestNewRequestFinalizer_contextIsDisjointedFromTheRPC(t *testing.T) { ctx, cancel := context.WithDeadline(context.WithValue(ctx, ctxKey{}, "value"), parentDeadline) defer cancel() - requireSuppressedCancellation := func(t testing.TB, ctx context.Context) { + requireSuppressedCancellation := func(tb testing.TB, ctx context.Context) { deadline, ok := ctx.Deadline() - require.True(t, ok) - require.NotEqual(t, parentDeadline, deadline) - require.Equal(t, ctx.Value(ctxKey{}), "value") - require.Nil(t, ctx.Err()) + require.True(tb, ok) + require.NotEqual(tb, parentDeadline, deadline) + require.Equal(tb, ctx.Value(ctxKey{}), "value") + require.Nil(tb, ctx.Err()) select { case <-ctx.Done(): - t.Fatal("context should not be canceled if the parent is canceled") + tb.Fatal("context should not be canceled if the parent is canceled") default: - require.NotNil(t, ctx.Done()) + require.NotNil(tb, ctx.Done()) } } diff --git a/internal/praefect/datastore/assignment_test.go b/internal/praefect/datastore/assignment_test.go index 56a771e2d..61ac24ec4 100644 --- a/internal/praefect/datastore/assignment_test.go +++ b/internal/praefect/datastore/assignment_test.go @@ -119,16 +119,16 @@ func TestAssignmentStore_SetReplicationFactor(t *testing.T) { type matcher func(testing.TB, []string) equal := func(expected []string) matcher { - return func(t testing.TB, actual []string) { - t.Helper() - require.Equal(t, expected, actual) + return func(tb testing.TB, actual []string) { + tb.Helper() + require.Equal(tb, expected, actual) } } contains := func(expecteds ...[]string) matcher { - return func(t testing.TB, actual []string) { - t.Helper() - require.Contains(t, expecteds, actual) + return func(tb testing.TB, actual []string) { + tb.Helper() + require.Contains(tb, expecteds, actual) } } diff --git a/internal/praefect/datastore/repository_store_test.go b/internal/praefect/datastore/repository_store_test.go index 3b6ba6709..e47d2d431 100644 --- a/internal/praefect/datastore/repository_store_test.go +++ b/internal/praefect/datastore/repository_store_test.go @@ -37,10 +37,10 @@ type replicaRecord struct { // It structured as virtual-storage->relative_path->storage->replicaRecord type storageState map[string]map[string]map[string]replicaRecord -func requireState(t testing.TB, ctx context.Context, db glsql.Querier, vss virtualStorageState, ss storageState) { - t.Helper() +func requireState(tb testing.TB, ctx context.Context, db glsql.Querier, vss virtualStorageState, ss storageState) { + tb.Helper() - requireVirtualStorageState := func(t testing.TB, ctx context.Context, exp virtualStorageState) { + requireVirtualStorageState := func(tb testing.TB, ctx context.Context, exp virtualStorageState) { rows, err := db.QueryContext(ctx, ` SELECT repository_id, virtual_storage, relative_path, replica_path, "primary", assigned_storages FROM repositories @@ -51,7 +51,7 @@ LEFT JOIN ( ) AS repository_assignments USING (repository_id, virtual_storage, relative_path) `) - require.NoError(t, err) + require.NoError(tb, err) defer rows.Close() act := make(virtualStorageState) @@ -62,7 +62,7 @@ LEFT JOIN ( primary sql.NullString assignments glsql.StringArray ) - require.NoError(t, rows.Scan(&repositoryID, &virtualStorage, &relativePath, &replicaPath, &primary, &assignments)) + require.NoError(tb, rows.Scan(&repositoryID, &virtualStorage, &relativePath, &replicaPath, &primary, &assignments)) if act[virtualStorage] == nil { act[virtualStorage] = make(map[string]repositoryRecord) } @@ -75,16 +75,16 @@ LEFT JOIN ( } } - require.NoError(t, rows.Err()) - require.Equal(t, exp, act) + require.NoError(tb, rows.Err()) + require.Equal(tb, exp, act) } - requireStorageState := func(t testing.TB, ctx context.Context, exp storageState) { + requireStorageState := func(tb testing.TB, ctx context.Context, exp storageState) { rows, err := db.QueryContext(ctx, ` SELECT repository_id, virtual_storage, relative_path, storage, generation FROM storage_repositories `) - require.NoError(t, err) + require.NoError(tb, err) defer rows.Close() act := make(storageState) @@ -92,7 +92,7 @@ FROM storage_repositories var repositoryID sql.NullInt64 var vs, rel, storage string var gen int - require.NoError(t, rows.Scan(&repositoryID, &vs, &rel, &storage, &gen)) + require.NoError(tb, rows.Scan(&repositoryID, &vs, &rel, &storage, &gen)) if act[vs] == nil { act[vs] = make(map[string]map[string]replicaRecord) @@ -104,12 +104,12 @@ FROM storage_repositories act[vs][rel][storage] = replicaRecord{repositoryID: repositoryID.Int64, generation: gen} } - require.NoError(t, rows.Err()) - require.Equal(t, exp, act) + require.NoError(tb, rows.Err()) + require.Equal(tb, exp, act) } - requireVirtualStorageState(t, ctx, vss) - requireStorageState(t, ctx, ss) + requireVirtualStorageState(tb, ctx, vss) + requireStorageState(tb, ctx, ss) } func TestRepositoryStore_Postgres(t *testing.T) { diff --git a/internal/praefect/datastore/storage_cleanup_test.go b/internal/praefect/datastore/storage_cleanup_test.go index 88666e801..568116727 100644 --- a/internal/praefect/datastore/storage_cleanup_test.go +++ b/internal/praefect/datastore/storage_cleanup_test.go @@ -249,20 +249,20 @@ type storageCleanupRow struct { TriggeredAt sql.NullTime } -func getAllStoragesCleanup(t testing.TB, db testdb.DB) []storageCleanupRow { +func getAllStoragesCleanup(tb testing.TB, db testdb.DB) []storageCleanupRow { rows, err := db.Query(`SELECT * FROM storage_cleanups`) - require.NoError(t, err) + require.NoError(tb, err) defer func() { - require.NoError(t, rows.Close()) + require.NoError(tb, rows.Close()) }() var res []storageCleanupRow for rows.Next() { var dst storageCleanupRow err := rows.Scan(&dst.VirtualStorage, &dst.Storage, &dst.LastRun, &dst.TriggeredAt) - require.NoError(t, err) + require.NoError(tb, err) res = append(res, dst) } - require.NoError(t, rows.Err()) + require.NoError(tb, rows.Err()) return res } diff --git a/internal/praefect/nodes/health_manager_test.go b/internal/praefect/nodes/health_manager_test.go index c31903de9..92959e37f 100644 --- a/internal/praefect/nodes/health_manager_test.go +++ b/internal/praefect/nodes/health_manager_test.go @@ -604,8 +604,8 @@ func TestHealthManager_databaseTimeout(t *testing.T) { require.EqualError(t, <-blockedErr, "update checks: timeout: context canceled") } -func predateHealthChecks(t testing.TB, db testdb.DB, amount time.Duration) { - t.Helper() +func predateHealthChecks(tb testing.TB, db testdb.DB, amount time.Duration) { + tb.Helper() _, err := db.Exec(` UPDATE node_status SET @@ -613,7 +613,7 @@ func predateHealthChecks(t testing.TB, db testdb.DB, amount time.Duration) { last_seen_active_at = last_seen_active_at - INTERVAL '1 MICROSECOND' * $1 `, amount.Microseconds(), ) - require.NoError(t, err) + require.NoError(tb, err) } // This test case ensures the record updates are done in an ordered manner to avoid concurrent writes diff --git a/internal/praefect/nodes/per_repository_test.go b/internal/praefect/nodes/per_repository_test.go index e361b3ff1..3a75736f8 100644 --- a/internal/praefect/nodes/per_repository_test.go +++ b/internal/praefect/nodes/per_repository_test.go @@ -27,18 +27,18 @@ func TestPerRepositoryElector(t *testing.T) { type state map[string]map[string]map[string]storageRecord - type matcher func(t testing.TB, primary string) + type matcher func(tb testing.TB, primary string) any := func(expected ...string) matcher { - return func(t testing.TB, primary string) { - t.Helper() - require.Contains(t, expected, primary) + return func(tb testing.TB, primary string) { + tb.Helper() + require.Contains(tb, expected, primary) } } noPrimary := func() matcher { - return func(t testing.TB, primary string) { - t.Helper() - require.Empty(t, primary) + return func(tb testing.TB, primary string) { + tb.Helper() + require.Empty(tb, primary) } } diff --git a/internal/praefect/nodes/sql_elector_test.go b/internal/praefect/nodes/sql_elector_test.go index df5af8eaa..b2c90ac21 100644 --- a/internal/praefect/nodes/sql_elector_test.go +++ b/internal/praefect/nodes/sql_elector_test.go @@ -258,21 +258,21 @@ func TestElectDemotedPrimary(t *testing.T) { // predateLastSeenActiveAt shifts the last_seen_active_at column to an earlier time. This avoids // waiting for the node's status to become unhealthy. -func predateLastSeenActiveAt(t testing.TB, db testdb.DB, shardName, nodeName string, amount time.Duration) { - t.Helper() +func predateLastSeenActiveAt(tb testing.TB, db testdb.DB, shardName, nodeName string, amount time.Duration) { + tb.Helper() _, err := db.Exec(` UPDATE node_status SET last_seen_active_at = last_seen_active_at - INTERVAL '1 MICROSECOND' * $1 WHERE shard_name = $2 AND node_name = $3`, amount.Microseconds(), shardName, nodeName, ) - require.NoError(t, err) + require.NoError(tb, err) } // predateElection shifts the election to an earlier time. This avoids waiting for the failover timeout to trigger // a new election. -func predateElection(t testing.TB, ctx context.Context, db glsql.Querier, shardName string, amount time.Duration) { - t.Helper() +func predateElection(tb testing.TB, ctx context.Context, db glsql.Querier, shardName string, amount time.Duration) { + tb.Helper() _, err := db.ExecContext(ctx, "UPDATE shard_primaries SET elected_at = elected_at - INTERVAL '1 MICROSECOND' * $1 WHERE shard_name = $2", @@ -280,7 +280,7 @@ func predateElection(t testing.TB, ctx context.Context, db glsql.Querier, shardN shardName, ) - require.NoError(t, err) + require.NoError(tb, err) } func TestElectNewPrimary(t *testing.T) { diff --git a/internal/praefect/repocleaner/repository_test.go b/internal/praefect/repocleaner/repository_test.go index 37b2e90d7..441540a13 100644 --- a/internal/praefect/repocleaner/repository_test.go +++ b/internal/praefect/repocleaner/repository_test.go @@ -360,11 +360,11 @@ func (as actionStub) Perform(ctx context.Context, virtualStorage, storage string return nil } -func waitReceive(t testing.TB, waitChan <-chan struct{}) { - t.Helper() +func waitReceive(tb testing.TB, waitChan <-chan struct{}) { + tb.Helper() select { case <-waitChan: case <-time.After(time.Minute): - require.FailNow(t, "waiting for too long") + require.FailNow(tb, "waiting for too long") } } diff --git a/internal/praefect/testserver.go b/internal/praefect/testserver.go index fbbd58d2e..f957634cf 100644 --- a/internal/praefect/testserver.go +++ b/internal/praefect/testserver.go @@ -59,19 +59,19 @@ type BuildOptions struct { } // WithMockBackends mocks backends with a set of passed in stubs. -func WithMockBackends(t testing.TB, backends map[string]mock.SimpleServiceServer) func([]*config.VirtualStorage) []testhelper.Cleanup { +func WithMockBackends(tb testing.TB, backends map[string]mock.SimpleServiceServer) func([]*config.VirtualStorage) []testhelper.Cleanup { return func(virtualStorages []*config.VirtualStorage) []testhelper.Cleanup { var cleanups []testhelper.Cleanup for _, vs := range virtualStorages { - require.Equal(t, len(backends), len(vs.Nodes), + require.Equal(tb, len(backends), len(vs.Nodes), "mock server count doesn't match config nodes") for i, node := range vs.Nodes { backend, ok := backends[node.Storage] - require.True(t, ok, "missing backend server for node %s", node.Storage) + require.True(tb, ok, "missing backend server for node %s", node.Storage) - backendAddr, cleanup := newMockDownstream(t, node.Token, backend) + backendAddr, cleanup := newMockDownstream(tb, node.Token, backend) cleanups = append(cleanups, cleanup) node.Address = backendAddr @@ -83,19 +83,19 @@ func WithMockBackends(t testing.TB, backends map[string]mock.SimpleServiceServer } } -func defaultQueue(t testing.TB) datastore.ReplicationEventQueue { - return datastore.NewPostgresReplicationEventQueue(testdb.New(t)) +func defaultQueue(tb testing.TB) datastore.ReplicationEventQueue { + return datastore.NewPostgresReplicationEventQueue(testdb.New(tb)) } func defaultTxMgr(conf config.Config) *transactions.Manager { return transactions.NewManager(conf) } -func defaultNodeMgr(t testing.TB, conf config.Config, rs datastore.RepositoryStore) nodes.Manager { - nodeMgr, err := nodes.NewManager(testhelper.NewDiscardingLogEntry(t), conf, nil, rs, promtest.NewMockHistogramVec(), protoregistry.GitalyProtoPreregistered, nil, nil, nil) - require.NoError(t, err) +func defaultNodeMgr(tb testing.TB, conf config.Config, rs datastore.RepositoryStore) nodes.Manager { + nodeMgr, err := nodes.NewManager(testhelper.NewDiscardingLogEntry(tb), conf, nil, rs, promtest.NewMockHistogramVec(), protoregistry.GitalyProtoPreregistered, nil, nil, nil) + require.NoError(tb, err) nodeMgr.Start(0, time.Hour) - t.Cleanup(nodeMgr.Stop) + tb.Cleanup(nodeMgr.Stop) return nodeMgr } @@ -182,7 +182,7 @@ func startProcessBacklog(ctx context.Context, replMgr ReplMgr) <-chan struct{} { // and release all acquired resources. // The function should be used only for testing purposes and not as part of the production code. func RunPraefectServer( - t testing.TB, + tb testing.TB, ctx context.Context, conf config.Config, opt BuildOptions, @@ -190,7 +190,7 @@ func RunPraefectServer( var cleanups []testhelper.Cleanup if opt.WithQueue == nil { - opt.WithQueue = defaultQueue(t) + opt.WithQueue = defaultQueue(tb) } if opt.WithRepoStore == nil { opt.WithRepoStore = defaultRepoStore(conf) @@ -208,7 +208,7 @@ func RunPraefectServer( opt.WithLogger = log.Default() } if opt.WithNodeMgr == nil { - opt.WithNodeMgr = defaultNodeMgr(t, conf, opt.WithRepoStore) + opt.WithNodeMgr = defaultNodeMgr(tb, conf, opt.WithRepoStore) } if opt.WithAssignmentStore == nil { opt.WithAssignmentStore = NewDisabledAssignmentStore(conf.StorageNames()) @@ -253,7 +253,7 @@ func RunPraefectServer( opt.WithChecks, ) - listener, port := listenAvailPort(t) + listener, port := listenAvailPort(tb) errQ := make(chan error) ctx, cancel := context.WithCancel(ctx) @@ -265,7 +265,7 @@ func RunPraefectServer( replMgrDone := startProcessBacklog(ctx, replmgr) // dial client to praefect - cc := dialLocalPort(t, port, false) + cc := dialLocalPort(tb, port, false) cleanup := func() { cc.Close() @@ -278,7 +278,7 @@ func RunPraefectServer( cancel() <-replMgrDone - require.NoError(t, <-errQ) + require.NoError(tb, <-errQ) } return cc, prf, cleanup diff --git a/internal/praefect/transaction_test.go b/internal/praefect/transaction_test.go index d709ac83d..472f294d9 100644 --- a/internal/praefect/transaction_test.go +++ b/internal/praefect/transaction_test.go @@ -29,10 +29,10 @@ type voter struct { shouldSucceed bool } -func runPraefectServerAndTxMgr(t testing.TB, ctx context.Context) (*grpc.ClientConn, *transactions.Manager, testhelper.Cleanup) { +func runPraefectServerAndTxMgr(tb testing.TB, ctx context.Context) (*grpc.ClientConn, *transactions.Manager, testhelper.Cleanup) { conf := testConfig(1) txMgr := transactions.NewManager(conf) - cc, _, cleanup := RunPraefectServer(t, ctx, conf, BuildOptions{ + cc, _, cleanup := RunPraefectServer(tb, ctx, conf, BuildOptions{ WithTxMgr: txMgr, WithNodeMgr: nullNodeMgr{}, // to suppress node address issues }) diff --git a/internal/praefect/verifier_test.go b/internal/praefect/verifier_test.go index f152779d9..f2252e0ad 100644 --- a/internal/praefect/verifier_test.go +++ b/internal/praefect/verifier_test.go @@ -744,7 +744,7 @@ gitaly_praefect_verification_jobs_dequeued_total{storage="gitaly-2",virtual_stor // getAllReplicas gets all replicas from the database except for the locked-repository which is created // by the test suite to ensure non-blocking queries. -func getAllReplicas(ctx context.Context, t testing.TB, db glsql.Querier) map[string]map[string][]string { +func getAllReplicas(ctx context.Context, tb testing.TB, db glsql.Querier) map[string]map[string][]string { rows, err := db.QueryContext(ctx, ` SELECT repositories.virtual_storage, repositories.relative_path, storage FROM repositories @@ -752,13 +752,13 @@ func getAllReplicas(ctx context.Context, t testing.TB, db glsql.Querier) map[str WHERE repositories.relative_path != 'locked-repository' ORDER BY virtual_storage, relative_path, storage `) - require.NoError(t, err) + require.NoError(tb, err) defer rows.Close() results := map[string]map[string][]string{} for rows.Next() { var virtualStorage, relativePath, storage string - require.NoError(t, rows.Scan(&virtualStorage, &relativePath, &storage)) + require.NoError(tb, rows.Scan(&virtualStorage, &relativePath, &storage)) if results[virtualStorage] == nil { results[virtualStorage] = map[string][]string{} @@ -766,7 +766,7 @@ func getAllReplicas(ctx context.Context, t testing.TB, db glsql.Querier) map[str results[virtualStorage][relativePath] = append(results[virtualStorage][relativePath], storage) } - require.NoError(t, rows.Err()) + require.NoError(tb, rows.Err()) return results } diff --git a/internal/safe/file_writer_test.go b/internal/safe/file_writer_test.go index f5d035bce..83992a25a 100644 --- a/internal/safe/file_writer_test.go +++ b/internal/safe/file_writer_test.go @@ -128,8 +128,8 @@ func TestFileWriter_commitBeforeClose(t *testing.T) { require.FileExists(t, dstPath) } -func dirEmpty(t testing.TB, dirPath string) bool { +func dirEmpty(tb testing.TB, dirPath string) bool { infos, err := os.ReadDir(dirPath) - require.NoError(t, err) + require.NoError(tb, err) return len(infos) == 0 } diff --git a/internal/testhelper/grpc.go b/internal/testhelper/grpc.go index 536894d16..8cf96b326 100644 --- a/internal/testhelper/grpc.go +++ b/internal/testhelper/grpc.go @@ -35,27 +35,27 @@ func (mockServerTransportStream) SetTrailer(md metadata.MD) error { return nil } // It can accept not only proto.Message, but slices, maps, and structs too. // This is required as comparing messages directly with `require.Equal` doesn't // work. -func ProtoEqual(t testing.TB, expected, actual interface{}) { - t.Helper() - require.Empty(t, cmp.Diff(expected, actual, protocmp.Transform(), cmpopts.EquateErrors())) +func ProtoEqual(tb testing.TB, expected, actual interface{}) { + tb.Helper() + require.Empty(tb, cmp.Diff(expected, actual, protocmp.Transform(), cmpopts.EquateErrors())) } // RequireGrpcCode asserts that the error has the expected gRPC status code. -func RequireGrpcCode(t testing.TB, err error, expectedCode codes.Code) { - t.Helper() +func RequireGrpcCode(tb testing.TB, err error, expectedCode codes.Code) { + tb.Helper() - require.Error(t, err) + require.Error(tb, err) status, ok := status.FromError(err) - require.True(t, ok) - require.Equal(t, expectedCode, status.Code()) + require.True(tb, ok) + require.Equal(tb, expectedCode, status.Code()) } // RequireGrpcError asserts that expected and actual gRPC errors are equal. Comparing gRPC errors // directly with `require.Equal()` will not typically work correct. -func RequireGrpcError(t testing.TB, expected, actual error) { - t.Helper() +func RequireGrpcError(tb testing.TB, expected, actual error) { + tb.Helper() // .Proto() handles nil receiver - ProtoEqual(t, status.Convert(expected).Proto(), status.Convert(actual).Proto()) + ProtoEqual(tb, status.Convert(expected).Proto(), status.Convert(actual).Proto()) } // MergeOutgoingMetadata merges provided metadata-s and returns context with resulting value. diff --git a/internal/testhelper/testcfg/build.go b/internal/testhelper/testcfg/build.go index d1d9e7a8b..3d527a041 100644 --- a/internal/testhelper/testcfg/build.go +++ b/internal/testhelper/testcfg/build.go @@ -20,47 +20,47 @@ import ( var buildOnceByName sync.Map // BuildGitalyGit2Go builds the gitaly-git2go command and installs it into the binary directory. -func BuildGitalyGit2Go(t testing.TB, cfg config.Cfg) string { - return buildGitalyCommand(t, cfg, "gitaly-git2go") +func BuildGitalyGit2Go(tb testing.TB, cfg config.Cfg) string { + return buildGitalyCommand(tb, cfg, "gitaly-git2go") } // BuildGitalyWrapper builds the gitaly-wrapper command and installs it into the binary directory. -func BuildGitalyWrapper(t *testing.T, cfg config.Cfg) string { - return buildGitalyCommand(t, cfg, "gitaly-wrapper") +func BuildGitalyWrapper(tb testing.TB, cfg config.Cfg) string { + return buildGitalyCommand(tb, cfg, "gitaly-wrapper") } // BuildGitalyLFSSmudge builds the gitaly-lfs-smudge command and installs it into the binary // directory. -func BuildGitalyLFSSmudge(t *testing.T, cfg config.Cfg) string { - return buildGitalyCommand(t, cfg, "gitaly-lfs-smudge") +func BuildGitalyLFSSmudge(tb testing.TB, cfg config.Cfg) string { + return buildGitalyCommand(tb, cfg, "gitaly-lfs-smudge") } // BuildGitalyHooks builds the gitaly-hooks command and installs it into the binary directory. -func BuildGitalyHooks(t testing.TB, cfg config.Cfg) string { - return buildGitalyCommand(t, cfg, "gitaly-hooks") +func BuildGitalyHooks(tb testing.TB, cfg config.Cfg) string { + return buildGitalyCommand(tb, cfg, "gitaly-hooks") } // BuildGitalySSH builds the gitaly-ssh command and installs it into the binary directory. -func BuildGitalySSH(t testing.TB, cfg config.Cfg) string { - return buildGitalyCommand(t, cfg, "gitaly-ssh") +func BuildGitalySSH(tb testing.TB, cfg config.Cfg) string { + return buildGitalyCommand(tb, cfg, "gitaly-ssh") } // BuildPraefect builds the praefect command and installs it into the binary directory. -func BuildPraefect(t testing.TB, cfg config.Cfg) string { - return buildGitalyCommand(t, cfg, "praefect") +func BuildPraefect(tb testing.TB, cfg config.Cfg) string { + return buildGitalyCommand(tb, cfg, "praefect") } // BuildGitaly builds the gitaly binary and installs it into the binary directory. The gitaly binary // embeds other binaries it needs to use when servicing requests. The packed binaries are not built // prior to building this gitaly binary and thus cannot be guaranteed to be from the same build. -func BuildGitaly(t testing.TB, cfg config.Cfg) string { - return buildGitalyCommand(t, cfg, "gitaly") +func BuildGitaly(tb testing.TB, cfg config.Cfg) string { + return buildGitalyCommand(tb, cfg, "gitaly") } // buildGitalyCommand builds an executable and places it in the correct directory depending // whether it is packed in the production build or not. -func buildGitalyCommand(t testing.TB, cfg config.Cfg, executableName string) string { - return BuildBinary(t, filepath.Dir(cfg.BinaryPath(executableName)), gitalyCommandPath(executableName)) +func buildGitalyCommand(tb testing.TB, cfg config.Cfg, executableName string) string { + return BuildBinary(tb, filepath.Dir(cfg.BinaryPath(executableName)), gitalyCommandPath(executableName)) } var ( @@ -71,11 +71,11 @@ var ( // BuildBinary builds a Go binary once and copies it into the target directory. The source path can // either be a ".go" file or a directory containing Go files. Returns the path to the executable in // the destination directory. -func BuildBinary(t testing.TB, targetDir, sourcePath string) string { +func BuildBinary(tb testing.TB, targetDir, sourcePath string) string { createGlobalBinaryDirectoryOnce.Do(func() { - sharedBinariesDir = testhelper.CreateGlobalDirectory(t, "bins") + sharedBinariesDir = testhelper.CreateGlobalDirectory(tb, "bins") }) - require.NotEmpty(t, sharedBinariesDir, "creation of shared binary directory failed") + require.NotEmpty(tb, sharedBinariesDir, "creation of shared binary directory failed") var ( // executableName is the name of the executable. @@ -88,13 +88,13 @@ func BuildBinary(t testing.TB, targetDir, sourcePath string) string { buildOnceInterface, _ := buildOnceByName.LoadOrStore(executableName, &sync.Once{}) buildOnce, ok := buildOnceInterface.(*sync.Once) - require.True(t, ok) + require.True(tb, ok) buildOnce.Do(func() { - require.NoFileExists(t, sharedBinaryPath, "binary has already been built") + require.NoFileExists(tb, sharedBinaryPath, "binary has already been built") - cfg := Build(t) - gitCommandFactory := gittest.NewCommandFactory(t, cfg) + cfg := Build(tb) + gitCommandFactory := gittest.NewCommandFactory(tb, cfg) gitExecEnv := gitCommandFactory.GetExecutionEnvironment(context.TODO()) // Unfortunately, Go has started to execute Git as parts of its build process in @@ -145,9 +145,9 @@ func BuildBinary(t testing.TB, targetDir, sourcePath string) string { // Instead, we just override the system-level gitconfig to point to a temporary file // that contains this setting. _, currentFile, _, ok := runtime.Caller(0) - require.True(t, ok) - gitconfigPath := filepath.Join(testhelper.TempDir(t), "gitconfig") - require.NoError(t, os.WriteFile(gitconfigPath, []byte( + require.True(tb, ok) + gitconfigPath := filepath.Join(testhelper.TempDir(tb), "gitconfig") + require.NoError(tb, os.WriteFile(gitconfigPath, []byte( "[safe]\ndirectory = "+filepath.Join(filepath.Dir(currentFile), "..", "..", "..")+"\n"), 0o400), ) gitEnvironment = append(gitEnvironment, @@ -171,20 +171,20 @@ func BuildBinary(t testing.TB, targetDir, sourcePath string) string { cmd.Env = gitEnvironment output, err := cmd.CombinedOutput() - require.NoError(t, err, "building Go executable: %v, output: %q", err, output) + require.NoError(tb, err, "building Go executable: %v, output: %q", err, output) }) - require.FileExists(t, sharedBinaryPath, "%s does not exist", executableName) - require.NoFileExists(t, targetPath, "%s exists already -- do you try to build it twice?", executableName) + require.FileExists(tb, sharedBinaryPath, "%s does not exist", executableName) + require.NoFileExists(tb, targetPath, "%s exists already -- do you try to build it twice?", executableName) - require.NoError(t, os.MkdirAll(targetDir, os.ModePerm)) + require.NoError(tb, os.MkdirAll(targetDir, os.ModePerm)) // We hard-link the file into place instead of copying it because copying used to cause // ETXTBSY errors in CI. This is likely caused by a bug in the overlay filesystem used by // Docker, so we just work around this by linking the file instead. It's more efficient // anyway, the only thing is that no test must modify the binary directly. But let's count // on that. - require.NoError(t, os.Link(sharedBinaryPath, targetPath)) + require.NoError(tb, os.Link(sharedBinaryPath, targetPath)) return targetPath } diff --git a/internal/testhelper/testcfg/gitaly_builder.go b/internal/testhelper/testcfg/gitaly_builder.go index d1ea23283..e8aead0f4 100644 --- a/internal/testhelper/testcfg/gitaly_builder.go +++ b/internal/testhelper/testcfg/gitaly_builder.go @@ -75,50 +75,50 @@ type GitalyCfgBuilder struct { } // Build setups required filesystem structure, creates and returns configuration of the gitaly service. -func (gc *GitalyCfgBuilder) Build(t testing.TB) config.Cfg { - t.Helper() +func (gc *GitalyCfgBuilder) Build(tb testing.TB) config.Cfg { + tb.Helper() cfg := gc.cfg if cfg.SocketPath == "" { cfg.SocketPath = UnconfiguredSocketPath } - root := testhelper.TempDir(t) + root := testhelper.TempDir(tb) if cfg.BinDir == "" { cfg.BinDir = filepath.Join(root, "bin.d") - require.NoError(t, os.Mkdir(cfg.BinDir, 0o755)) + require.NoError(tb, os.Mkdir(cfg.BinDir, 0o755)) } if cfg.Ruby.Dir == "" { _, currentFile, _, ok := runtime.Caller(0) - require.True(t, ok, "could not get caller info") + require.True(tb, ok, "could not get caller info") cfg.Ruby.Dir = filepath.Join(filepath.Dir(currentFile), "../../../ruby") } if cfg.Logging.Dir == "" { cfg.Logging.Dir = filepath.Join(root, "log.d") - require.NoError(t, os.Mkdir(cfg.Logging.Dir, 0o755)) + require.NoError(tb, os.Mkdir(cfg.Logging.Dir, 0o755)) } if cfg.GitlabShell.Dir == "" { cfg.GitlabShell.Dir = filepath.Join(root, "shell.d") - require.NoError(t, os.Mkdir(cfg.GitlabShell.Dir, 0o755)) + require.NoError(tb, os.Mkdir(cfg.GitlabShell.Dir, 0o755)) } if cfg.RuntimeDir == "" { cfg.RuntimeDir = filepath.Join(root, "runtime.d") - require.NoError(t, os.Mkdir(cfg.RuntimeDir, 0o700)) - require.NoError(t, os.Mkdir(cfg.InternalSocketDir(), 0o755)) + require.NoError(tb, os.Mkdir(cfg.RuntimeDir, 0o700)) + require.NoError(tb, os.Mkdir(cfg.InternalSocketDir(), 0o755)) } if len(cfg.Storages) != 0 && len(gc.storages) != 0 { - require.FailNow(t, "invalid configuration build setup: fix storages configured") + require.FailNow(tb, "invalid configuration build setup: fix storages configured") } if len(cfg.Storages) == 0 { storagesDir := filepath.Join(root, "storages.d") - require.NoError(t, os.Mkdir(storagesDir, 0o755)) + require.NoError(tb, os.Mkdir(storagesDir, 0o755)) if len(gc.storages) == 0 { gc.storages = []string{"default"} @@ -128,7 +128,7 @@ func (gc *GitalyCfgBuilder) Build(t testing.TB) config.Cfg { cfg.Storages = make([]config.Storage, len(gc.storages)) for i, storageName := range gc.storages { storagePath := filepath.Join(storagesDir, storageName) - require.NoError(t, os.MkdirAll(storagePath, 0o755)) + require.NoError(tb, os.MkdirAll(storagePath, 0o755)) cfg.Storages[i].Name = storageName cfg.Storages[i].Path = storagePath } @@ -138,7 +138,7 @@ func (gc *GitalyCfgBuilder) Build(t testing.TB) config.Cfg { if cfg.Ruby.LinguistLanguagesPath == "" { // set a stub to prevent a long ruby process to run where it is not needed cfg.Ruby.LinguistLanguagesPath = filepath.Join(root, "linguist_languages.json") - require.NoError(t, os.WriteFile(cfg.Ruby.LinguistLanguagesPath, []byte(`{}`), 0o655)) + require.NoError(tb, os.WriteFile(cfg.Ruby.LinguistLanguagesPath, []byte(`{}`), 0o655)) } } @@ -147,23 +147,23 @@ func (gc *GitalyCfgBuilder) Build(t testing.TB) config.Cfg { // to have lying around. cfg.Git.IgnoreGitconfig = true - require.NoError(t, cfg.Validate()) + require.NoError(tb, cfg.Validate()) return cfg } // BuildWithRepoAt setups required filesystem structure, creates and returns configuration of the gitaly service, // clones test repository into each configured storage the provided relative path. -func (gc *GitalyCfgBuilder) BuildWithRepoAt(t testing.TB, relativePath string) (config.Cfg, []*gitalypb.Repository) { - t.Helper() +func (gc *GitalyCfgBuilder) BuildWithRepoAt(tb testing.TB, relativePath string) (config.Cfg, []*gitalypb.Repository) { + tb.Helper() - ctx := testhelper.Context(t) - cfg := gc.Build(t) + ctx := testhelper.Context(tb) + cfg := gc.Build(tb) // clone the test repo to the each storage repos := make([]*gitalypb.Repository, len(cfg.Storages)) for i, gitalyStorage := range cfg.Storages { - repo, _ := gittest.CreateRepository(ctx, t, cfg, gittest.CreateRepositoryConfig{ + repo, _ := gittest.CreateRepository(ctx, tb, cfg, gittest.CreateRepositoryConfig{ SkipCreationViaService: true, Storage: gitalyStorage, RelativePath: relativePath, @@ -178,18 +178,18 @@ 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 { +func Build(tb testing.TB, opts ...Option) config.Cfg { cfgBuilder := NewGitalyCfgBuilder(opts...) - return cfgBuilder.Build(t) + return cfgBuilder.Build(tb) } // BuildWithRepo creates a minimal configuration setup with no options. // 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) { +func BuildWithRepo(tb testing.TB, opts ...Option) (config.Cfg, *gitalypb.Repository, string) { cfgBuilder := NewGitalyCfgBuilder(opts...) - cfg, repos := cfgBuilder.BuildWithRepoAt(t, t.Name()) + cfg, repos := cfgBuilder.BuildWithRepoAt(tb, tb.Name()) repoPath := filepath.Join(cfg.Storages[0].Path, repos[0].RelativePath) return cfg, repos[0], repoPath } diff --git a/internal/testhelper/testcfg/metadata.go b/internal/testhelper/testcfg/metadata.go index 071f6c77b..2913c2869 100644 --- a/internal/testhelper/testcfg/metadata.go +++ b/internal/testhelper/testcfg/metadata.go @@ -13,7 +13,7 @@ import ( // GitalyServersMetadataFromCfg returns a metadata pair for gitaly-servers to be used in // inter-gitaly operations. -func GitalyServersMetadataFromCfg(t testing.TB, cfg config.Cfg) metadata.MD { +func GitalyServersMetadataFromCfg(tb testing.TB, cfg config.Cfg) metadata.MD { gitalyServers := storage.GitalyServers{} storages: for _, s := range cfg.Storages { @@ -27,12 +27,12 @@ storages: continue storages } } - require.FailNow(t, "no address found on the config") + require.FailNow(tb, "no address found on the config") } gitalyServersJSON, err := json.Marshal(gitalyServers) if err != nil { - t.Fatal(err) + tb.Fatal(err) } return metadata.Pairs("gitaly-servers", base64.StdEncoding.EncodeToString(gitalyServersJSON)) diff --git a/internal/testhelper/testdb/db.go b/internal/testhelper/testdb/db.go index edb474a74..c909859c1 100644 --- a/internal/testhelper/testdb/db.go +++ b/internal/testhelper/testdb/db.go @@ -36,10 +36,10 @@ type TxWrapper struct { // Rollback executes Rollback operation on the wrapped *sql.Tx if it is set. // After execution is sets Tx to nil to prevent errors on the repeated invocations (useful // for testing when Rollback is deferred). -func (txw *TxWrapper) Rollback(t testing.TB) { - t.Helper() +func (txw *TxWrapper) Rollback(tb testing.TB) { + tb.Helper() if txw.Tx != nil { - require.NoError(t, txw.Tx.Rollback()) + require.NoError(tb, txw.Tx.Rollback()) txw.Tx = nil } } @@ -47,10 +47,10 @@ func (txw *TxWrapper) Rollback(t testing.TB) { // Commit executes Commit operation on the wrapped *sql.Tx if it is set. // After execution is sets Tx to nil to prevent errors on the deferred invocations (useful // for testing when Rollback is deferred). -func (txw *TxWrapper) Commit(t testing.TB) { - t.Helper() +func (txw *TxWrapper) Commit(tb testing.TB) { + tb.Helper() if txw.Tx != nil { - require.NoError(t, txw.Tx.Commit()) + require.NoError(tb, txw.Tx.Commit()) txw.Tx = nil } } @@ -63,38 +63,38 @@ type DB struct { } // Begin starts a new transaction and returns it wrapped into TxWrapper. -func (db DB) Begin(t testing.TB) *TxWrapper { - t.Helper() +func (db DB) Begin(tb testing.TB) *TxWrapper { + tb.Helper() tx, err := db.DB.Begin() - require.NoError(t, err) + require.NoError(tb, err) return &TxWrapper{Tx: tx} } // Truncate removes all data from the list of tables and restarts identities for them. -func (db DB) Truncate(t testing.TB, tables ...string) { - t.Helper() +func (db DB) Truncate(tb testing.TB, tables ...string) { + tb.Helper() for _, table := range tables { _, err := db.DB.Exec("DELETE FROM " + table) - require.NoError(t, err, "database cleanup failed: %s", tables) + require.NoError(tb, err, "database cleanup failed: %s", tables) } _, err := db.DB.Exec("SELECT setval(relname::TEXT, 1, false) from pg_class where relkind = 'S'") - require.NoError(t, err, "database cleanup failed: %s", tables) + require.NoError(tb, err, "database cleanup failed: %s", tables) } // RequireRowsInTable verifies that `tname` table has `n` amount of rows in it. -func (db DB) RequireRowsInTable(t *testing.T, tname string, n int) { - t.Helper() +func (db DB) RequireRowsInTable(tb testing.TB, tname string, n int) { + tb.Helper() var count int - require.NoError(t, db.QueryRow("SELECT COUNT(*) FROM "+tname).Scan(&count)) - require.Equal(t, n, count, "unexpected amount of rows in table: %d instead of %d", count, n) + require.NoError(tb, db.QueryRow("SELECT COUNT(*) FROM "+tname).Scan(&count)) + require.Equal(tb, n, count, "unexpected amount of rows in table: %d instead of %d", count, n) } // TruncateAll removes all data from known set of tables. -func (db DB) TruncateAll(t testing.TB) { - db.Truncate(t, +func (db DB) TruncateAll(tb testing.TB) { + db.Truncate(tb, "replication_queue_job_lock", "replication_queue", "replication_queue_lock", @@ -109,9 +109,9 @@ func (db DB) TruncateAll(t testing.TB) { } // MustExec executes `q` with `args` and verifies there are no errors. -func (db DB) MustExec(t testing.TB, q string, args ...interface{}) { +func (db DB) MustExec(tb testing.TB, q string, args ...interface{}) { _, err := db.DB.Exec(q, args...) - require.NoError(t, err) + require.NoError(tb, err) } // Close removes schema if it was used and releases connection pool. @@ -130,22 +130,22 @@ func (db DB) Close() error { // PGPORT - required, binding port // PGUSER - optional, user - `$ whoami` would be used if not provided // Once the test is completed the database will be dropped on test cleanup execution. -func New(t testing.TB) DB { - t.Helper() +func New(tb testing.TB) DB { + tb.Helper() database := "praefect_" + strings.ReplaceAll(uuid.New().String(), "-", "") - return DB{DB: initPraefectDB(t, database), Name: database} + return DB{DB: initPraefectDB(tb, database), Name: database} } // GetConfig returns the database configuration determined by // environment variables. See NewDB() for the list of variables. -func GetConfig(t testing.TB, database string) config.DB { - env := getDatabaseEnvironment(t) +func GetConfig(tb testing.TB, database string) config.DB { + env := getDatabaseEnvironment(tb) - require.Contains(t, env, "PGHOST", "PGHOST env var expected to be provided to connect to Postgres database") - require.Contains(t, env, "PGPORT", "PGHOST env var expected to be provided to connect to Postgres database") + require.Contains(tb, env, "PGHOST", "PGHOST env var expected to be provided to connect to Postgres database") + require.Contains(tb, env, "PGPORT", "PGHOST env var expected to be provided to connect to Postgres database") portNumber, err := strconv.Atoi(env["PGPORT"]) - require.NoError(t, err, "PGPORT must be a port number of the Postgres database listens for incoming connections") + require.NoError(tb, err, "PGPORT must be a port number of the Postgres database listens for incoming connections") // connect to 'postgres' database first to re-create testing database from scratch conf := config.DB{ @@ -166,27 +166,27 @@ func GetConfig(t testing.TB, database string) config.DB { if bouncerPort, ok := env["PGPORT_PGBOUNCER"]; ok { bouncerPortNumber, err := strconv.Atoi(bouncerPort) - require.NoError(t, err, "PGPORT_PGBOUNCER must be a port number of the PgBouncer") + require.NoError(tb, err, "PGPORT_PGBOUNCER must be a port number of the PgBouncer") conf.Port = bouncerPortNumber } return conf } -func requireSQLOpen(t testing.TB, dbCfg config.DB, direct bool) *sql.DB { - t.Helper() +func requireSQLOpen(tb testing.TB, dbCfg config.DB, direct bool) *sql.DB { + tb.Helper() db, err := sql.Open("pgx", glsql.DSN(dbCfg, direct)) - require.NoErrorf(t, err, "failed to connect to %q database", dbCfg.DBName) - if !assert.NoErrorf(t, db.Ping(), "failed to communicate with %q database", dbCfg.DBName) { - require.NoErrorf(t, db.Close(), "release connection to the %q database", dbCfg.DBName) + require.NoErrorf(tb, err, "failed to connect to %q database", dbCfg.DBName) + if !assert.NoErrorf(tb, db.Ping(), "failed to communicate with %q database", dbCfg.DBName) { + require.NoErrorf(tb, db.Close(), "release connection to the %q database", dbCfg.DBName) } return db } -func requireTerminateAllConnections(t testing.TB, db *sql.DB, database string) { - t.Helper() +func requireTerminateAllConnections(tb testing.TB, db *sql.DB, database string) { + tb.Helper() _, err := db.Exec("SELECT PG_TERMINATE_BACKEND(pid) FROM PG_STAT_ACTIVITY WHERE datname = '" + database + "'") - require.NoError(t, err) + require.NoError(tb, err) // Once the pg_terminate_backend has completed, we may need to wait before the connections // are fully released. pg_terminate_backend will return true as long as the signal was @@ -194,9 +194,9 @@ func requireTerminateAllConnections(t testing.TB, db *sql.DB, database string) { // TODO: In Postgre 14, pg_terminate_backend takes an optional timeout argument that makes it a blocking // call. https://gitlab.com/gitlab-org/gitaly/-/issues/3937 tracks the refactor work to remove this // require.Eventuallyf call in favor of passing in a timeout to pg_terminate_backend - require.Eventuallyf(t, func() bool { + require.Eventuallyf(tb, func() bool { var openConnections int - require.NoError(t, db.QueryRow( + require.NoError(tb, db.QueryRow( `SELECT COUNT(*) FROM pg_stat_activity WHERE datname = $1 AND pid != pg_backend_pid()`, database). Scan(&openConnections)) @@ -204,35 +204,37 @@ func requireTerminateAllConnections(t testing.TB, db *sql.DB, database string) { }, 20*time.Second, 10*time.Millisecond, "wait for all connections to be terminated") } -func initPraefectDB(t testing.TB, database string) *sql.DB { - t.Helper() +func initPraefectDB(tb testing.TB, database string) *sql.DB { + tb.Helper() - dbCfg := GetConfig(t, "postgres") + dbCfg := GetConfig(tb, "postgres") // We require a direct connection to the Postgres instance and not through the PgBouncer // because we use transaction pool mood for it and it doesn't work well for system advisory locks. - postgresDB := requireSQLOpen(t, dbCfg, true) - defer func() { require.NoErrorf(t, postgresDB.Close(), "release connection to the %q database", dbCfg.DBName) }() + postgresDB := requireSQLOpen(tb, dbCfg, true) + defer func() { + require.NoErrorf(tb, postgresDB.Close(), "release connection to the %q database", dbCfg.DBName) + }() // Acquire exclusive advisory lock to prevent other concurrent test from doing the same. _, err := postgresDB.Exec(`SELECT pg_advisory_lock($1)`, advisoryLockIDDatabaseTemplate) - require.NoError(t, err, "not able to acquire lock for synchronisation") + require.NoError(tb, err, "not able to acquire lock for synchronisation") var advisoryUnlock func() advisoryUnlock = func() { - require.True(t, scanSingleBool(t, postgresDB, `SELECT pg_advisory_unlock($1)`, advisoryLockIDDatabaseTemplate), "release advisory lock") + require.True(tb, scanSingleBool(tb, postgresDB, `SELECT pg_advisory_unlock($1)`, advisoryLockIDDatabaseTemplate), "release advisory lock") advisoryUnlock = func() {} } defer func() { advisoryUnlock() }() - templateDBExists := databaseExist(t, postgresDB, praefectTemplateDatabase) + templateDBExists := databaseExist(tb, postgresDB, praefectTemplateDatabase) if !templateDBExists { _, err := postgresDB.Exec("CREATE DATABASE " + praefectTemplateDatabase + " WITH ENCODING 'UTF8'") - require.NoErrorf(t, err, "failed to create %q database", praefectTemplateDatabase) + require.NoErrorf(tb, err, "failed to create %q database", praefectTemplateDatabase) } - templateDBConf := GetConfig(t, praefectTemplateDatabase) - templateDB := requireSQLOpen(t, templateDBConf, true) + templateDBConf := GetConfig(tb, praefectTemplateDatabase) + templateDB := requireSQLOpen(tb, templateDBConf, true) defer func() { - require.NoErrorf(t, templateDB.Close(), "release connection to the %q database", templateDBConf.DBName) + require.NoErrorf(tb, templateDB.Close(), "release connection to the %q database", templateDBConf.DBName) }() if _, err := glsql.Migrate(templateDB, false); err != nil { @@ -240,37 +242,37 @@ func initPraefectDB(t testing.TB, database string) *sql.DB { // current migration. It may be caused by other code changes done in another branch. if pErr := (*migrate.PlanError)(nil); errors.As(err, &pErr) { if strings.EqualFold(pErr.ErrorMessage, "unknown migration in database") { - require.NoErrorf(t, templateDB.Close(), "release connection to the %q database", templateDBConf.DBName) + require.NoErrorf(tb, templateDB.Close(), "release connection to the %q database", templateDBConf.DBName) _, err = postgresDB.Exec("DROP DATABASE " + praefectTemplateDatabase) - require.NoErrorf(t, err, "failed to drop %q database", praefectTemplateDatabase) + require.NoErrorf(tb, err, "failed to drop %q database", praefectTemplateDatabase) _, err = postgresDB.Exec("CREATE DATABASE " + praefectTemplateDatabase + " WITH ENCODING 'UTF8'") - require.NoErrorf(t, err, "failed to create %q database", praefectTemplateDatabase) + require.NoErrorf(tb, err, "failed to create %q database", praefectTemplateDatabase) - remigrateTemplateDB := requireSQLOpen(t, templateDBConf, true) + remigrateTemplateDB := requireSQLOpen(tb, templateDBConf, true) defer func() { - require.NoErrorf(t, remigrateTemplateDB.Close(), "release connection to the %q database", templateDBConf.DBName) + require.NoErrorf(tb, remigrateTemplateDB.Close(), "release connection to the %q database", templateDBConf.DBName) }() _, err = glsql.Migrate(remigrateTemplateDB, false) - require.NoErrorf(t, err, "failed to run database migration on %q", praefectTemplateDatabase) + require.NoErrorf(tb, err, "failed to run database migration on %q", praefectTemplateDatabase) } else { - require.NoErrorf(t, err, "failed to run database migration on %q", praefectTemplateDatabase) + require.NoErrorf(tb, err, "failed to run database migration on %q", praefectTemplateDatabase) } } else { - require.NoErrorf(t, err, "failed to run database migration on %q", praefectTemplateDatabase) + require.NoErrorf(tb, err, "failed to run database migration on %q", praefectTemplateDatabase) } } // Release advisory lock as soon as possible to unblock other tests from execution. advisoryUnlock() - require.NoErrorf(t, templateDB.Close(), "release connection to the %q database", templateDBConf.DBName) + require.NoErrorf(tb, templateDB.Close(), "release connection to the %q database", templateDBConf.DBName) _, err = postgresDB.Exec(`CREATE DATABASE ` + database + ` TEMPLATE ` + praefectTemplateDatabase) - require.NoErrorf(t, err, "failed to create %q database", praefectTemplateDatabase) + require.NoErrorf(tb, err, "failed to create %q database", praefectTemplateDatabase) - t.Cleanup(func() { - if _, ok := getDatabaseEnvironment(t)["PGHOST_PGBOUNCER"]; ok { + tb.Cleanup(func() { + if _, ok := getDatabaseEnvironment(tb)["PGHOST_PGBOUNCER"]; ok { pgbouncerCfg := dbCfg // This database name will connect us to the special admin console. pgbouncerCfg.DBName = "pgbouncer" @@ -278,8 +280,8 @@ func initPraefectDB(t testing.TB, database string) *sql.DB { // We cannot use `requireSQLOpen()` because it would ping the database, // which is not supported by the PgBouncer admin console. pgbouncerDB, err := sql.Open("pgx", glsql.DSN(pgbouncerCfg, false)) - require.NoError(t, err) - defer testhelper.MustClose(t, pgbouncerDB) + require.NoError(tb, err) + defer testhelper.MustClose(tb, pgbouncerDB) // Trying to release connections like we do with the "normal" Postgres // database regularly results in flaky tests with PgBouncer given that the @@ -287,41 +289,41 @@ func initPraefectDB(t testing.TB, database string) *sql.DB { // connections by connecting to its admin console and using the KILL // command, which instructs it to kill all client and server connections. _, err = pgbouncerDB.Exec("KILL " + database) - require.NoError(t, err, "killing PgBouncer connections") + require.NoError(tb, err, "killing PgBouncer connections") } dbCfg.DBName = "postgres" - postgresDB := requireSQLOpen(t, dbCfg, true) - defer testhelper.MustClose(t, postgresDB) + postgresDB := requireSQLOpen(tb, dbCfg, true) + defer testhelper.MustClose(tb, postgresDB) // We need to force-terminate open connections as for the tasks that use PgBouncer // the actual client connected to the database is a PgBouncer and not a test that is // running. - requireTerminateAllConnections(t, postgresDB, database) + requireTerminateAllConnections(tb, postgresDB, database) _, err = postgresDB.Exec("DROP DATABASE " + database) - require.NoErrorf(t, err, "failed to drop %q database", database) + require.NoErrorf(tb, err, "failed to drop %q database", database) }) // Connect to the testing database with optional PgBouncer dbCfg.DBName = database - praefectTestDB := requireSQLOpen(t, dbCfg, false) - t.Cleanup(func() { + praefectTestDB := requireSQLOpen(tb, dbCfg, false) + tb.Cleanup(func() { if err := praefectTestDB.Close(); !errors.Is(err, net.ErrClosed) { - require.NoErrorf(t, err, "release connection to the %q database", dbCfg.DBName) + require.NoErrorf(tb, err, "release connection to the %q database", dbCfg.DBName) } }) return praefectTestDB } -func databaseExist(t testing.TB, db *sql.DB, database string) bool { - return scanSingleBool(t, db, `SELECT EXISTS(SELECT * FROM pg_database WHERE datname = $1)`, database) +func databaseExist(tb testing.TB, db *sql.DB, database string) bool { + return scanSingleBool(tb, db, `SELECT EXISTS(SELECT * FROM pg_database WHERE datname = $1)`, database) } -func scanSingleBool(t testing.TB, db *sql.DB, query string, args ...interface{}) bool { +func scanSingleBool(tb testing.TB, db *sql.DB, query string, args ...interface{}) bool { var flag bool row := db.QueryRow(query, args...) - require.NoError(t, row.Scan(&flag)) + require.NoError(tb, row.Scan(&flag)) return flag } @@ -333,7 +335,7 @@ var ( databaseEnv map[string]string ) -func getDatabaseEnvironment(t testing.TB) map[string]string { +func getDatabaseEnvironment(tb testing.TB) map[string]string { databaseEnvOnce.Do(func() { envvars := map[string]string{} @@ -374,12 +376,12 @@ func getDatabaseEnvironment(t testing.TB) map[string]string { // WaitForBlockedQuery is a helper that waits until a blocked query matching the prefix is present in the // database. This is useful for ensuring another transaction is blocking a query when testing concurrent // execution of multiple queries. -func WaitForBlockedQuery(ctx context.Context, t testing.TB, db glsql.Querier, queryPrefix string) { - t.Helper() +func WaitForBlockedQuery(ctx context.Context, tb testing.TB, db glsql.Querier, queryPrefix string) { + tb.Helper() for { var queryBlocked bool - require.NoError(t, db.QueryRowContext(ctx, ` + require.NoError(tb, db.QueryRowContext(ctx, ` SELECT EXISTS ( SELECT FROM pg_stat_activity WHERE TRIM(e'\n' FROM query) LIKE $1 @@ -404,10 +406,10 @@ func WaitForBlockedQuery(ctx context.Context, t testing.TB, db glsql.Querier, qu } // SetMigrations ensures the requested number of migrations are up and the remainder are down. -func SetMigrations(t testing.TB, db DB, cfg config.Config, up int) { +func SetMigrations(tb testing.TB, db DB, cfg config.Config, up int) { // Ensure all migrations are up first _, err := glsql.Migrate(db.DB, true) - require.NoError(t, err) + require.NoError(tb, err) migrationCt := len(migrations.All()) @@ -422,7 +424,7 @@ func SetMigrations(t testing.TB, db DB, cfg config.Config, up int) { // It would be preferable to use migrate.MigrateDown() here, but that introduces // a circular dependency between testdb and datastore. n, err := migrationSet.ExecMax(db.DB, "postgres", ms, migrate.Down, down) - require.NoError(t, err) - require.Equal(t, down, n) + require.NoError(tb, err) + require.Equal(tb, down, n) } } diff --git a/internal/testhelper/testdb/health.go b/internal/testhelper/testdb/health.go index b6822506e..4cc1fdf57 100644 --- a/internal/testhelper/testdb/health.go +++ b/internal/testhelper/testdb/health.go @@ -12,8 +12,8 @@ import ( // praefect name -> virtual storage -> storage. On each run, it clears all previous health checks from the table, so the // passed in nodes are the only ones considered healthy after the function. As the healthy nodes are determined by the time of // the last successful health check, this should be run in the same transastion as the tested query to prevent flakiness. -func SetHealthyNodes(t testing.TB, ctx context.Context, db glsql.Querier, healthyNodes map[string]map[string][]string) { - t.Helper() +func SetHealthyNodes(tb testing.TB, ctx context.Context, db glsql.Querier, healthyNodes map[string]map[string][]string) { + tb.Helper() var praefects, virtualStorages, storages []string for praefect, virtualStors := range healthyNodes { @@ -44,5 +44,5 @@ ON CONFLICT (praefect_name, shard_name, node_name) DO UPDATE SET virtualStorages, storages, ) - require.NoError(t, err) + require.NoError(tb, err) } diff --git a/internal/testhelper/testhelper.go b/internal/testhelper/testhelper.go index 8e5977401..f1db352f5 100644 --- a/internal/testhelper/testhelper.go +++ b/internal/testhelper/testhelper.go @@ -44,19 +44,19 @@ func IsPraefectEnabled() bool { // SkipWithPraefect skips the test if it is being executed with Praefect in front // of the Gitaly. -func SkipWithPraefect(t testing.TB, reason string) { +func SkipWithPraefect(tb testing.TB, reason string) { if IsPraefectEnabled() { - t.Skipf(reason) + tb.Skipf(reason) } } // MustReadFile returns the content of a file or fails at once. -func MustReadFile(t testing.TB, filename string) []byte { - t.Helper() +func MustReadFile(tb testing.TB, filename string) []byte { + tb.Helper() content, err := os.ReadFile(filename) if err != nil { - t.Fatal(err) + tb.Fatal(err) } return content @@ -71,11 +71,11 @@ func GitlabTestStoragePath() string { } // MustRunCommand runs a command with an optional standard input and returns the standard output, or fails. -func MustRunCommand(t testing.TB, stdin io.Reader, name string, args ...string) []byte { - t.Helper() +func MustRunCommand(tb testing.TB, stdin io.Reader, name string, args ...string) []byte { + tb.Helper() if filepath.Base(name) == "git" { - require.Fail(t, "Please use gittest.Exec or gittest.ExecStream to run git commands.") + require.Fail(tb, "Please use gittest.Exec or gittest.ExecStream to run git commands.") } cmd := exec.Command(name, args...) @@ -86,7 +86,7 @@ func MustRunCommand(t testing.TB, stdin io.Reader, name string, args ...string) output, err := cmd.Output() if err != nil { stderr := err.(*exec.ExitError).Stderr - require.NoError(t, err, "%s %s: %s", name, args, stderr) + require.NoError(tb, err, "%s %s: %s", name, args, stderr) } return output @@ -96,43 +96,43 @@ func MustRunCommand(t testing.TB, stdin io.Reader, name string, args ...string) // an error. This function is useful when closing via `defer`, as a simple // `defer require.NoError(t, closer.Close())` would cause `closer.Close()` to // be executed early already. -func MustClose(t testing.TB, closer io.Closer) { - require.NoError(t, closer.Close()) +func MustClose(tb testing.TB, closer io.Closer) { + require.NoError(tb, closer.Close()) } // CopyFile copies a file at the path src to a file at the path dst -func CopyFile(t testing.TB, src, dst string) { +func CopyFile(tb testing.TB, src, dst string) { fsrc, err := os.Open(src) - require.NoError(t, err) - defer MustClose(t, fsrc) + require.NoError(tb, err) + defer MustClose(tb, fsrc) fdst, err := os.Create(dst) - require.NoError(t, err) - defer MustClose(t, fdst) + require.NoError(tb, err) + defer MustClose(tb, fdst) _, err = io.Copy(fdst, fsrc) - require.NoError(t, err) + require.NoError(tb, err) } // GetTemporaryGitalySocketFileName will return a unique, useable socket file name -func GetTemporaryGitalySocketFileName(t testing.TB) string { - require.NotEmpty(t, testDirectory, "you must call testhelper.Configure() before GetTemporaryGitalySocketFileName()") +func GetTemporaryGitalySocketFileName(tb testing.TB) string { + require.NotEmpty(tb, testDirectory, "you must call testhelper.Configure() before GetTemporaryGitalySocketFileName()") tmpfile, err := os.CreateTemp(testDirectory, "gitaly.socket.") - require.NoError(t, err) + require.NoError(tb, err) name := tmpfile.Name() - require.NoError(t, tmpfile.Close()) - require.NoError(t, os.Remove(name)) + require.NoError(tb, tmpfile.Close()) + require.NoError(tb, os.Remove(name)) return name } // GetLocalhostListener listens on the next available TCP port and returns // the listener and the localhost address (host:port) string. -func GetLocalhostListener(t testing.TB) (net.Listener, string) { +func GetLocalhostListener(tb testing.TB) (net.Listener, string) { l, err := net.Listen("tcp", "localhost:0") - require.NoError(t, err) + require.NoError(tb, err) addr := fmt.Sprintf("localhost:%d", l.Addr().(*net.TCPAddr).Port) @@ -150,9 +150,9 @@ func ContextWithLogger(logger *log.Entry) ContextOpt { } // Context returns that gets canceled at the end of the test. -func Context(t testing.TB, opts ...ContextOpt) context.Context { +func Context(tb testing.TB, opts ...ContextOpt) context.Context { ctx, cancel := context.WithCancel(ContextWithoutCancel(opts...)) - t.Cleanup(cancel) + tb.Cleanup(cancel) return ctx } @@ -189,23 +189,23 @@ func ContextWithoutCancel(opts ...ContextOpt) context.Context { // CreateGlobalDirectory creates a directory in the test directory that is shared across all // between all tests. -func CreateGlobalDirectory(t testing.TB, name string) string { - require.NotEmpty(t, testDirectory, "global temporary directory does not exist") +func CreateGlobalDirectory(tb testing.TB, name string) string { + require.NotEmpty(tb, testDirectory, "global temporary directory does not exist") path := filepath.Join(testDirectory, name) - require.NoError(t, os.Mkdir(path, 0o777)) + require.NoError(tb, os.Mkdir(path, 0o777)) return path } // TempDir is a wrapper around os.MkdirTemp that provides a cleanup function. -func TempDir(t testing.TB) string { +func TempDir(tb testing.TB) string { if testDirectory == "" { panic("you must call testhelper.Configure() before TempDir()") } tmpDir, err := os.MkdirTemp(testDirectory, "") - require.NoError(t, err) - t.Cleanup(func() { - require.NoError(t, os.RemoveAll(tmpDir)) + require.NoError(tb, err) + tb.Cleanup(func() { + require.NoError(tb, os.RemoveAll(tmpDir)) }) return tmpDir @@ -218,11 +218,11 @@ type Cleanup func() // WriteExecutable ensures that the parent directory exists, and writes an executable with provided // content. The executable must not exist previous to writing it. Returns the path of the written // executable. -func WriteExecutable(t testing.TB, path string, content []byte) string { +func WriteExecutable(tb testing.TB, path string, content []byte) string { dir := filepath.Dir(path) - require.NoError(t, os.MkdirAll(dir, 0o755)) - t.Cleanup(func() { - assert.NoError(t, os.RemoveAll(dir)) + require.NoError(tb, os.MkdirAll(dir, 0o755)) + tb.Cleanup(func() { + assert.NoError(tb, os.RemoveAll(dir)) }) // Open the file descriptor and write the script into it. It may happen that any other @@ -235,9 +235,9 @@ func WriteExecutable(t testing.TB, path string, content []byte) string { // We thus need to perform file locking to ensure that all writeable references to this // file have been closed before returning. executable, err := os.OpenFile(path, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o755) - require.NoError(t, err) + require.NoError(tb, err) _, err = io.Copy(executable, bytes.NewReader(content)) - require.NoError(t, err) + require.NoError(tb, err) // We now lock the file descriptor for exclusive access. If there was a forked process // holding the writeable file descriptor at this point in time, then it would refer to the @@ -247,45 +247,45 @@ func WriteExecutable(t testing.TB, path string, content []byte) string { // // No matter what, after this step any file descriptors referring to this writeable file // descriptor will be exclusively locked. - require.NoError(t, syscall.Flock(int(executable.Fd()), syscall.LOCK_EX)) + require.NoError(tb, syscall.Flock(int(executable.Fd()), syscall.LOCK_EX)) // We now close this file. The file will be automatically unlocked as soon as all // references to this file descriptor are closed. - MustClose(t, executable) + MustClose(tb, executable) // We now open the file again, but this time only for reading. executable, err = os.Open(path) - require.NoError(t, err) + require.NoError(tb, err) // And this time, we try to acquire a shared lock on this file. This call will block until // the exclusive file lock on the above writeable file descriptor has been dropped. So as // soon as we're able to acquire the lock we know that there cannot be any open writeable // file descriptors for this file anymore, and thus we won't get ETXTBSY anymore. - require.NoError(t, syscall.Flock(int(executable.Fd()), syscall.LOCK_SH)) - MustClose(t, executable) + require.NoError(tb, syscall.Flock(int(executable.Fd()), syscall.LOCK_SH)) + MustClose(tb, executable) return path } // Unsetenv unsets an environment variable. The variable will be restored after the test has // finished. -func Unsetenv(t testing.TB, key string) { - t.Helper() +func Unsetenv(tb testing.TB, key string) { + tb.Helper() - // We're first using `t.Setenv()` here due to two reasons: first, it will automitcally + // We're first using `tb.Setenv()` here due to two reasons: first, it will automitcally // handle restoring the environment variable for us after the test has finished. And second, - // it performs a check whether we're running with `t.Parallel()`. - t.Setenv(key, "") + // it performs a check whether we're running with `tb.Parallel()`. + tb.Setenv(key, "") // And now we can unset the environment variable given that we know we're not running in a // parallel test and where the cleanup function has been installed. - require.NoError(t, os.Unsetenv(key)) + require.NoError(tb, os.Unsetenv(key)) } // 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 GenerateCerts(t *testing.T) (string, string) { - t.Helper() +func GenerateCerts(tb testing.TB) (string, string) { + tb.Helper() rootCA := &x509.Certificate{ SerialNumber: big.NewInt(1), @@ -299,31 +299,31 @@ func GenerateCerts(t *testing.T) (string, string) { } caKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) + require.NoError(tb, err) caCert, err := x509.CreateCertificate(rand.Reader, rootCA, rootCA, &caKey.PublicKey, caKey) - require.NoError(t, err) + require.NoError(tb, err) entityKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - require.NoError(t, err) + require.NoError(tb, err) entityX509 := &x509.Certificate{ SerialNumber: big.NewInt(2), } entityCert, err := x509.CreateCertificate(rand.Reader, rootCA, entityX509, &entityKey.PublicKey, caKey) - require.NoError(t, err) + require.NoError(tb, err) certFile, err := os.CreateTemp(testDirectory, "") - require.NoError(t, err) - defer MustClose(t, certFile) - t.Cleanup(func() { - require.NoError(t, os.Remove(certFile.Name())) + require.NoError(tb, err) + defer MustClose(tb, certFile) + tb.Cleanup(func() { + require.NoError(tb, os.Remove(certFile.Name())) }) // create chained PEM file with CA and entity cert for _, cert := range [][]byte{entityCert, caCert} { - require.NoError(t, + require.NoError(tb, pem.Encode(certFile, &pem.Block{ Type: "CERTIFICATE", Bytes: cert, @@ -332,16 +332,16 @@ func GenerateCerts(t *testing.T) (string, string) { } keyFile, err := os.CreateTemp(testDirectory, "") - require.NoError(t, err) - defer MustClose(t, keyFile) - t.Cleanup(func() { - require.NoError(t, os.Remove(keyFile.Name())) + require.NoError(tb, err) + defer MustClose(tb, keyFile) + tb.Cleanup(func() { + require.NoError(tb, os.Remove(keyFile.Name())) }) entityKeyBytes, err := x509.MarshalECPrivateKey(entityKey) - require.NoError(t, err) + require.NoError(tb, err) - require.NoError(t, + require.NoError(tb, pem.Encode(keyFile, &pem.Block{ Type: "ECDSA PRIVATE KEY", Bytes: entityKeyBytes, diff --git a/internal/testhelper/testserver.go b/internal/testhelper/testserver.go index a48225810..c344e59fa 100644 --- a/internal/testhelper/testserver.go +++ b/internal/testhelper/testserver.go @@ -12,22 +12,22 @@ import ( // NewServerWithHealth creates a new gRPC server with the health server set up. // It will listen on the socket identified by `socketName`. -func NewServerWithHealth(t testing.TB, socketName string) *health.Server { +func NewServerWithHealth(tb testing.TB, socketName string) *health.Server { lis, err := net.Listen("unix", socketName) - require.NoError(t, err) + require.NoError(tb, err) - return NewHealthServerWithListener(t, lis) + return NewHealthServerWithListener(tb, lis) } // NewHealthServerWithListener creates a new gRPC server with the health server // set up. It will listen on the given listener. -func NewHealthServerWithListener(t testing.TB, listener net.Listener) *health.Server { +func NewHealthServerWithListener(tb testing.TB, listener net.Listener) *health.Server { srv := grpc.NewServer() healthSrvr := health.NewServer() healthpb.RegisterHealthServer(srv, healthSrvr) - t.Cleanup(srv.Stop) - go func() { require.NoError(t, srv.Serve(listener)) }() + tb.Cleanup(srv.Stop) + go func() { require.NoError(tb, srv.Serve(listener)) }() return healthSrvr } diff --git a/internal/testhelper/testserver/gitaly.go b/internal/testhelper/testserver/gitaly.go index 1d90fabfe..07749aa46 100644 --- a/internal/testhelper/testserver/gitaly.go +++ b/internal/testhelper/testserver/gitaly.go @@ -44,13 +44,13 @@ import ( // It accepts addition Registrar to register all required service instead of // calling service.RegisterAll explicitly because it creates a circular dependency // when the function is used in on of internal/gitaly/service/... packages. -func RunGitalyServer(t testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server, registrar func(srv *grpc.Server, deps *service.Dependencies), opts ...GitalyServerOpt) string { - return StartGitalyServer(t, cfg, rubyServer, registrar, opts...).Address() +func RunGitalyServer(tb testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server, registrar func(srv *grpc.Server, deps *service.Dependencies), opts ...GitalyServerOpt) string { + return StartGitalyServer(tb, cfg, rubyServer, registrar, opts...).Address() } // StartGitalyServer creates and runs gitaly (and praefect as a proxy) server. -func StartGitalyServer(t testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server, registrar func(srv *grpc.Server, deps *service.Dependencies), opts ...GitalyServerOpt) GitalyServer { - gitalySrv, gitalyAddr, disablePraefect := runGitaly(t, cfg, rubyServer, registrar, opts...) +func StartGitalyServer(tb testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server, registrar func(srv *grpc.Server, deps *service.Dependencies), opts ...GitalyServerOpt) GitalyServer { + gitalySrv, gitalyAddr, disablePraefect := runGitaly(tb, cfg, rubyServer, registrar, opts...) if !testhelper.IsPraefectEnabled() || disablePraefect { return GitalyServer{ @@ -60,7 +60,7 @@ func StartGitalyServer(t testing.TB, cfg config.Cfg, rubyServer *rubyserver.Serv } } - praefectServer := runPraefectProxy(t, cfg, gitalyAddr) + praefectServer := runPraefectProxy(tb, cfg, gitalyAddr) return GitalyServer{ Server: gitalySrv, shutdown: func() { @@ -71,13 +71,13 @@ func StartGitalyServer(t testing.TB, cfg config.Cfg, rubyServer *rubyserver.Serv } } -func runPraefectProxy(t testing.TB, gitalyCfg config.Cfg, gitalyAddr string) PraefectServer { - return StartPraefect(t, praefectconfig.Config{ - SocketPath: testhelper.GetTemporaryGitalySocketFileName(t), +func runPraefectProxy(tb testing.TB, gitalyCfg config.Cfg, gitalyAddr string) PraefectServer { + return StartPraefect(tb, praefectconfig.Config{ + SocketPath: testhelper.GetTemporaryGitalySocketFileName(tb), Auth: auth.Config{ Token: gitalyCfg.Auth.Token, }, - DB: testdb.GetConfig(t, testdb.New(t).Name), + DB: testdb.GetConfig(tb, testdb.New(tb).Name), Failover: praefectconfig.Failover{ Enabled: true, ElectionStrategy: praefectconfig.ElectionStrategyLocal, @@ -124,7 +124,7 @@ func (gs GitalyServer) Address() string { } // waitHealthy waits until the server hosted at address becomes healthy. -func waitHealthy(ctx context.Context, t testing.TB, addr string, authToken string) { +func waitHealthy(ctx context.Context, tb testing.TB, addr string, authToken string) { grpcOpts := []grpc.DialOption{ grpc.WithBlock(), } @@ -133,30 +133,30 @@ func waitHealthy(ctx context.Context, t testing.TB, addr string, authToken strin } conn, err := client.DialContext(ctx, addr, grpcOpts) - require.NoError(t, err) - defer testhelper.MustClose(t, conn) + require.NoError(tb, err) + defer testhelper.MustClose(tb, conn) healthClient := healthpb.NewHealthClient(conn) resp, err := healthClient.Check(ctx, &healthpb.HealthCheckRequest{}, grpc.WaitForReady(true)) - require.NoError(t, err) - require.Equal(t, healthpb.HealthCheckResponse_SERVING, resp.Status, "server not yet ready to serve") + require.NoError(tb, err) + require.Equal(tb, healthpb.HealthCheckResponse_SERVING, resp.Status, "server not yet ready to serve") } -func runGitaly(t testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server, registrar func(srv *grpc.Server, deps *service.Dependencies), opts ...GitalyServerOpt) (*grpc.Server, string, bool) { - t.Helper() +func runGitaly(tb testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server, registrar func(srv *grpc.Server, deps *service.Dependencies), opts ...GitalyServerOpt) (*grpc.Server, string, bool) { + tb.Helper() var gsd gitalyServerDeps for _, opt := range opts { gsd = opt(gsd) } - deps := gsd.createDependencies(t, cfg, rubyServer) - t.Cleanup(func() { gsd.conns.Close() }) + deps := gsd.createDependencies(tb, cfg, rubyServer) + tb.Cleanup(func() { gsd.conns.Close() }) serverFactory := server.NewGitalyServerFactory( cfg, - gsd.logger.WithField("test", t.Name()), + gsd.logger.WithField("test", tb.Name()), deps.GetBackchannelRegistry(), deps.GetDiskCache(), []*limithandler.LimiterMiddleware{deps.GetLimitHandler()}, @@ -164,28 +164,28 @@ func runGitaly(t testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server, regi if cfg.RuntimeDir != "" { internalServer, err := serverFactory.CreateInternal() - require.NoError(t, err) - t.Cleanup(internalServer.Stop) + require.NoError(tb, err) + tb.Cleanup(internalServer.Stop) registrar(internalServer, deps) registerHealthServerIfNotRegistered(internalServer) - require.NoError(t, os.MkdirAll(cfg.InternalSocketDir(), 0o700)) - t.Cleanup(func() { require.NoError(t, os.RemoveAll(cfg.InternalSocketDir())) }) + require.NoError(tb, os.MkdirAll(cfg.InternalSocketDir(), 0o700)) + tb.Cleanup(func() { require.NoError(tb, os.RemoveAll(cfg.InternalSocketDir())) }) internalListener, err := net.Listen("unix", cfg.InternalSocketPath()) - require.NoError(t, err) + require.NoError(tb, err) go func() { - assert.NoError(t, internalServer.Serve(internalListener), "failure to serve internal gRPC") + assert.NoError(tb, internalServer.Serve(internalListener), "failure to serve internal gRPC") }() - ctx := testhelper.Context(t) - waitHealthy(ctx, t, "unix://"+internalListener.Addr().String(), cfg.Auth.Token) + ctx := testhelper.Context(tb) + waitHealthy(ctx, tb, "unix://"+internalListener.Addr().String(), cfg.Auth.Token) } externalServer, err := serverFactory.CreateExternal(cfg.TLS.CertPath != "" && cfg.TLS.KeyPath != "") - require.NoError(t, err) - t.Cleanup(externalServer.Stop) + require.NoError(tb, err) + tb.Cleanup(externalServer.Stop) registrar(externalServer, deps) registerHealthServerIfNotRegistered(externalServer) @@ -195,27 +195,27 @@ func runGitaly(t testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server, regi switch { case cfg.TLSListenAddr != "": listener, err = net.Listen("tcp", cfg.TLSListenAddr) - require.NoError(t, err) + require.NoError(tb, err) _, port, err := net.SplitHostPort(listener.Addr().String()) - require.NoError(t, err) + require.NoError(tb, err) addr = "tls://localhost:" + port case cfg.ListenAddr != "": listener, err = net.Listen("tcp", cfg.ListenAddr) - require.NoError(t, err) + require.NoError(tb, err) addr = "tcp://" + listener.Addr().String() default: - serverSocketPath := testhelper.GetTemporaryGitalySocketFileName(t) + serverSocketPath := testhelper.GetTemporaryGitalySocketFileName(tb) listener, err = net.Listen("unix", serverSocketPath) - require.NoError(t, err) + require.NoError(tb, err) addr = "unix://" + serverSocketPath } go func() { - assert.NoError(t, externalServer.Serve(listener), "failure to serve external gRPC") + assert.NoError(tb, externalServer.Serve(listener), "failure to serve external gRPC") }() - ctx := testhelper.Context(t) - waitHealthy(ctx, t, addr, cfg.Auth.Token) + ctx := testhelper.Context(tb) + waitHealthy(ctx, tb, addr, cfg.Auth.Token) return externalServer, addr, gsd.disablePraefect } @@ -249,9 +249,9 @@ type gitalyServerDeps struct { housekeepingManager housekeeping.Manager } -func (gsd *gitalyServerDeps) createDependencies(t testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server) *service.Dependencies { +func (gsd *gitalyServerDeps) createDependencies(tb testing.TB, cfg config.Cfg, rubyServer *rubyserver.Server) *service.Dependencies { if gsd.logger == nil { - gsd.logger = testhelper.NewDiscardingLogger(t) + gsd.logger = testhelper.NewDiscardingLogger(tb) } if gsd.conns == nil { @@ -264,7 +264,7 @@ func (gsd *gitalyServerDeps) createDependencies(t testing.TB, cfg config.Cfg, ru if gsd.gitlabClient == nil { gsd.gitlabClient = gitlab.NewMockClient( - t, gitlab.MockAllowed, gitlab.MockPreReceive, gitlab.MockPostReceive, + tb, gitlab.MockAllowed, gitlab.MockPreReceive, gitlab.MockPostReceive, ) } @@ -277,7 +277,7 @@ func (gsd *gitalyServerDeps) createDependencies(t testing.TB, cfg config.Cfg, ru } if gsd.gitCmdFactory == nil { - gsd.gitCmdFactory = gittest.NewCommandFactory(t, cfg) + gsd.gitCmdFactory = gittest.NewCommandFactory(tb, cfg) } if gsd.hookMgr == nil { @@ -287,13 +287,13 @@ func (gsd *gitalyServerDeps) createDependencies(t testing.TB, cfg config.Cfg, ru if gsd.linguist == nil { var err error gsd.linguist, err = linguist.New(cfg, gsd.gitCmdFactory) - require.NoError(t, err) + require.NoError(tb, err) } if gsd.catfileCache == nil { cache := catfile.NewCache(cfg) gsd.catfileCache = cache - t.Cleanup(cache.Stop) + tb.Cleanup(cache.Stop) } if gsd.diskCache == nil { @@ -302,7 +302,7 @@ func (gsd *gitalyServerDeps) createDependencies(t testing.TB, cfg config.Cfg, ru if gsd.packObjectsCache == nil { gsd.packObjectsCache = streamcache.New(cfg.PackObjectsCache, gsd.logger) - t.Cleanup(gsd.packObjectsCache.Stop) + tb.Cleanup(gsd.packObjectsCache.Stop) } if gsd.packObjectsConcurrencyTracker == nil { diff --git a/internal/testhelper/testserver/praefect.go b/internal/testhelper/testserver/praefect.go index 2598a0966..ec930ffd8 100644 --- a/internal/testhelper/testserver/praefect.go +++ b/internal/testhelper/testserver/praefect.go @@ -50,32 +50,32 @@ func (ps PraefectServer) Shutdown() { // StartPraefect creates and runs a Praefect proxy. This server is created by running the external // Praefect executable. -func StartPraefect(t testing.TB, cfg config.Config) PraefectServer { - t.Helper() +func StartPraefect(tb testing.TB, cfg config.Config) PraefectServer { + tb.Helper() praefectSpawnTokens <- struct{}{} - t.Cleanup(func() { + tb.Cleanup(func() { <-praefectSpawnTokens }) // We're precreating the Unix socket which we pass to Praefect. This closes a race where // the Unix socket didn't yet exist when we tried to dial the Praefect server. praefectServerSocket, err := net.Listen("unix", cfg.SocketPath) - require.NoError(t, err) - testhelper.MustClose(t, praefectServerSocket) - t.Cleanup(func() { require.NoError(t, os.RemoveAll(praefectServerSocket.Addr().String())) }) + require.NoError(tb, err) + testhelper.MustClose(tb, praefectServerSocket) + tb.Cleanup(func() { require.NoError(tb, os.RemoveAll(praefectServerSocket.Addr().String())) }) - tempDir := testhelper.TempDir(t) + tempDir := testhelper.TempDir(tb) configFilePath := filepath.Join(tempDir, "config.toml") configFile, err := os.Create(configFilePath) - require.NoError(t, err) - defer testhelper.MustClose(t, configFile) + require.NoError(tb, err) + defer testhelper.MustClose(tb, configFile) - require.NoError(t, toml.NewEncoder(configFile).Encode(&cfg)) - require.NoError(t, configFile.Sync()) + require.NoError(tb, toml.NewEncoder(configFile).Encode(&cfg)) + require.NoError(tb, configFile.Sync()) - binaryPath := testcfg.BuildPraefect(t, gitalycfg.Cfg{ + binaryPath := testcfg.BuildPraefect(tb, gitalycfg.Cfg{ BinDir: tempDir, }) @@ -85,7 +85,7 @@ func StartPraefect(t testing.TB, cfg config.Config) PraefectServer { cmd.Stderr = &stderr cmd.Stdout = os.Stdout - require.NoError(t, cmd.Start()) + require.NoError(tb, cmd.Start()) var waitErr error var waitOnce sync.Once @@ -103,7 +103,7 @@ func StartPraefect(t testing.TB, cfg config.Config) PraefectServer { _ = wait() }, } - t.Cleanup(praefectServer.Shutdown) + tb.Cleanup(praefectServer.Shutdown) ctx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) defer cancel() @@ -120,7 +120,7 @@ func StartPraefect(t testing.TB, cfg config.Config) PraefectServer { // up in order to connect to it. select { case <-processExitedCh: - require.FailNowf(t, "Praefect has died", "%s", stderr.String()) + require.FailNowf(tb, "Praefect has died", "%s", stderr.String()) default: } @@ -129,13 +129,13 @@ func StartPraefect(t testing.TB, cfg config.Config) PraefectServer { switch ctx.Err() { case context.DeadlineExceeded: // Capture Praefect logs when waitHealthy takes too long. - require.FailNowf(t, "Connecting to Praefect exceeded deadline", "%s", stderr.String()) + require.FailNowf(tb, "Connecting to Praefect exceeded deadline", "%s", stderr.String()) } default: } }() - waitHealthy(ctx, t, praefectServer.Address(), cfg.Auth.Token) + waitHealthy(ctx, tb, praefectServer.Address(), cfg.Auth.Token) return praefectServer } |