From 097b6736b4d756ad34244ffaba8ccbe7668433c8 Mon Sep 17 00:00:00 2001 From: Abhinav Gupta Date: Sat, 15 Feb 2025 13:39:35 -0800 Subject: [PATCH] all(test): prefer t.Context where possible t.Context was added in Go 1.24 to provide a context that is valid only for the lifetime of a test function. This change updates test functions to use this context where possible. Cases where it can't be used: - rapid tests - t.Cleanup functions --- branch_submit_test.go | 4 +- go.mod | 2 +- internal/forge/github/auth_test.go | 14 ++-- internal/forge/github/comment_test.go | 5 +- internal/forge/github/integration_test.go | 78 +++++++++----------- internal/forge/gitlab/auth_test.go | 24 +++--- internal/forge/gitlab/comment_test.go | 7 +- internal/forge/gitlab/integration_test.go | 45 ++++++----- internal/git/branch_test.go | 55 +++++++------- internal/git/config_test.go | 5 +- internal/git/integration_test.go | 6 +- internal/git/pull_test.go | 8 +- internal/git/rebase_test.go | 9 +-- internal/git/remote_test.go | 5 +- internal/git/tree_test.go | 12 ++- internal/spice/branch_test.go | 7 +- internal/spice/config_test.go | 3 +- internal/spice/remote_test.go | 5 +- internal/spice/state/branch_test.go | 19 ++++- internal/spice/state/storage/backend_test.go | 5 +- internal/spice/state/storage/git_test.go | 3 +- internal/spice/state/store_test.go | 15 ++-- internal/spice/state/version_test.go | 7 +- internal/spice/template_test.go | 7 +- 24 files changed, 178 insertions(+), 172 deletions(-) diff --git a/branch_submit_test.go b/branch_submit_test.go index 5b4662a2..463b073d 100644 --- a/branch_submit_test.go +++ b/branch_submit_test.go @@ -15,7 +15,7 @@ import ( func TestBranchSubmit_listChangeTemplates(t *testing.T) { t.Run("NoTimeout", func(t *testing.T) { log := logutil.TestLogger(t) - ctx := context.Background() + ctx := t.Context() tmpl := &forge.ChangeTemplate{} svc := &spiceTemplateServiceStub{ ListChangeTemplatesF: func(ctx context.Context, _ string, _ forge.Repository) ([]*forge.ChangeTemplate, error) { @@ -34,7 +34,7 @@ func TestBranchSubmit_listChangeTemplates(t *testing.T) { t.Run("Timeout", func(t *testing.T) { log := logutil.TestLogger(t) - ctx := context.Background() + ctx := t.Context() svc := &spiceTemplateServiceStub{ ListChangeTemplatesF: func(ctx context.Context, _ string, _ forge.Repository) ([]*forge.ChangeTemplate, error) { diff --git a/go.mod b/go.mod index 7f5e9708..27f7108a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module go.abhg.dev/gs -go 1.23.4 +go 1.24.0 require ( github.com/alecthomas/kong v1.8.1 diff --git a/internal/forge/github/auth_test.go b/internal/forge/github/auth_test.go index d2d2112b..37d99420 100644 --- a/internal/forge/github/auth_test.go +++ b/internal/forge/github/auth_test.go @@ -2,7 +2,6 @@ package github import ( "bytes" - "context" "encoding/json" "errors" "io" @@ -75,11 +74,10 @@ func TestAuthHasGitHubToken(t *testing.T) { Log: log.New(&logBuffer), } - ctx := context.Background() view := &ui.FileView{W: io.Discard} t.Run("AuthenticationFlow", func(t *testing.T) { - _, err := f.AuthenticationFlow(ctx, view) + _, err := f.AuthenticationFlow(t.Context(), view) require.Error(t, err) assert.ErrorContains(t, err, "already authenticated") assert.Contains(t, logBuffer.String(), "Already authenticated") @@ -181,7 +179,7 @@ func TestDeviceFlowAuthenticator(t *testing.T) { DeviceAuthURL: srv.URL + "/device/code", TokenURL: srv.URL + "/oauth/access_token", }, - }).Authenticate(context.Background(), &ui.FileView{W: io.Discard}) + }).Authenticate(t.Context(), &ui.FileView{W: io.Discard}) require.NoError(t, err) assert.Equal(t, "my-token", tok.AccessToken) @@ -207,7 +205,7 @@ func TestAuthenticationFlow_PAT(t *testing.T) { uitest.RunScripts(t, func(t testing.TB, ts *testscript.TestScript, view ui.InteractiveView) { wantToken := strings.TrimSpace(ts.ReadFile("want_token")) - got, err := new(Forge).AuthenticationFlow(context.Background(), view) + got, err := new(Forge).AuthenticationFlow(t.Context(), view) require.NoError(t, err) assert.Equal(t, &AuthenticationToken{ @@ -228,7 +226,7 @@ func TestAuthCLI(t *testing.T) { runCmd: func(*exec.Cmd) error { return nil }, - }).Authenticate(context.Background(), discardView) + }).Authenticate(t.Context(), discardView) require.NoError(t, err) f := Forge{ @@ -253,7 +251,7 @@ func TestAuthCLI(t *testing.T) { Stderr: []byte("great sadness"), } }, - }).Authenticate(context.Background(), discardView) + }).Authenticate(t.Context(), discardView) require.Error(t, err) assert.ErrorContains(t, err, "not authenticated") assert.ErrorContains(t, err, "great sadness") @@ -265,7 +263,7 @@ func TestAuthCLI(t *testing.T) { runCmd: func(*exec.Cmd) error { return errors.New("gh not found") }, - }).Authenticate(context.Background(), discardView) + }).Authenticate(t.Context(), discardView) require.Error(t, err) assert.ErrorContains(t, err, "gh not found") }) diff --git a/internal/forge/github/comment_test.go b/internal/forge/github/comment_test.go index 795fade7..fa26128b 100644 --- a/internal/forge/github/comment_test.go +++ b/internal/forge/github/comment_test.go @@ -1,7 +1,6 @@ package github import ( - "context" "encoding/json" "net/http" "net/http/httptest" @@ -128,7 +127,7 @@ func TestListChangeComments(t *testing.T) { defer srv.Close() repo, err := newRepository( - context.Background(), new(Forge), + t.Context(), new(Forge), "owner", "repo", logutil.TestLogger(t), githubv4.NewEnterpriseClient(srv.URL, nil), @@ -138,7 +137,7 @@ func TestListChangeComments(t *testing.T) { prID := PR{Number: 1, GQLID: "prID"} - ctx := context.Background() + ctx := t.Context() var bodies []string for comment, err := range repo.ListChangeComments(ctx, &prID, tt.opts) { require.NoError(t, err) diff --git a/internal/forge/github/integration_test.go b/internal/forge/github/integration_test.go index c11d337f..fed9b625 100644 --- a/internal/forge/github/integration_test.go +++ b/internal/forge/github/integration_test.go @@ -92,22 +92,20 @@ func newGitHubClient( } func TestIntegration_Repository(t *testing.T) { - ctx := context.Background() rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) - _, err := github.NewRepository(ctx, new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, nil) + _, err := github.NewRepository(t.Context(), new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, nil) require.NoError(t, err) } func TestIntegration_Repository_FindChangeByID(t *testing.T) { - ctx := context.Background() rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) - repo, err := github.NewRepository(ctx, new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, _gitSpiceRepoID) + repo, err := github.NewRepository(t.Context(), new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, _gitSpiceRepoID) require.NoError(t, err) t.Run("found", func(t *testing.T) { - change, err := repo.FindChangeByID(ctx, &github.PR{Number: 141}) + change, err := repo.FindChangeByID(t.Context(), &github.PR{Number: 141}) require.NoError(t, err) assert.Equal(t, &forge.FindChangeItem{ @@ -125,21 +123,20 @@ func TestIntegration_Repository_FindChangeByID(t *testing.T) { }) t.Run("not-found", func(t *testing.T) { - _, err := repo.FindChangeByID(ctx, &github.PR{Number: 999}) + _, err := repo.FindChangeByID(t.Context(), &github.PR{Number: 999}) require.Error(t, err) assert.ErrorContains(t, err, "Could not resolve") }) } func TestIntegration_Repository_FindChangesByBranch(t *testing.T) { - ctx := context.Background() rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) - repo, err := github.NewRepository(ctx, new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, _gitSpiceRepoID) + repo, err := github.NewRepository(t.Context(), new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, _gitSpiceRepoID) require.NoError(t, err) t.Run("found", func(t *testing.T) { - changes, err := repo.FindChangesByBranch(ctx, "gh-graphql", forge.FindChangesOptions{}) + changes, err := repo.FindChangesByBranch(t.Context(), "gh-graphql", forge.FindChangesOptions{}) require.NoError(t, err) assert.Equal(t, []*forge.FindChangeItem{ { @@ -158,20 +155,19 @@ func TestIntegration_Repository_FindChangesByBranch(t *testing.T) { }) t.Run("not-found", func(t *testing.T) { - changes, err := repo.FindChangesByBranch(ctx, "does-not-exist", forge.FindChangesOptions{}) + changes, err := repo.FindChangesByBranch(t.Context(), "does-not-exist", forge.FindChangesOptions{}) require.NoError(t, err) assert.Empty(t, changes) }) } func TestIntegration_Repository_ChangesAreMerged(t *testing.T) { - ctx := context.Background() rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) - repo, err := github.NewRepository(ctx, new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, _gitSpiceRepoID) + repo, err := github.NewRepository(t.Context(), new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, _gitSpiceRepoID) require.NoError(t, err) - merged, err := repo.ChangesAreMerged(ctx, []forge.ChangeID{ + merged, err := repo.ChangesAreMerged(t.Context(), []forge.ChangeID{ &github.PR{Number: 196, GQLID: "PR_kwDOJ2BQKs5ylEYu"}, // merged &github.PR{Number: 387, GQLID: "PR_kwDOJ2BQKs56wX01"}, // open (not merged) &github.PR{Number: 144, GQLID: "PR_kwDOJ2BQKs5xNeqO"}, // merged @@ -183,15 +179,13 @@ func TestIntegration_Repository_ChangesAreMerged(t *testing.T) { } func TestIntegration_Repository_ListChangeTemplates(t *testing.T) { - ctx := context.Background() - t.Run("absent", func(t *testing.T) { rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) - repo, err := github.NewRepository(ctx, new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, _gitSpiceRepoID) + repo, err := github.NewRepository(t.Context(), new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, _gitSpiceRepoID) require.NoError(t, err) - templates, err := repo.ListChangeTemplates(ctx) + templates, err := repo.ListChangeTemplates(t.Context()) require.NoError(t, err) assert.Empty(t, templates) }) @@ -199,10 +193,10 @@ func TestIntegration_Repository_ListChangeTemplates(t *testing.T) { t.Run("present", func(t *testing.T) { rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) - repo, err := github.NewRepository(ctx, new(github.Forge), "golang", "go", logutil.TestLogger(t), ghc, nil) + repo, err := github.NewRepository(t.Context(), new(github.Forge), "golang", "go", logutil.TestLogger(t), ghc, nil) require.NoError(t, err) - templates, err := repo.ListChangeTemplates(ctx) + templates, err := repo.ListChangeTemplates(t.Context()) require.NoError(t, err) require.Len(t, templates, 1) @@ -213,15 +207,13 @@ func TestIntegration_Repository_ListChangeTemplates(t *testing.T) { } func TestIntegration_Repository_NewChangeMetadata(t *testing.T) { - ctx := context.Background() - rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) - repo, err := github.NewRepository(ctx, new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, _gitSpiceRepoID) + repo, err := github.NewRepository(t.Context(), new(github.Forge), "abhinav", "git-spice", logutil.TestLogger(t), ghc, _gitSpiceRepoID) require.NoError(t, err) t.Run("valid", func(t *testing.T) { - md, err := repo.NewChangeMetadata(ctx, &github.PR{Number: 196}) + md, err := repo.NewChangeMetadata(t.Context(), &github.PR{Number: 196}) require.NoError(t, err) assert.Equal(t, &github.PR{ @@ -232,14 +224,13 @@ func TestIntegration_Repository_NewChangeMetadata(t *testing.T) { }) t.Run("invalid", func(t *testing.T) { - _, err := repo.NewChangeMetadata(ctx, &github.PR{Number: 10000}) + _, err := repo.NewChangeMetadata(t.Context(), &github.PR{Number: 10000}) require.Error(t, err) assert.ErrorContains(t, err, "get pull request ID") }) } func TestIntegration_Repository_SubmitEditChange(t *testing.T) { - ctx := context.Background() branchFixture := fixturetest.New(_fixtures, "branch", func() string { return randomString(8) }) @@ -263,6 +254,8 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { cmd.Stdout = output require.NoError(t, cmd.Run(), "failed to clone test-repo") + ctx := t.Context() + var err error gitRepo, err = git.Open(ctx, repoDir, git.OpenOptions{ Log: logutil.TestLogger(t), @@ -309,11 +302,11 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) repo, err := github.NewRepository( - ctx, new(github.Forge), "abhinav", "test-repo", logutil.TestLogger(t), ghc, _testRepoID, + t.Context(), new(github.Forge), "abhinav", "test-repo", logutil.TestLogger(t), ghc, _testRepoID, ) require.NoError(t, err) - change, err := repo.SubmitChange(ctx, forge.SubmitChangeRequest{ + change, err := repo.SubmitChange(t.Context(), forge.SubmitChangeRequest{ Subject: branchName, Body: "Test PR", Base: "main", @@ -331,7 +324,7 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { t.Logf("Pushing new base: %s", newBase) if *_update { require.NoError(t, - gitRepo.Push(ctx, git.PushOptions{ + gitRepo.Push(t.Context(), git.PushOptions{ Remote: "origin", Refspec: git.Refspec("main:" + newBase), }), "could not push base branch") @@ -339,7 +332,7 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { t.Cleanup(func() { t.Logf("Deleting remote branch: %s", newBase) require.NoError(t, - gitRepo.Push(ctx, git.PushOptions{ + gitRepo.Push(context.Background(), git.PushOptions{ Remote: "origin", Refspec: git.Refspec(":" + newBase), }), "error deleting branch") @@ -348,18 +341,18 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { t.Logf("Changing base to: %s", newBase) require.NoError(t, - repo.EditChange(ctx, changeID, forge.EditChangeOptions{ + repo.EditChange(t.Context(), changeID, forge.EditChangeOptions{ Base: newBase, }), "could not update base branch for PR") t.Cleanup(func() { t.Logf("Changing base back to: main") require.NoError(t, - repo.EditChange(ctx, changeID, forge.EditChangeOptions{ + repo.EditChange(context.Background(), changeID, forge.EditChangeOptions{ Base: "main", }), "error restoring base branch") }) - change, err := repo.FindChangeByID(ctx, changeID) + change, err := repo.FindChangeByID(t.Context(), changeID) require.NoError(t, err, "could not find PR after changing base") assert.Equal(t, newBase, change.BaseName, @@ -370,37 +363,36 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { t.Logf("Changing to draft") draft := true require.NoError(t, - repo.EditChange(ctx, changeID, forge.EditChangeOptions{ + repo.EditChange(t.Context(), changeID, forge.EditChangeOptions{ Draft: &draft, }), "could not update draft status for PR") t.Cleanup(func() { t.Logf("Changing to ready for review") draft = false require.NoError(t, - repo.EditChange(ctx, changeID, forge.EditChangeOptions{ + repo.EditChange(t.Context(), changeID, forge.EditChangeOptions{ Draft: &draft, }), "error restoring draft status") }) - change, err := repo.FindChangeByID(ctx, changeID) + change, err := repo.FindChangeByID(t.Context(), changeID) require.NoError(t, err, "could not find PR after changing draft") assert.True(t, change.Draft, "draft change did not take effect") }) } func TestIntegration_Repository_comments(t *testing.T) { - ctx := context.Background() rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) repo, err := github.NewRepository( - ctx, new(github.Forge), "abhinav", "test-repo", logutil.TestLogger(t), ghc, _testRepoID, + t.Context(), new(github.Forge), "abhinav", "test-repo", logutil.TestLogger(t), ghc, _testRepoID, ) require.NoError(t, err) commentBody := fixturetest.New(_fixtures, "comment", func() string { return randomString(32) }).Get(t) - commentID, err := repo.PostChangeComment(ctx, &github.PR{ + commentID, err := repo.PostChangeComment(t.Context(), &github.PR{ Number: 4, GQLID: githubv4.ID("PR_kwDOMVd0xs51N_9r"), }, commentBody) @@ -409,7 +401,7 @@ func TestIntegration_Repository_comments(t *testing.T) { t.Logf("Deleting comment: %s", commentID) require.NoError(t, - repo.DeleteChangeComment(ctx, commentID), + repo.DeleteChangeComment(t.Context(), commentID), "could not delete comment") }) @@ -419,7 +411,7 @@ func TestIntegration_Repository_comments(t *testing.T) { }).Get(t) require.NoError(t, - repo.UpdateChangeComment(ctx, commentID, newCommentBody), + repo.UpdateChangeComment(t.Context(), commentID, newCommentBody), "could not update comment") }) } @@ -428,7 +420,7 @@ func TestIntegration_Repository_ListChangeComments_simple(t *testing.T) { const _prGQLID = "PR_kwDOJ2BQKs55Hpxz" // https://github.com/abhinav/git-spice/pull/356 prID := &github.PR{Number: 356, GQLID: githubv4.ID(_prGQLID)} - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) repo, err := github.NewRepository( @@ -472,7 +464,7 @@ func TestIntegration_Repository_ListChangeComments_paginated(t *testing.T) { GQLID: githubv4.ID("PR_kwDOMVd0xs51N_9r"), } - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitHubClient(rec.GetDefaultClient()) repo, err := github.NewRepository( @@ -518,7 +510,7 @@ func TestIntegration_Repository_ListChangeComments_paginated(t *testing.T) { } func TestIntegration_Repository_notFoundError(t *testing.T) { - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) client := rec.GetDefaultClient() client.Transport = graphqlutil.WrapTransport(client.Transport) diff --git a/internal/forge/gitlab/auth_test.go b/internal/forge/gitlab/auth_test.go index 70288fce..b381123f 100644 --- a/internal/forge/gitlab/auth_test.go +++ b/internal/forge/gitlab/auth_test.go @@ -144,11 +144,10 @@ func TestAuth_alreadyHasGitLabToken(t *testing.T) { Log: log.New(&logBuffer), } - ctx := context.Background() view := &ui.FileView{W: io.Discard} t.Run("AuthenticationFlow", func(t *testing.T) { - _, err := f.AuthenticationFlow(ctx, view) + _, err := f.AuthenticationFlow(t.Context(), view) require.Error(t, err) assert.ErrorContains(t, err, "already authenticated") assert.Contains(t, logBuffer.String(), "Already authenticated") @@ -259,7 +258,7 @@ func TestAuthenticationFlow_PAT(t *testing.T) { uitest.RunScripts(t, func(t testing.TB, ts *testscript.TestScript, view ui.InteractiveView) { wantToken := strings.TrimSpace(ts.ReadFile("want_token")) - got, err := new(Forge).AuthenticationFlow(context.Background(), view) + got, err := new(Forge).AuthenticationFlow(t.Context(), view) require.NoError(t, err) assert.Equal(t, &AuthenticationToken{ @@ -276,20 +275,20 @@ func TestGLabCLI(t *testing.T) { // False will fail. t.Run("Status/Error", func(t *testing.T) { - ok, err := glCLI.Status(context.Background(), "example.com") + ok, err := glCLI.Status(t.Context(), "example.com") require.NoError(t, err) assert.False(t, ok) }) t.Run("Token/Error", func(t *testing.T) { - _, err := glCLI.Token(context.Background(), "example.com") + _, err := glCLI.Token(t.Context(), "example.com") require.Error(t, err) }) t.Run("Status/Okay", func(t *testing.T) { glCLI.runCmd = func(*exec.Cmd) error { return nil } - ok, err := glCLI.Status(context.Background(), "example.com") + ok, err := glCLI.Status(t.Context(), "example.com") require.NoError(t, err) assert.True(t, ok) }) @@ -303,7 +302,7 @@ func TestGLabCLI(t *testing.T) { return nil } - token, err := glCLI.Token(context.Background(), "example.com") + token, err := glCLI.Token(t.Context(), "example.com") require.NoError(t, err) assert.Equal(t, "1234567890abcdef", token) }) @@ -316,7 +315,7 @@ func TestGLabCLI(t *testing.T) { return nil } - _, err := glCLI.Token(context.Background(), "example.com") + _, err := glCLI.Token(t.Context(), "example.com") require.Error(t, err) assert.ErrorContains(t, err, "token not found") }) @@ -409,7 +408,7 @@ func TestDeviceFlowAuthenticator(t *testing.T) { DeviceAuthURL: srv.URL + "/oauth/authorize_device", TokenURL: srv.URL + "/oauth/token", }, - }).Authenticate(context.Background(), &ui.FileView{W: io.Discard}) + }).Authenticate(t.Context(), &ui.FileView{W: io.Discard}) require.NoError(t, err) assert.Equal(t, &AuthenticationToken{ @@ -433,13 +432,12 @@ func TestCLIAuthenticator(t *testing.T) { }, } - ctx := context.Background() view := &ui.FileView{W: io.Discard} t.Run("Success", func(t *testing.T) { statusOk, statusErr = true, nil - tok, err := auth.Authenticate(ctx, view) + tok, err := auth.Authenticate(t.Context(), view) require.NoError(t, err) assert.Equal(t, &AuthenticationToken{ AuthType: AuthTypeGitLabCLI, @@ -450,7 +448,7 @@ func TestCLIAuthenticator(t *testing.T) { t.Run("Unauthenticated", func(t *testing.T) { statusOk, statusErr = false, nil - _, err := auth.Authenticate(ctx, view) + _, err := auth.Authenticate(t.Context(), view) require.Error(t, err) assert.ErrorContains(t, err, "not authenticated") }) @@ -458,7 +456,7 @@ func TestCLIAuthenticator(t *testing.T) { t.Run("Error", func(t *testing.T) { statusOk, statusErr = false, assert.AnError - _, err := auth.Authenticate(ctx, view) + _, err := auth.Authenticate(t.Context(), view) require.Error(t, err) assert.ErrorIs(t, err, assert.AnError) }) diff --git a/internal/forge/gitlab/comment_test.go b/internal/forge/gitlab/comment_test.go index b3995d20..7560204f 100644 --- a/internal/forge/gitlab/comment_test.go +++ b/internal/forge/gitlab/comment_test.go @@ -1,7 +1,6 @@ package gitlab import ( - "context" "encoding/json" "net/http" "net/http/httptest" @@ -163,13 +162,13 @@ func TestListChangeComments(t *testing.T) { })) defer srv.Close() - client, _ := newGitLabClient(context.Background(), srv.URL, &AuthenticationToken{ + client, _ := newGitLabClient(t.Context(), srv.URL, &AuthenticationToken{ AuthType: AuthTypePAT, AccessToken: "token", }) repoID := 100 repo, err := newRepository( - context.Background(), new(Forge), + t.Context(), new(Forge), "owner", "repo", logutil.TestLogger(t), client, @@ -179,7 +178,7 @@ func TestListChangeComments(t *testing.T) { mrID := MR{Number: 1} - ctx := context.Background() + ctx := t.Context() var bodies []string for comment, err := range repo.ListChangeComments(ctx, &mrID, tt.opts) { require.NoError(t, err) diff --git a/internal/forge/gitlab/integration_test.go b/internal/forge/gitlab/integration_test.go index 8580a8d3..9069f749 100644 --- a/internal/forge/gitlab/integration_test.go +++ b/internal/forge/gitlab/integration_test.go @@ -96,7 +96,7 @@ func newGitLabClient( } func TestIntegration_Repository(t *testing.T) { - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitLabClient(rec.GetDefaultClient()) _, err := gitlab.NewRepository(ctx, new(gitlab.Forge), "abg", "test-repo", logutil.TestLogger(t), ghc, nil) @@ -104,13 +104,14 @@ func TestIntegration_Repository(t *testing.T) { } func TestIntegration_Repository_FindChangeByID(t *testing.T) { - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitLabClient(rec.GetDefaultClient()) repo, err := gitlab.NewRepository(ctx, new(gitlab.Forge), "abg", "test-repo", logutil.TestLogger(t), ghc, _testRepoID) require.NoError(t, err) t.Run("found", func(t *testing.T) { + ctx := t.Context() change, err := repo.FindChangeByID(ctx, &gitlab.MR{Number: 2}) require.NoError(t, err) @@ -128,6 +129,7 @@ func TestIntegration_Repository_FindChangeByID(t *testing.T) { }) t.Run("not-found", func(t *testing.T) { + ctx := t.Context() _, err := repo.FindChangeByID(ctx, &gitlab.MR{Number: 999}) require.Error(t, err) assert.ErrorContains(t, err, "404 Not Found") @@ -135,13 +137,14 @@ func TestIntegration_Repository_FindChangeByID(t *testing.T) { } func TestIntegration_Repository_FindChangesByBranch(t *testing.T) { - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitLabClient(rec.GetDefaultClient()) repo, err := gitlab.NewRepository(ctx, new(gitlab.Forge), "abg", "test-repo", logutil.TestLogger(t), ghc, _testRepoID) require.NoError(t, err) t.Run("found", func(t *testing.T) { + ctx := t.Context() changes, err := repo.FindChangesByBranch(ctx, "branch-name-test-TMmz0MkH", forge.FindChangesOptions{}) require.NoError(t, err) assert.Equal(t, []*forge.FindChangeItem{ @@ -160,6 +163,7 @@ func TestIntegration_Repository_FindChangesByBranch(t *testing.T) { }) t.Run("not-found", func(t *testing.T) { + ctx := t.Context() changes, err := repo.FindChangesByBranch(ctx, "does-not-exist", forge.FindChangesOptions{}) require.NoError(t, err) assert.Empty(t, changes) @@ -167,7 +171,7 @@ func TestIntegration_Repository_FindChangesByBranch(t *testing.T) { } func TestIntegration_Repository_ChangesAreMerged(t *testing.T) { - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitLabClient(rec.GetDefaultClient()) repo, err := gitlab.NewRepository(ctx, new(gitlab.Forge), "abg", "test-repo", logutil.TestLogger(t), ghc, _testRepoID) @@ -183,9 +187,8 @@ func TestIntegration_Repository_ChangesAreMerged(t *testing.T) { } func TestIntegration_Repository_ListChangeTemplates(t *testing.T) { - ctx := context.Background() - t.Run("absent", func(t *testing.T) { + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitLabClient(rec.GetDefaultClient()) repo, err := gitlab.NewRepository(ctx, new(gitlab.Forge), "abg", "test-repo", logutil.TestLogger(t), ghc, _testRepoID) @@ -197,6 +200,7 @@ func TestIntegration_Repository_ListChangeTemplates(t *testing.T) { }) t.Run("present", func(t *testing.T) { + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitLabClient(rec.GetDefaultClient()) repo, err := gitlab.NewRepository(ctx, new(gitlab.Forge), "gitlab-org", "cli", logutil.TestLogger(t), ghc, nil) @@ -213,7 +217,7 @@ func TestIntegration_Repository_ListChangeTemplates(t *testing.T) { } func TestIntegration_Repository_NewChangeMetadata(t *testing.T) { - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitLabClient(rec.GetDefaultClient()) @@ -221,6 +225,7 @@ func TestIntegration_Repository_NewChangeMetadata(t *testing.T) { require.NoError(t, err) t.Run("valid", func(t *testing.T) { + ctx := t.Context() md, err := repo.NewChangeMetadata(ctx, &gitlab.MR{Number: 3}) require.NoError(t, err) @@ -231,13 +236,14 @@ func TestIntegration_Repository_NewChangeMetadata(t *testing.T) { }) t.Run("invalid", func(t *testing.T) { + ctx := t.Context() _, err := repo.NewChangeMetadata(ctx, &gitlab.MR{Number: 10000}) require.Nil(t, err) }) } func TestIntegration_Repository_SubmitEditChange(t *testing.T) { - ctx := context.Background() + ctx := t.Context() branchFixture := fixturetest.New(_fixtures, "branch", func() string { return randomString(8) }) @@ -297,7 +303,7 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { t.Cleanup(func() { t.Logf("Deleting remote branch: %s", branchName) assert.NoError(t, - gitRepo.Push(ctx, git.PushOptions{ + gitRepo.Push(context.Background(), git.PushOptions{ Remote: "origin", Refspec: git.Refspec(":" + branchName), }), "error deleting branch") @@ -321,6 +327,7 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { changeID := change.ID t.Run("ChangeBase", func(t *testing.T) { + ctx := t.Context() newBaseFixture := fixturetest.New(_fixtures, "new-base", func() string { return randomString(8) }) @@ -337,7 +344,7 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { t.Cleanup(func() { t.Logf("Deleting remote branch: %s", newBase) require.NoError(t, - gitRepo.Push(ctx, git.PushOptions{ + gitRepo.Push(context.Background(), git.PushOptions{ Remote: "origin", Refspec: git.Refspec(":" + newBase), }), "error deleting branch") @@ -352,7 +359,7 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { t.Cleanup(func() { t.Logf("Changing base back to: main") require.NoError(t, - repo.EditChange(ctx, changeID, forge.EditChangeOptions{ + repo.EditChange(context.Background(), changeID, forge.EditChangeOptions{ Base: "main", }), "error restoring base branch") }) @@ -365,6 +372,7 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { }) t.Run("ChangeDraft", func(t *testing.T) { + ctx := t.Context() t.Logf("Changing to draft") draft := true require.NoError(t, @@ -375,7 +383,7 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { t.Logf("Changing to ready for review") draft = false require.NoError(t, - repo.EditChange(ctx, changeID, forge.EditChangeOptions{ + repo.EditChange(context.Background(), changeID, forge.EditChangeOptions{ Draft: &draft, }), "error restoring draft status") }) @@ -387,7 +395,7 @@ func TestIntegration_Repository_SubmitEditChange(t *testing.T) { } func TestIntegration_Repository_comments(t *testing.T) { - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitLabClient(rec.GetDefaultClient()) repo, err := gitlab.NewRepository( @@ -406,11 +414,12 @@ func TestIntegration_Repository_comments(t *testing.T) { t.Logf("Deleting comment: %s", commentID) require.NoError(t, - repo.DeleteChangeComment(ctx, commentID), + repo.DeleteChangeComment(context.Background(), commentID), "could not delete comment") }) t.Run("UpdateChangeComment", func(t *testing.T) { + ctx := t.Context() newCommentBody := fixturetest.New(_fixtures, "new-comment", func() string { return randomString(32) }).Get(t) @@ -424,7 +433,7 @@ func TestIntegration_Repository_comments(t *testing.T) { func TestIntegration_Repository_ListChangeComments_simple(t *testing.T) { prID := &gitlab.MR{Number: 4} - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitLabClient(rec.GetDefaultClient()) repo, err := gitlab.NewRepository( @@ -468,7 +477,7 @@ func TestIntegration_Repository_ListChangeComments_paginated(t *testing.T) { Number: 7, } - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) ghc := newGitLabClient(rec.GetDefaultClient()) repo, err := gitlab.NewRepository( @@ -490,7 +499,7 @@ func TestIntegration_Repository_ListChangeComments_paginated(t *testing.T) { t.Logf("Deleting comment: %s", commentID) assert.NoError(t, - repo.DeleteChangeComment(ctx, commentID), + repo.DeleteChangeComment(context.Background(), commentID), "could not delete comment") } }) @@ -514,7 +523,7 @@ func TestIntegration_Repository_ListChangeComments_paginated(t *testing.T) { } func TestIntegration_Repository_notFoundError(t *testing.T) { - ctx := context.Background() + ctx := t.Context() rec := newRecorder(t, t.Name()) client := rec.GetDefaultClient() ghc := newGitLabClient(client) diff --git a/internal/git/branch_test.go b/internal/git/branch_test.go index 022a13bc..cfb2e7b2 100644 --- a/internal/git/branch_test.go +++ b/internal/git/branch_test.go @@ -1,7 +1,6 @@ package git_test import ( - "context" "path/filepath" "testing" @@ -43,21 +42,20 @@ func TestIntegrationBranches(t *testing.T) { `))) require.NoError(t, err) - ctx := context.Background() - repo, err := git.Open(ctx, fixture.Dir(), git.OpenOptions{ + repo, err := git.Open(t.Context(), fixture.Dir(), git.OpenOptions{ Log: logutil.TestLogger(t), }) require.NoError(t, err) t.Run("CurrentBranch", func(t *testing.T) { - name, err := repo.CurrentBranch(ctx) + name, err := repo.CurrentBranch(t.Context()) require.NoError(t, err) assert.Equal(t, "main", name) }) t.Run("ListBranches", func(t *testing.T) { - bs, err := repo.LocalBranches(ctx) + bs, err := repo.LocalBranches(t.Context()) require.NoError(t, err) assert.Equal(t, []git.LocalBranch{ @@ -70,15 +68,15 @@ func TestIntegrationBranches(t *testing.T) { backToMain := func(t testing.TB) { t.Helper() - assert.NoError(t, repo.Checkout(ctx, "main")) + assert.NoError(t, repo.Checkout(t.Context(), "main")) } t.Run("Checkout", func(t *testing.T) { defer backToMain(t) - require.NoError(t, repo.Checkout(ctx, "feature1")) + require.NoError(t, repo.Checkout(t.Context(), "feature1")) - name, err := repo.CurrentBranch(ctx) + name, err := repo.CurrentBranch(t.Context()) require.NoError(t, err) assert.Equal(t, "feature1", name) @@ -87,19 +85,19 @@ func TestIntegrationBranches(t *testing.T) { t.Run("DetachedHead", func(t *testing.T) { defer backToMain(t) - require.NoError(t, repo.DetachHead(ctx, "main")) + require.NoError(t, repo.DetachHead(t.Context(), "main")) - _, err := repo.CurrentBranch(ctx) + _, err := repo.CurrentBranch(t.Context()) assert.ErrorIs(t, err, git.ErrDetachedHead) }) t.Run("CreateBranch", func(t *testing.T) { - require.NoError(t, repo.CreateBranch(ctx, git.CreateBranchRequest{ + require.NoError(t, repo.CreateBranch(t.Context(), git.CreateBranchRequest{ Name: "feature3", Head: "main", })) - bs, err := repo.LocalBranches(ctx) + bs, err := repo.LocalBranches(t.Context()) if assert.NoError(t, err) { assert.Equal(t, []git.LocalBranch{ {Name: "feature1"}, @@ -111,11 +109,11 @@ func TestIntegrationBranches(t *testing.T) { t.Run("DeleteBranch", func(t *testing.T) { require.NoError(t, - repo.DeleteBranch(ctx, "feature3", git.BranchDeleteOptions{ + repo.DeleteBranch(t.Context(), "feature3", git.BranchDeleteOptions{ Force: true, })) - bs, err := repo.LocalBranches(ctx) + bs, err := repo.LocalBranches(t.Context()) require.NoError(t, err) assert.Equal(t, []git.LocalBranch{ @@ -127,17 +125,17 @@ func TestIntegrationBranches(t *testing.T) { }) t.Run("RenameBranch", func(t *testing.T) { - require.NoError(t, repo.CreateBranch(ctx, git.CreateBranchRequest{ + require.NoError(t, repo.CreateBranch(t.Context(), git.CreateBranchRequest{ Name: "feature3", Head: "main", })) - require.NoError(t, repo.RenameBranch(ctx, git.RenameBranchRequest{ + require.NoError(t, repo.RenameBranch(t.Context(), git.RenameBranchRequest{ OldName: "feature3", NewName: "feature4", })) - bs, err := repo.LocalBranches(ctx) + bs, err := repo.LocalBranches(t.Context()) if assert.NoError(t, err) { assert.Equal(t, []git.LocalBranch{ {Name: "feature1"}, @@ -148,7 +146,7 @@ func TestIntegrationBranches(t *testing.T) { } require.NoError(t, - repo.DeleteBranch(ctx, "feature4", git.BranchDeleteOptions{ + repo.DeleteBranch(t.Context(), "feature4", git.BranchDeleteOptions{ Force: true, })) }) @@ -188,7 +186,7 @@ func TestIntegrationLocalBranchesWorktrees(t *testing.T) { `))) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() repo, err := git.Open(ctx, filepath.Join(fixture.Dir(), "repo"), git.OpenOptions{Log: logutil.TestLogger(t)}, @@ -242,46 +240,45 @@ func TestIntegrationRemoteBranches(t *testing.T) { `))) require.NoError(t, err) - ctx := context.Background() - repo, err := git.Open(ctx, + repo, err := git.Open(t.Context(), filepath.Join(fixture.Dir(), "clone"), git.OpenOptions{Log: logutil.TestLogger(t)}, ) require.NoError(t, err) t.Run("no upstream", func(t *testing.T) { - _, err := repo.BranchUpstream(ctx, "feature1") + _, err := repo.BranchUpstream(t.Context(), "feature1") require.Error(t, err) assert.ErrorIs(t, err, git.ErrNotExist) }) require.NoError(t, - repo.SetBranchUpstream(ctx, "feature1", "origin/feature1")) + repo.SetBranchUpstream(t.Context(), "feature1", "origin/feature1")) t.Run("has upstream", func(t *testing.T) { - upstream, err := repo.BranchUpstream(ctx, "feature1") + upstream, err := repo.BranchUpstream(t.Context(), "feature1") require.NoError(t, err) assert.Equal(t, "origin/feature1", upstream) }) t.Run("unset upstream", func(t *testing.T) { require.NoError(t, - repo.SetBranchUpstream(ctx, "feature1", "")) + repo.SetBranchUpstream(t.Context(), "feature1", "")) - _, err := repo.BranchUpstream(ctx, "feature1") + _, err := repo.BranchUpstream(t.Context(), "feature1") require.Error(t, err) assert.ErrorIs(t, err, git.ErrNotExist) }) require.NoError(t, - repo.SetBranchUpstream(ctx, "feature1", "origin/feature1")) + repo.SetBranchUpstream(t.Context(), "feature1", "origin/feature1")) t.Run("delete upstream", func(t *testing.T) { require.NoError(t, - repo.DeleteBranch(ctx, "origin/feature1", git.BranchDeleteOptions{ + repo.DeleteBranch(t.Context(), "origin/feature1", git.BranchDeleteOptions{ Remote: true, })) - _, err := repo.BranchUpstream(ctx, "feature1") + _, err := repo.BranchUpstream(t.Context(), "feature1") require.Error(t, err) assert.ErrorIs(t, err, git.ErrNotExist) }) diff --git a/internal/git/config_test.go b/internal/git/config_test.go index 87437fe2..00e3289e 100644 --- a/internal/git/config_test.go +++ b/internal/git/config_test.go @@ -2,7 +2,6 @@ package git import ( "bytes" - "context" "io" "os/exec" "path/filepath" @@ -147,7 +146,7 @@ func TestConfigListRegexp(t *testing.T) { exec: execer, }) - got, err := sliceutil.CollectErr(cfg.ListRegexp(context.Background(), ".")) + got, err := sliceutil.CollectErr(cfg.ListRegexp(t.Context(), ".")) require.NoError(t, err) assert.Equal(t, tt.want, got) }) @@ -227,7 +226,7 @@ func TestIntegrationConfigListRegexp(t *testing.T) { "GIT_CONFIG_NOSYSTEM=1", } - ctx := context.Background() + ctx := t.Context() log := logutil.TestLogger(t) for _, set := range tt.sets { args := append([]string{"config", "--global"}, set...) diff --git a/internal/git/integration_test.go b/internal/git/integration_test.go index f868be2f..8755c611 100644 --- a/internal/git/integration_test.go +++ b/internal/git/integration_test.go @@ -1,7 +1,6 @@ package git_test import ( - "context" "testing" "time" @@ -52,13 +51,14 @@ func TestIntegrationCommitListing(t *testing.T) { `))) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() repo, err := git.Open(ctx, fixture.Dir(), git.OpenOptions{ Log: logutil.TestLogger(t), }) require.NoError(t, err) t.Run("ListCommitsDetails", func(t *testing.T) { + ctx := t.Context() commits, err := repo.ListCommitsDetails(ctx, git.CommitRangeFrom("HEAD").Limit(2)) require.NoError(t, err) @@ -84,6 +84,7 @@ func TestIntegrationCommitListing(t *testing.T) { }) t.Run("CommitSubject", func(t *testing.T) { + ctx := t.Context() subject, err := repo.CommitSubject(ctx, "HEAD") require.NoError(t, err) assert.Equal(t, "Add feature2", subject) @@ -94,6 +95,7 @@ func TestIntegrationCommitListing(t *testing.T) { }) t.Run("CommitMessageRange", func(t *testing.T) { + ctx := t.Context() msgs, err := repo.CommitMessageRange(ctx, "HEAD", "HEAD~2") require.NoError(t, err) diff --git a/internal/git/pull_test.go b/internal/git/pull_test.go index 7350701f..1748127e 100644 --- a/internal/git/pull_test.go +++ b/internal/git/pull_test.go @@ -1,7 +1,6 @@ package git import ( - "context" "errors" "os/exec" "testing" @@ -59,7 +58,7 @@ func TestPullArgs(t *testing.T) { return nil }) - ctx := context.Background() + ctx := t.Context() err := repo.Pull(ctx, tt.give) require.NoError(t, err) }) @@ -69,10 +68,9 @@ func TestPullArgs(t *testing.T) { func TestPullErrors(t *testing.T) { execer := NewMockExecer(gomock.NewController(t)) repo := NewTestRepository(t, "", execer) - ctx := context.Background() t.Run("refspec without remote", func(t *testing.T) { - if err := repo.Pull(ctx, PullOptions{Refspec: "main"}); assert.Error(t, err) { + if err := repo.Pull(t.Context(), PullOptions{Refspec: "main"}); assert.Error(t, err) { assert.ErrorContains(t, err, "refspec specified without remote") } }) @@ -83,7 +81,7 @@ func TestPullErrors(t *testing.T) { Run(gomock.Any()). Return(giveErr) - err := repo.Pull(ctx, PullOptions{}) + err := repo.Pull(t.Context(), PullOptions{}) require.Error(t, err) assert.ErrorIs(t, err, giveErr) }) diff --git a/internal/git/rebase_test.go b/internal/git/rebase_test.go index 856c0162..0727c24f 100644 --- a/internal/git/rebase_test.go +++ b/internal/git/rebase_test.go @@ -1,7 +1,6 @@ package git_test import ( - "context" "os" "path/filepath" "testing" @@ -46,8 +45,7 @@ func TestRebase_deliberateInterrupt(t *testing.T) { require.NoError(t, err) t.Cleanup(fixture.Cleanup) - ctx := context.Background() - repo, err := git.Open(ctx, fixture.Dir(), git.OpenOptions{ + repo, err := git.Open(t.Context(), fixture.Dir(), git.OpenOptions{ Log: logutil.TestLogger(t), }) require.NoError(t, err) @@ -79,6 +77,7 @@ func TestRebase_deliberateInterrupt(t *testing.T) { for _, tt := range noFuncTests { t.Run(tt.name, func(t *testing.T) { + ctx := t.Context() defer func() { assert.NoError(t, repo.RebaseAbort(ctx)) }() @@ -131,8 +130,7 @@ func TestRebase_unexpectedInterrupt(t *testing.T) { `))) require.NoError(t, err) - ctx := context.Background() - repo, err := git.Open(ctx, fixture.Dir(), git.OpenOptions{ + repo, err := git.Open(t.Context(), fixture.Dir(), git.OpenOptions{ Log: logutil.TestLogger(t), }) require.NoError(t, err) @@ -140,6 +138,7 @@ func TestRebase_unexpectedInterrupt(t *testing.T) { login(t, "user") t.Run("noInterruptFunc", func(t *testing.T) { + ctx := t.Context() defer func() { assert.NoError(t, repo.RebaseAbort(ctx)) }() diff --git a/internal/git/remote_test.go b/internal/git/remote_test.go index 59d6745b..6241f8f5 100644 --- a/internal/git/remote_test.go +++ b/internal/git/remote_test.go @@ -1,7 +1,6 @@ package git_test import ( - "context" "io" "os/exec" "sync" @@ -17,7 +16,7 @@ import ( func TestRepositoryListRemoteRefs(t *testing.T) { mockExecer := git.NewMockExecer(gomock.NewController(t)) repo := git.NewTestRepository(t, "", mockExecer) - ctx := context.Background() + ctx := t.Context() var wg sync.WaitGroup defer wg.Wait() @@ -58,7 +57,7 @@ func TestRepositoryListRemoteRefs(t *testing.T) { func TestRepositoryListRemoteRefsOptions(t *testing.T) { mockExecer := git.NewMockExecer(gomock.NewController(t)) repo := git.NewTestRepository(t, "", mockExecer) - ctx := context.Background() + ctx := t.Context() var wg sync.WaitGroup defer wg.Wait() diff --git a/internal/git/tree_test.go b/internal/git/tree_test.go index b74a8324..1dc1e63a 100644 --- a/internal/git/tree_test.go +++ b/internal/git/tree_test.go @@ -2,7 +2,6 @@ package git_test import ( "bytes" - "context" "testing" "github.com/stretchr/testify/assert" @@ -33,7 +32,7 @@ func TestParseMode(t *testing.T) { func TestIntegrationListTreeAbsent(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() repo, err := git.Init(ctx, t.TempDir(), git.InitOptions{ Log: logutil.TestLogger(t), }) @@ -46,7 +45,7 @@ func TestIntegrationListTreeAbsent(t *testing.T) { func TestIntegrationMakeTree(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() repo, err := git.Init(ctx, t.TempDir(), git.InitOptions{ Log: logutil.TestLogger(t), }) @@ -70,6 +69,7 @@ func TestIntegrationMakeTree(t *testing.T) { }, ents) t.Run("subdir", func(t *testing.T) { + ctx := t.Context() newDirHash, err := repo.MakeTree(ctx, []git.TreeEntry{ {Type: git.BlobType, Name: "baz", Hash: emptyFile}, {Type: git.TreeType, Name: "sub", Hash: dirHash}, @@ -92,7 +92,7 @@ func TestIntegrationMakeTree(t *testing.T) { func TestIntegrationUpdateTree(t *testing.T) { t.Parallel() - ctx := context.Background() + ctx := t.Context() repo, err := git.Init(ctx, t.TempDir(), git.InitOptions{ Log: logutil.TestLogger(t), }) @@ -131,6 +131,7 @@ func TestIntegrationUpdateTree(t *testing.T) { }, ents) t.Run("overwrite", func(t *testing.T) { + ctx := t.Context() newBlob, err := repo.WriteObject(ctx, git.BlobType, bytes.NewReader([]byte("hello"))) require.NoError(t, err) @@ -154,6 +155,7 @@ func TestIntegrationUpdateTree(t *testing.T) { }) t.Run("delete", func(t *testing.T) { + ctx := t.Context() deletedHash, err := repo.UpdateTree(ctx, git.UpdateTreeRequest{ Tree: newHash, Deletes: []string{"bar/baz"}, @@ -172,6 +174,7 @@ func TestIntegrationUpdateTree(t *testing.T) { // empty directories are pruned from the tree. t.Run("clear empty dirs", func(t *testing.T) { + ctx := t.Context() deletedHash, err := repo.UpdateTree(ctx, git.UpdateTreeRequest{ Tree: newHash, Deletes: []string{"qux/quux/qu"}, @@ -196,6 +199,7 @@ func TestIntegrationUpdateTree(t *testing.T) { }) t.Run("delete all files", func(t *testing.T) { + ctx := t.Context() deletedHash, err := repo.UpdateTree(ctx, git.UpdateTreeRequest{ Tree: newHash, Deletes: []string{"foo", "bar/baz", "qux/quux/qu"}, diff --git a/internal/spice/branch_test.go b/internal/spice/branch_test.go index 86b78f4e..814d32be 100644 --- a/internal/spice/branch_test.go +++ b/internal/spice/branch_test.go @@ -1,7 +1,6 @@ package spice import ( - "context" "encoding/json" "net/http" "net/http/httptest" @@ -36,8 +35,6 @@ func TestGenerateBranchName(t *testing.T) { } func TestService_LookupBranch_changeAssociation(t *testing.T) { - ctx := context.Background() - // This test should not make real requests to the server, // but we need a real URL to work with for matching. shamhubServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -56,6 +53,7 @@ func TestService_LookupBranch_changeAssociation(t *testing.T) { // Without a remote set, the Service won't have a Forge connected. t.Run("NoRemote", func(t *testing.T) { + ctx := t.Context() mockCtrl := gomock.NewController(t) mockRepo := NewMockGitRepository(mockCtrl) mockStore := NewMockStore(mockCtrl) @@ -75,6 +73,7 @@ func TestService_LookupBranch_changeAssociation(t *testing.T) { // We should still be able to resolve metadata // for known forges. t.Run("KnownForge", func(t *testing.T) { + ctx := t.Context() mockStore.EXPECT(). LookupBranch(gomock.Any(), "feature"). Return(&state.LookupResponse{ @@ -94,6 +93,7 @@ func TestService_LookupBranch_changeAssociation(t *testing.T) { // And should not fail for unknown forges. t.Run("UnknownForge", func(t *testing.T) { + ctx := t.Context() mockStore.EXPECT(). LookupBranch(gomock.Any(), "feature"). Return(&state.LookupResponse{ @@ -113,6 +113,7 @@ func TestService_LookupBranch_changeAssociation(t *testing.T) { }) t.Run("CorruptedMetadata", func(t *testing.T) { + ctx := t.Context() mockCtrl := gomock.NewController(t) mockRepo := NewMockGitRepository(mockCtrl) mockStore := NewMockStore(mockCtrl) diff --git a/internal/spice/config_test.go b/internal/spice/config_test.go index 6153fd7f..f0b1b893 100644 --- a/internal/spice/config_test.go +++ b/internal/spice/config_test.go @@ -1,7 +1,6 @@ package spice_test import ( - "context" "os" "path/filepath" reflect "reflect" @@ -191,7 +190,7 @@ func TestIntegrationConfig_loadFromGit(t *testing.T) { ), "write configuration file") // Read configuration - ctx := context.Background() + ctx := t.Context() gitCfg := git.NewConfig(git.ConfigOptions{ Log: logutil.TestLogger(t), Dir: home, diff --git a/internal/spice/remote_test.go b/internal/spice/remote_test.go index 870a266f..84a09aaf 100644 --- a/internal/spice/remote_test.go +++ b/internal/spice/remote_test.go @@ -1,7 +1,6 @@ package spice import ( - "context" "iter" "testing" @@ -85,7 +84,7 @@ func TestUnusedBranchName(t *testing.T) { lastCall = currCall } - got, err := svc.UnusedBranchName(context.Background(), "origin", tt.branch) + got, err := svc.UnusedBranchName(t.Context(), "origin", tt.branch) require.NoError(t, err) assert.Equal(t, tt.wantBranch, got) }) @@ -103,7 +102,7 @@ func TestUnusedBranchName_listError(t *testing.T) { yield(git.RemoteRef{}, assert.AnError) }) - _, err := svc.UnusedBranchName(context.Background(), "origin", "feature") + _, err := svc.UnusedBranchName(t.Context(), "origin", "feature") require.Error(t, err) assert.ErrorIs(t, err, assert.AnError) } diff --git a/internal/spice/state/branch_test.go b/internal/spice/state/branch_test.go index c8a8f7a1..fe3aa95d 100644 --- a/internal/spice/state/branch_test.go +++ b/internal/spice/state/branch_test.go @@ -123,7 +123,7 @@ func TestBranchStateUnmarshal(t *testing.T) { } func TestBranchTxUpsertErrors(t *testing.T) { - ctx := context.Background() + ctx := t.Context() db := storage.NewDB(make(storage.MapBackend)) store, err := InitStore(ctx, InitStoreRequest{ DB: db, @@ -132,6 +132,7 @@ func TestBranchTxUpsertErrors(t *testing.T) { require.NoError(t, err) t.Run("MissingBranch", func(t *testing.T) { + ctx := t.Context() tx := store.BeginBranchTx() err := tx.Upsert(ctx, UpsertRequest{}) assert.ErrorContains(t, err, "branch name is required") @@ -139,6 +140,7 @@ func TestBranchTxUpsertErrors(t *testing.T) { }) t.Run("TrunkNotAllowed", func(t *testing.T) { + ctx := t.Context() tx := store.BeginBranchTx() err := tx.Upsert(ctx, UpsertRequest{ Name: "main", @@ -152,6 +154,7 @@ func TestBranchTxUpsertErrors(t *testing.T) { }) t.Run("NewBranchNoBase", func(t *testing.T) { + ctx := t.Context() tx := store.BeginBranchTx() err := tx.Upsert(ctx, UpsertRequest{ Name: "foo", @@ -164,6 +167,7 @@ func TestBranchTxUpsertErrors(t *testing.T) { }) t.Run("NewBranchUnknownBase", func(t *testing.T) { + ctx := t.Context() tx := store.BeginBranchTx() err := tx.Upsert(ctx, UpsertRequest{ Name: "foo", @@ -192,6 +196,7 @@ func TestBranchTxUpsertErrors(t *testing.T) { } t.Run("Cycle", func(t *testing.T) { + ctx := t.Context() tx := store.BeginBranchTx() err := tx.Upsert(ctx, UpsertRequest{ Name: "foo", @@ -207,6 +212,7 @@ func TestBranchTxUpsertErrors(t *testing.T) { }) t.Run("DeletedBase", func(t *testing.T) { + ctx := t.Context() { tx := store.BeginBranchTx() require.NoError(t, tx.Upsert(ctx, UpsertRequest{ @@ -231,7 +237,7 @@ func TestBranchTxUpsertErrors(t *testing.T) { } func TestBranchTxDelete(t *testing.T) { - ctx := context.Background() + ctx := t.Context() db := storage.NewDB(make(storage.MapBackend)) store, err := InitStore(ctx, InitStoreRequest{ DB: db, @@ -240,6 +246,7 @@ func TestBranchTxDelete(t *testing.T) { require.NoError(t, err) t.Run("MissingBranch", func(t *testing.T) { + ctx := t.Context() tx := store.BeginBranchTx() err := tx.Delete(ctx, "") assert.ErrorContains(t, err, "branch name is required") @@ -247,6 +254,7 @@ func TestBranchTxDelete(t *testing.T) { }) t.Run("TrunkNotAllowed", func(t *testing.T) { + ctx := t.Context() tx := store.BeginBranchTx() err := tx.Delete(ctx, "main") assert.ErrorIs(t, err, ErrTrunk) @@ -254,6 +262,7 @@ func TestBranchTxDelete(t *testing.T) { }) t.Run("UnknownBranch", func(t *testing.T) { + ctx := t.Context() tx := store.BeginBranchTx() err := tx.Delete(ctx, "unknown") assert.ErrorIs(t, err, ErrNotExist) @@ -274,6 +283,7 @@ func TestBranchTxDelete(t *testing.T) { } t.Run("HasAboves", func(t *testing.T) { + ctx := t.Context() tx := store.BeginBranchTx() err := tx.Delete(ctx, "foo") assert.ErrorContains(t, err, "needed by bar") @@ -284,6 +294,7 @@ func TestBranchTxDelete(t *testing.T) { }) t.Run("UpsertAndDelete", func(t *testing.T) { + ctx := t.Context() tx := store.BeginBranchTx() require.NoError(t, tx.Upsert(ctx, UpsertRequest{ Name: "baz", @@ -298,7 +309,7 @@ func TestBranchTxDelete(t *testing.T) { } func TestBranchTxUpsertChangeMetadataCanClear(t *testing.T) { - ctx := context.Background() + ctx := t.Context() db := storage.NewDB(make(storage.MapBackend)) store, err := InitStore(ctx, InitStoreRequest{ DB: db, @@ -341,7 +352,7 @@ func TestBranchTxUpsertChangeMetadataCanClear(t *testing.T) { } func TestBranchTxUpsert_canClearUpstream(t *testing.T) { - ctx := context.Background() + ctx := t.Context() db := storage.NewDB(make(storage.MapBackend)) store, err := InitStore(ctx, InitStoreRequest{ DB: db, diff --git a/internal/spice/state/storage/backend_test.go b/internal/spice/state/storage/backend_test.go index 26e6490c..aa86e889 100644 --- a/internal/spice/state/storage/backend_test.go +++ b/internal/spice/state/storage/backend_test.go @@ -1,7 +1,6 @@ package storage import ( - "context" "strconv" "sync" "testing" @@ -18,7 +17,7 @@ func TestStorageBackend(t *testing.T) { }) t.Run("Git", func(t *testing.T) { - ctx := context.Background() + ctx := t.Context() repo, err := git.Init(ctx, t.TempDir(), git.InitOptions{ Log: logutil.TestLogger(t), }) @@ -35,7 +34,7 @@ func TestStorageBackend(t *testing.T) { } func testStorageBackend(t *testing.T, backend Backend) { - ctx := context.Background() + ctx := t.Context() db := NewDB(backend) t.Run("ClearEmpty", func(t *testing.T) { diff --git a/internal/spice/state/storage/git_test.go b/internal/spice/state/storage/git_test.go index b12eaa98..e9d0cc99 100644 --- a/internal/spice/state/storage/git_test.go +++ b/internal/spice/state/storage/git_test.go @@ -1,7 +1,6 @@ package storage import ( - "context" "testing" "github.com/stretchr/testify/assert" @@ -11,7 +10,7 @@ import ( ) func TestGitBackendUpdateNoChanges(t *testing.T) { - ctx := context.Background() + ctx := t.Context() repo, err := git.Init(ctx, t.TempDir(), git.InitOptions{ Log: logutil.TestLogger(t), }) diff --git a/internal/spice/state/store_test.go b/internal/spice/state/store_test.go index d5bbec48..bd342cb8 100644 --- a/internal/spice/state/store_test.go +++ b/internal/spice/state/store_test.go @@ -1,7 +1,6 @@ package state_test import ( - "context" "encoding/json" "testing" @@ -13,7 +12,7 @@ import ( ) func TestStore(t *testing.T) { - ctx := context.Background() + ctx := t.Context() db := storage.NewDB(make(storage.MapBackend)) _, err := state.InitStore(ctx, state.InitStoreRequest{ @@ -42,6 +41,7 @@ func TestStore(t *testing.T) { require.NoError(t, err) t.Run("get", func(t *testing.T) { + ctx := t.Context() res, err := store.LookupBranch(ctx, "foo") require.NoError(t, err) @@ -62,6 +62,7 @@ func TestStore(t *testing.T) { })) t.Run("overwrite", func(t *testing.T) { + ctx := t.Context() err := state.UpdateBranch(ctx, store, &state.UpdateRequest{ Upserts: []state.UpsertRequest{ { @@ -85,6 +86,7 @@ func TestStore(t *testing.T) { }) t.Run("name with slash", func(t *testing.T) { + ctx := t.Context() err := state.UpdateBranch(ctx, store, &state.UpdateRequest{ Upserts: []state.UpsertRequest{{ Name: "bar/baz", @@ -105,6 +107,7 @@ func TestStore(t *testing.T) { }) t.Run("upstream branch", func(t *testing.T) { + ctx := t.Context() upstream := "remoteBranch" err := state.UpdateBranch(ctx, store, &state.UpdateRequest{ Upserts: []state.UpsertRequest{{ @@ -131,7 +134,7 @@ func TestOpenStore_errors(t *testing.T) { "version": []byte("500"), } - _, err := state.OpenStore(context.Background(), storage.NewDB(mem), nil) + _, err := state.OpenStore(t.Context(), storage.NewDB(mem), nil) require.Error(t, err) assert.ErrorContains(t, err, "check store layout:") assert.ErrorAs(t, err, new(*state.VersionMismatchError)) @@ -139,7 +142,7 @@ func TestOpenStore_errors(t *testing.T) { t.Run("NotInitialized", func(t *testing.T) { mem := make(storage.MapBackend) - _, err := state.OpenStore(context.Background(), storage.NewDB(mem), nil) + _, err := state.OpenStore(t.Context(), storage.NewDB(mem), nil) require.Error(t, err) assert.ErrorIs(t, err, state.ErrUninitialized) }) @@ -149,7 +152,7 @@ func TestOpenStore_errors(t *testing.T) { "repo": []byte(`{`), } - _, err := state.OpenStore(context.Background(), storage.NewDB(mem), nil) + _, err := state.OpenStore(t.Context(), storage.NewDB(mem), nil) require.Error(t, err) assert.ErrorContains(t, err, "get repo state:") }) @@ -159,7 +162,7 @@ func TestOpenStore_errors(t *testing.T) { "repo": []byte(`{}`), } - _, err := state.OpenStore(context.Background(), storage.NewDB(mem), nil) + _, err := state.OpenStore(t.Context(), storage.NewDB(mem), nil) require.Error(t, err) assert.ErrorContains(t, err, "corrupt state:") }) diff --git a/internal/spice/state/version_test.go b/internal/spice/state/version_test.go index 95d9561d..5197e80f 100644 --- a/internal/spice/state/version_test.go +++ b/internal/spice/state/version_test.go @@ -1,7 +1,6 @@ package state import ( - "context" "testing" "github.com/stretchr/testify/assert" @@ -39,7 +38,7 @@ func TestLoadVersion(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { db := storage.NewDB(tt.files) - got, err := loadVersion(context.Background(), db) + got, err := loadVersion(t.Context(), db) require.NoError(t, err) assert.Equal(t, tt.want, got) }) @@ -71,7 +70,7 @@ func TestCheckVersion(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { db := storage.NewDB(tt.files) - err := checkVersion(context.Background(), db) + err := checkVersion(t.Context(), db) if tt.err { require.Error(t, err) assert.ErrorAs(t, err, new(*VersionMismatchError)) @@ -90,7 +89,7 @@ func TestCheckVersion_loadError(t *testing.T) { Get(gomock.Any(), gomock.Any(), gomock.Any()). Return(assert.AnError) - err := checkVersion(context.Background(), mockDB) + err := checkVersion(t.Context(), mockDB) require.Error(t, err) assert.ErrorContains(t, err, "load store version:") assert.ErrorIs(t, err, assert.AnError) diff --git a/internal/spice/template_test.go b/internal/spice/template_test.go index f05adcd6..302b885f 100644 --- a/internal/spice/template_test.go +++ b/internal/spice/template_test.go @@ -31,7 +31,7 @@ func TestListChangeTemplates(t *testing.T) { `))) require.NoError(t, err) - ctx := context.Background() + ctx := t.Context() repo, err := git.Clone(ctx, upstream.Dir(), t.TempDir(), git.CloneOptions{ Log: logutil.TestLogger(t), }) @@ -63,6 +63,7 @@ func TestListChangeTemplates(t *testing.T) { assert.Equal(t, []*forge.ChangeTemplate{tmpl}, got) t.Run("Cached", func(t *testing.T) { + ctx := t.Context() _, cachedTemplates, err := store.LoadCachedTemplates(ctx) require.NoError(t, err) if assert.Len(t, cachedTemplates, 1) { @@ -76,6 +77,7 @@ func TestListChangeTemplates(t *testing.T) { }) t.Run("Timeout", func(t *testing.T) { + ctx := t.Context() // Change the cache key to force a cache miss, // and cause the forge to time out. require.NoError(t, store.CacheTemplates(ctx, "different", []*state.CachedTemplate{ @@ -101,6 +103,7 @@ func TestListChangeTemplates(t *testing.T) { }) t.Run("TimeoutNoCache", func(t *testing.T) { + ctx := t.Context() require.NoError(t, store.CacheTemplates(ctx, "different", nil)) remoteRepo.EXPECT(). @@ -115,7 +118,7 @@ func TestListChangeTemplates(t *testing.T) { func newMemoryStore(t *testing.T) *state.Store { t.Helper() - ctx := context.Background() + ctx := t.Context() db := storage.NewDB(make(storage.MapBackend)) store, err := state.InitStore(ctx, state.InitStoreRequest{ DB: db,