Use test context in tests and new loop system in benchmarks (#33648)

Replace all contexts in tests with go1.24 t.Context()

---------

Co-authored-by: Giteabot <teabot@gitea.io>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
This commit is contained in:
TheFox0x7 2025-02-20 10:57:40 +01:00 committed by GitHub
parent 3bbc482879
commit cc1fdc84ca
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
108 changed files with 712 additions and 794 deletions

View file

@ -4,7 +4,6 @@
package cache
import (
"context"
"testing"
"time"
@ -12,7 +11,7 @@ import (
)
func TestWithCacheContext(t *testing.T) {
ctx := WithCacheContext(context.Background())
ctx := WithCacheContext(t.Context())
v := GetContextData(ctx, "empty_field", "my_config1")
assert.Nil(t, v)
@ -52,7 +51,7 @@ func TestWithCacheContext(t *testing.T) {
}
func TestWithNoCacheContext(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
const field = "system_setting"

View file

@ -5,7 +5,6 @@ package csv
import (
"bytes"
"context"
"encoding/csv"
"io"
"strconv"
@ -231,7 +230,7 @@ John Doe john@doe.com This,note,had,a,lot,of,commas,to,test,delimiters`,
}
for n, c := range cases {
delimiter := determineDelimiter(markup.NewRenderContext(context.Background()).WithRelativePath(c.filename), []byte(decodeSlashes(t, c.csv)))
delimiter := determineDelimiter(markup.NewRenderContext(t.Context()).WithRelativePath(c.filename), []byte(decodeSlashes(t, c.csv)))
assert.EqualValues(t, c.expectedDelimiter, delimiter, "case %d: delimiter should be equal, expected '%c' got '%c'", n, c.expectedDelimiter, delimiter)
}
}

View file

@ -11,7 +11,7 @@ import (
)
func TestReadingBlameOutputSha256(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
if isGogit {

View file

@ -11,7 +11,7 @@ import (
)
func TestReadingBlameOutput(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
t.Run("Without .git-blame-ignore-revs", func(t *testing.T) {

View file

@ -47,7 +47,7 @@ func Benchmark_Blob_Data(b *testing.B) {
b.Fatal(err)
}
for i := 0; i < b.N; i++ {
for b.Loop() {
r, err := testBlob.DataAsync()
if err != nil {
b.Fatal(err)

View file

@ -15,7 +15,7 @@ func TestRunWithContextNoTimeout(t *testing.T) {
maxLoops := 10
// 'git --version' does not block so it must be finished before the timeout triggered.
cmd := NewCommand(context.Background(), "--version")
cmd := NewCommand(t.Context(), "--version")
for i := 0; i < maxLoops; i++ {
if err := cmd.Run(&RunOpts{}); err != nil {
t.Fatal(err)
@ -27,7 +27,7 @@ func TestRunWithContextTimeout(t *testing.T) {
maxLoops := 10
// 'git hash-object --stdin' blocks on stdin so we can have the timeout triggered.
cmd := NewCommand(context.Background(), "hash-object", "--stdin")
cmd := NewCommand(t.Context(), "hash-object", "--stdin")
for i := 0; i < maxLoops; i++ {
if err := cmd.Run(&RunOpts{Timeout: 1 * time.Millisecond}); err != nil {
if err != context.DeadlineExceeded {

View file

@ -4,20 +4,19 @@
package git
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
)
func TestRunWithContextStd(t *testing.T) {
cmd := NewCommand(context.Background(), "--version")
cmd := NewCommand(t.Context(), "--version")
stdout, stderr, err := cmd.RunStdString(&RunOpts{})
assert.NoError(t, err)
assert.Empty(t, stderr)
assert.Contains(t, stdout, "git version")
cmd = NewCommand(context.Background(), "--no-such-arg")
cmd = NewCommand(t.Context(), "--no-such-arg")
stdout, stderr, err = cmd.RunStdString(&RunOpts{})
if assert.Error(t, err) {
assert.Equal(t, stderr, err.Stderr())
@ -26,16 +25,16 @@ func TestRunWithContextStd(t *testing.T) {
assert.Empty(t, stdout)
}
cmd = NewCommand(context.Background())
cmd = NewCommand(t.Context())
cmd.AddDynamicArguments("-test")
assert.ErrorIs(t, cmd.Run(&RunOpts{}), ErrBrokenCommand)
cmd = NewCommand(context.Background())
cmd = NewCommand(t.Context())
cmd.AddDynamicArguments("--test")
assert.ErrorIs(t, cmd.Run(&RunOpts{}), ErrBrokenCommand)
subCmd := "version"
cmd = NewCommand(context.Background()).AddDynamicArguments(subCmd) // for test purpose only, the sub-command should never be dynamic for production
cmd = NewCommand(t.Context()).AddDynamicArguments(subCmd) // for test purpose only, the sub-command should never be dynamic for production
stdout, stderr, err = cmd.RunStdString(&RunOpts{})
assert.NoError(t, err)
assert.Empty(t, stderr)
@ -54,9 +53,9 @@ func TestGitArgument(t *testing.T) {
}
func TestCommandString(t *testing.T) {
cmd := NewCommandContextNoGlobals(context.Background(), "a", "-m msg", "it's a test", `say "hello"`)
cmd := NewCommandContextNoGlobals(t.Context(), "a", "-m msg", "it's a test", `say "hello"`)
assert.EqualValues(t, cmd.prog+` a "-m msg" "it's a test" "say \"hello\""`, cmd.LogString())
cmd = NewCommandContextNoGlobals(context.Background(), "url: https://a:b@c/", "/root/dir-a/dir-b")
cmd = NewCommandContextNoGlobals(t.Context(), "url: https://a:b@c/", "/root/dir-a/dir-b")
assert.EqualValues(t, cmd.prog+` "url: https://sanitized-credential@c/" .../dir-a/dir-b`, cmd.LogString())
}

View file

@ -4,7 +4,6 @@
package git
import (
"context"
"path/filepath"
"testing"
"time"
@ -83,7 +82,7 @@ func testGetCommitsInfo(t *testing.T, repo1 *Repository) {
}
// FIXME: Context.TODO() - if graceful has started we should use its Shutdown context otherwise use install signals in TestMain.
commitsInfo, treeCommit, err := entries.GetCommitsInfo(context.TODO(), commit, testCase.Path)
commitsInfo, treeCommit, err := entries.GetCommitsInfo(t.Context(), commit, testCase.Path)
assert.NoError(t, err, "Unable to get commit information for entries of subtree: %s in commit: %s from testcase due to error: %v", testCase.Path, testCase.CommitID, err)
if err != nil {
t.FailNow()
@ -159,8 +158,8 @@ func BenchmarkEntries_GetCommitsInfo(b *testing.B) {
entries.Sort()
b.ResetTimer()
b.Run(benchmark.name, func(b *testing.B) {
for i := 0; i < b.N; i++ {
_, _, err := entries.GetCommitsInfo(context.Background(), commit, "")
for b.Loop() {
_, _, err := entries.GetCommitsInfo(b.Context(), commit, "")
if err != nil {
b.Fatal(err)
}

View file

@ -4,7 +4,6 @@
package git
import (
"context"
"testing"
"github.com/stretchr/testify/assert"
@ -13,18 +12,18 @@ import (
func TestCommitSubmoduleLink(t *testing.T) {
sf := NewCommitSubmoduleFile("git@github.com:user/repo.git", "aaaa")
wl := sf.SubmoduleWebLink(context.Background())
wl := sf.SubmoduleWebLink(t.Context())
assert.Equal(t, "https://github.com/user/repo", wl.RepoWebLink)
assert.Equal(t, "https://github.com/user/repo/tree/aaaa", wl.CommitWebLink)
wl = sf.SubmoduleWebLink(context.Background(), "1111")
wl = sf.SubmoduleWebLink(t.Context(), "1111")
assert.Equal(t, "https://github.com/user/repo", wl.RepoWebLink)
assert.Equal(t, "https://github.com/user/repo/tree/1111", wl.CommitWebLink)
wl = sf.SubmoduleWebLink(context.Background(), "1111", "2222")
wl = sf.SubmoduleWebLink(t.Context(), "1111", "2222")
assert.Equal(t, "https://github.com/user/repo", wl.RepoWebLink)
assert.Equal(t, "https://github.com/user/repo/compare/1111...2222", wl.CommitWebLink)
wl = (*CommitSubmoduleFile)(nil).SubmoduleWebLink(context.Background())
wl = (*CommitSubmoduleFile)(nil).SubmoduleWebLink(t.Context())
assert.Nil(t, wl)
}

View file

@ -4,7 +4,6 @@
package git
import (
"context"
"os"
"path/filepath"
"strings"
@ -347,7 +346,7 @@ func TestGetCommitFileStatusMerges(t *testing.T) {
func Test_GetCommitBranchStart(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
repo, err := OpenRepository(context.Background(), bareRepo1Path)
repo, err := OpenRepository(t.Context(), bareRepo1Path)
assert.NoError(t, err)
defer repo.Close()
commit, err := repo.GetBranchCommit("branch1")

View file

@ -4,7 +4,6 @@
package git
import (
"context"
"path/filepath"
"testing"
@ -16,7 +15,7 @@ func TestGrepSearch(t *testing.T) {
assert.NoError(t, err)
defer repo.Close()
res, err := GrepSearch(context.Background(), repo, "void", GrepOptions{})
res, err := GrepSearch(t.Context(), repo, "void", GrepOptions{})
assert.NoError(t, err)
assert.Equal(t, []*GrepResult{
{
@ -31,7 +30,7 @@ func TestGrepSearch(t *testing.T) {
},
}, res)
res, err = GrepSearch(context.Background(), repo, "void", GrepOptions{PathspecList: []string{":(glob)java-hello/*"}})
res, err = GrepSearch(t.Context(), repo, "void", GrepOptions{PathspecList: []string{":(glob)java-hello/*"}})
assert.NoError(t, err)
assert.Equal(t, []*GrepResult{
{
@ -41,7 +40,7 @@ func TestGrepSearch(t *testing.T) {
},
}, res)
res, err = GrepSearch(context.Background(), repo, "void", GrepOptions{PathspecList: []string{":(glob,exclude)java-hello/*"}})
res, err = GrepSearch(t.Context(), repo, "void", GrepOptions{PathspecList: []string{":(glob,exclude)java-hello/*"}})
assert.NoError(t, err)
assert.Equal(t, []*GrepResult{
{
@ -51,7 +50,7 @@ func TestGrepSearch(t *testing.T) {
},
}, res)
res, err = GrepSearch(context.Background(), repo, "void", GrepOptions{MaxResultLimit: 1})
res, err = GrepSearch(t.Context(), repo, "void", GrepOptions{MaxResultLimit: 1})
assert.NoError(t, err)
assert.Equal(t, []*GrepResult{
{
@ -61,7 +60,7 @@ func TestGrepSearch(t *testing.T) {
},
}, res)
res, err = GrepSearch(context.Background(), repo, "void", GrepOptions{MaxResultLimit: 1, MaxLineLength: 39})
res, err = GrepSearch(t.Context(), repo, "void", GrepOptions{MaxResultLimit: 1, MaxLineLength: 39})
assert.NoError(t, err)
assert.Equal(t, []*GrepResult{
{
@ -71,11 +70,11 @@ func TestGrepSearch(t *testing.T) {
},
}, res)
res, err = GrepSearch(context.Background(), repo, "no-such-content", GrepOptions{})
res, err = GrepSearch(t.Context(), repo, "no-such-content", GrepOptions{})
assert.NoError(t, err)
assert.Empty(t, res)
res, err = GrepSearch(context.Background(), &Repository{Path: "no-such-git-repo"}, "no-such-content", GrepOptions{})
res, err = GrepSearch(t.Context(), &Repository{Path: "no-such-git-repo"}, "no-such-content", GrepOptions{})
assert.Error(t, err)
assert.Empty(t, res)
}

View file

@ -4,7 +4,6 @@
package git
import (
"context"
"path/filepath"
"testing"
@ -18,7 +17,7 @@ func TestGetNotes(t *testing.T) {
defer bareRepo1.Close()
note := Note{}
err = GetNote(context.Background(), bareRepo1, "95bb4d39648ee7e325106df01a621c530863a653", &note)
err = GetNote(t.Context(), bareRepo1, "95bb4d39648ee7e325106df01a621c530863a653", &note)
assert.NoError(t, err)
assert.Equal(t, []byte("Note contents\n"), note.Message)
assert.Equal(t, "Vladimir Panteleev", note.Commit.Author.Name)
@ -31,10 +30,10 @@ func TestGetNestedNotes(t *testing.T) {
defer repo.Close()
note := Note{}
err = GetNote(context.Background(), repo, "3e668dbfac39cbc80a9ff9c61eb565d944453ba4", &note)
err = GetNote(t.Context(), repo, "3e668dbfac39cbc80a9ff9c61eb565d944453ba4", &note)
assert.NoError(t, err)
assert.Equal(t, []byte("Note 2"), note.Message)
err = GetNote(context.Background(), repo, "ba0a96fa63532d6c5087ecef070b0250ed72fa47", &note)
err = GetNote(t.Context(), repo, "ba0a96fa63532d6c5087ecef070b0250ed72fa47", &note)
assert.NoError(t, err)
assert.Equal(t, []byte("Note 1"), note.Message)
}
@ -46,7 +45,7 @@ func TestGetNonExistentNotes(t *testing.T) {
defer bareRepo1.Close()
note := Note{}
err = GetNote(context.Background(), bareRepo1, "non_existent_sha", &note)
err = GetNote(t.Context(), bareRepo1, "non_existent_sha", &note)
assert.Error(t, err)
assert.IsType(t, ErrNotExist{}, err)
}

View file

@ -47,7 +47,7 @@ func BenchmarkRepository_GetBranches(b *testing.B) {
}
defer bareRepo1.Close()
for i := 0; i < b.N; i++ {
for b.Loop() {
_, _, err := bareRepo1.GetBranchNames(0, 0)
if err != nil {
b.Fatal(err)

View file

@ -4,7 +4,6 @@
package git
import (
"context"
"path/filepath"
"testing"
@ -33,21 +32,21 @@ func TestRepoIsEmpty(t *testing.T) {
func TestRepoGetDivergingCommits(t *testing.T) {
bareRepo1Path := filepath.Join(testReposDir, "repo1_bare")
do, err := GetDivergingCommits(context.Background(), bareRepo1Path, "master", "branch2")
do, err := GetDivergingCommits(t.Context(), bareRepo1Path, "master", "branch2")
assert.NoError(t, err)
assert.Equal(t, DivergeObject{
Ahead: 1,
Behind: 5,
}, do)
do, err = GetDivergingCommits(context.Background(), bareRepo1Path, "master", "master")
do, err = GetDivergingCommits(t.Context(), bareRepo1Path, "master", "master")
assert.NoError(t, err)
assert.Equal(t, DivergeObject{
Ahead: 0,
Behind: 0,
}, do)
do, err = GetDivergingCommits(context.Background(), bareRepo1Path, "master", "test")
do, err = GetDivergingCommits(t.Context(), bareRepo1Path, "master", "test")
assert.NoError(t, err)
assert.Equal(t, DivergeObject{
Ahead: 0,

View file

@ -4,7 +4,6 @@
package git
import (
"context"
"os"
"path/filepath"
"testing"
@ -28,7 +27,7 @@ func TestGetTemplateSubmoduleCommits(t *testing.T) {
}
func TestAddTemplateSubmoduleIndexes(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
tmpDir := t.TempDir()
var err error
_, _, err = NewCommand(ctx, "init").RunStdString(&RunOpts{Dir: tmpDir})

View file

@ -179,7 +179,7 @@ func TestParseRepositoryURL(t *testing.T) {
ctxReq := &http.Request{URL: ctxURL, Header: http.Header{}}
ctxReq.Host = ctxURL.Host
ctxReq.Header.Add("X-Forwarded-Proto", ctxURL.Scheme)
ctx := context.WithValue(context.Background(), httplib.RequestContextKey, ctxReq)
ctx := context.WithValue(t.Context(), httplib.RequestContextKey, ctxReq)
cases := []struct {
input string
ownerName, repoName, remaining string
@ -249,19 +249,19 @@ func TestMakeRepositoryBaseLink(t *testing.T) {
defer test.MockVariableValue(&setting.AppURL, "https://localhost:3000/subpath")()
defer test.MockVariableValue(&setting.AppSubURL, "/subpath")()
u, err := ParseRepositoryURL(context.Background(), "https://localhost:3000/subpath/user/repo.git")
u, err := ParseRepositoryURL(t.Context(), "https://localhost:3000/subpath/user/repo.git")
assert.NoError(t, err)
assert.Equal(t, "/subpath/user/repo", MakeRepositoryWebLink(u))
u, err = ParseRepositoryURL(context.Background(), "https://github.com/owner/repo.git")
u, err = ParseRepositoryURL(t.Context(), "https://github.com/owner/repo.git")
assert.NoError(t, err)
assert.Equal(t, "https://github.com/owner/repo", MakeRepositoryWebLink(u))
u, err = ParseRepositoryURL(context.Background(), "git@github.com:owner/repo.git")
u, err = ParseRepositoryURL(t.Context(), "git@github.com:owner/repo.git")
assert.NoError(t, err)
assert.Equal(t, "https://github.com/owner/repo", MakeRepositoryWebLink(u))
u, err = ParseRepositoryURL(context.Background(), "git+ssh://other:123/owner/repo.git")
u, err = ParseRepositoryURL(t.Context(), "git+ssh://other:123/owner/repo.git")
assert.NoError(t, err)
assert.Equal(t, "https://other/owner/repo", MakeRepositoryWebLink(u))
}

View file

@ -66,7 +66,7 @@ func TestLockAndDo(t *testing.T) {
func testLockAndDo(t *testing.T) {
const concurrency = 50
ctx := context.Background()
ctx := t.Context()
count := 0
wg := sync.WaitGroup{}
wg.Add(concurrency)

View file

@ -46,14 +46,14 @@ func TestLocker(t *testing.T) {
func testLocker(t *testing.T, locker Locker) {
t.Run("lock", func(t *testing.T) {
parentCtx := context.Background()
parentCtx := t.Context()
release, err := locker.Lock(parentCtx, "test")
defer release()
assert.NoError(t, err)
func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
release, err := locker.Lock(ctx, "test")
defer release()
@ -64,7 +64,7 @@ func testLocker(t *testing.T, locker Locker) {
release()
func() {
release, err := locker.Lock(context.Background(), "test")
release, err := locker.Lock(t.Context(), "test")
defer release()
assert.NoError(t, err)
@ -72,7 +72,7 @@ func testLocker(t *testing.T, locker Locker) {
})
t.Run("try lock", func(t *testing.T) {
parentCtx := context.Background()
parentCtx := t.Context()
ok, release, err := locker.TryLock(parentCtx, "test")
defer release()
@ -80,7 +80,7 @@ func testLocker(t *testing.T, locker Locker) {
assert.NoError(t, err)
func() {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
ok, release, err := locker.TryLock(ctx, "test")
defer release()
@ -92,7 +92,7 @@ func testLocker(t *testing.T, locker Locker) {
release()
func() {
ok, release, _ := locker.TryLock(context.Background(), "test")
ok, release, _ := locker.TryLock(t.Context(), "test")
defer release()
assert.True(t, ok)
@ -100,7 +100,7 @@ func testLocker(t *testing.T, locker Locker) {
})
t.Run("wait and acquired", func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
release, err := locker.Lock(ctx, "test")
require.NoError(t, err)
@ -109,7 +109,7 @@ func testLocker(t *testing.T, locker Locker) {
go func() {
defer wg.Done()
started := time.Now()
release, err := locker.Lock(context.Background(), "test") // should be blocked for seconds
release, err := locker.Lock(t.Context(), "test") // should be blocked for seconds
defer release()
assert.Greater(t, time.Since(started), time.Second)
assert.NoError(t, err)
@ -122,7 +122,7 @@ func testLocker(t *testing.T, locker Locker) {
})
t.Run("multiple release", func(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
release1, err := locker.Lock(ctx, "test")
require.NoError(t, err)
@ -159,13 +159,13 @@ func testRedisLocker(t *testing.T, locker *redisLocker) {
// Otherwise, it will affect other tests.
t.Run("close", func(t *testing.T) {
assert.NoError(t, locker.Close())
_, err := locker.Lock(context.Background(), "test")
_, err := locker.Lock(t.Context(), "test")
assert.Error(t, err)
})
}()
t.Run("failed extend", func(t *testing.T) {
release, err := locker.Lock(context.Background(), "test")
release, err := locker.Lock(t.Context(), "test")
defer release()
require.NoError(t, err)

View file

@ -51,7 +51,7 @@ func (t *testTraceStarter) start(ctx context.Context, traceSpan *TraceSpan, inte
func TestTraceStarter(t *testing.T) {
globalTraceStarters = []traceStarter{&testTraceStarter{}}
ctx := context.Background()
ctx := t.Context()
ctx, span := GetTracer().Start(ctx, "root")
defer span.End()

View file

@ -44,7 +44,7 @@ func TestMakeAbsoluteURL(t *testing.T) {
defer test.MockVariableValue(&setting.AppURL, "http://cfg-host/sub/")()
defer test.MockVariableValue(&setting.AppSubURL, "/sub")()
ctx := context.Background()
ctx := t.Context()
assert.Equal(t, "http://cfg-host/sub/", MakeAbsoluteURL(ctx, ""))
assert.Equal(t, "http://cfg-host/foo", MakeAbsoluteURL(ctx, "foo"))
assert.Equal(t, "http://cfg-host/foo", MakeAbsoluteURL(ctx, "/foo"))
@ -76,7 +76,7 @@ func TestMakeAbsoluteURL(t *testing.T) {
func TestIsCurrentGiteaSiteURL(t *testing.T) {
defer test.MockVariableValue(&setting.AppURL, "http://localhost:3000/sub/")()
defer test.MockVariableValue(&setting.AppSubURL, "/sub")()
ctx := context.Background()
ctx := t.Context()
good := []string{
"?key=val",
"/sub",

View file

@ -11,7 +11,6 @@ import (
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/indexer/code/bleve"
"code.gitea.io/gitea/modules/indexer/code/elasticsearch"
"code.gitea.io/gitea/modules/indexer/code/internal"
@ -37,7 +36,7 @@ func TestMain(m *testing.M) {
func testIndexer(name string, t *testing.T, indexer internal.Indexer) {
t.Run(name, func(t *testing.T) {
assert.NoError(t, setupRepositoryIndexes(git.DefaultContext, indexer))
assert.NoError(t, setupRepositoryIndexes(t.Context(), indexer))
keywords := []struct {
RepoIDs []int64
@ -235,7 +234,7 @@ func testIndexer(name string, t *testing.T, indexer internal.Indexer) {
for _, kw := range keywords {
t.Run(kw.Keyword, func(t *testing.T) {
total, res, langs, err := indexer.Search(context.TODO(), &internal.SearchOptions{
total, res, langs, err := indexer.Search(t.Context(), &internal.SearchOptions{
RepoIDs: kw.RepoIDs,
Keyword: kw.Keyword,
Paginator: &db.ListOptions{
@ -275,7 +274,7 @@ func testIndexer(name string, t *testing.T, indexer internal.Indexer) {
})
}
assert.NoError(t, tearDownRepositoryIndexes(indexer))
assert.NoError(t, tearDownRepositoryIndexes(t.Context(), indexer))
})
}
@ -287,7 +286,7 @@ func TestBleveIndexAndSearch(t *testing.T) {
idx := bleve.NewIndexer(dir)
defer idx.Close()
_, err := idx.Init(context.Background())
_, err := idx.Init(t.Context())
require.NoError(t, err)
testIndexer("beleve", t, idx)
@ -303,7 +302,7 @@ func TestESIndexAndSearch(t *testing.T) {
}
indexer := elasticsearch.NewIndexer(u, "gitea_codes")
if _, err := indexer.Init(context.Background()); err != nil {
if _, err := indexer.Init(t.Context()); err != nil {
if indexer != nil {
indexer.Close()
}
@ -324,9 +323,9 @@ func setupRepositoryIndexes(ctx context.Context, indexer internal.Indexer) error
return nil
}
func tearDownRepositoryIndexes(indexer internal.Indexer) error {
func tearDownRepositoryIndexes(ctx context.Context, indexer internal.Indexer) error {
for _, repoID := range repositoriesToSearch() {
if err := indexer.Delete(context.Background(), repoID); err != nil {
if err := indexer.Delete(ctx, repoID); err != nil {
return err
}
}

View file

@ -4,7 +4,6 @@
package issues
import (
"context"
"testing"
"code.gitea.io/gitea/models/db"
@ -83,7 +82,7 @@ func searchIssueWithKeyword(t *testing.T) {
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -118,7 +117,7 @@ func searchIssueByIndex(t *testing.T) {
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -162,7 +161,7 @@ func searchIssueInRepo(t *testing.T) {
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -232,7 +231,7 @@ func searchIssueByID(t *testing.T) {
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -257,7 +256,7 @@ func searchIssueIsPull(t *testing.T) {
},
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -282,7 +281,7 @@ func searchIssueIsClosed(t *testing.T) {
},
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -307,7 +306,7 @@ func searchIssueIsArchived(t *testing.T) {
},
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -332,7 +331,7 @@ func searchIssueByMilestoneID(t *testing.T) {
},
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -363,7 +362,7 @@ func searchIssueByLabelID(t *testing.T) {
},
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -382,7 +381,7 @@ func searchIssueByTime(t *testing.T) {
},
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -401,7 +400,7 @@ func searchIssueWithOrder(t *testing.T) {
},
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -432,7 +431,7 @@ func searchIssueInProject(t *testing.T) {
},
}
for _, test := range tests {
issueIDs, _, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, _, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
}
@ -455,7 +454,7 @@ func searchIssueWithPaginator(t *testing.T) {
},
}
for _, test := range tests {
issueIDs, total, err := SearchIssues(context.TODO(), &test.opts)
issueIDs, total, err := SearchIssues(t.Context(), &test.opts)
require.NoError(t, err)
assert.Equal(t, test.expectedIDs, issueIDs)
assert.Equal(t, test.expectedTotal, total)

View file

@ -24,10 +24,10 @@ import (
)
func TestIndexer(t *testing.T, indexer internal.Indexer) {
_, err := indexer.Init(context.Background())
_, err := indexer.Init(t.Context())
require.NoError(t, err)
require.NoError(t, indexer.Ping(context.Background()))
require.NoError(t, indexer.Ping(t.Context()))
var (
ids []int64
@ -39,32 +39,32 @@ func TestIndexer(t *testing.T, indexer internal.Indexer) {
ids = append(ids, v.ID)
data[v.ID] = v
}
require.NoError(t, indexer.Index(context.Background(), d...))
require.NoError(t, indexer.Index(t.Context(), d...))
require.NoError(t, waitData(indexer, int64(len(data))))
}
defer func() {
require.NoError(t, indexer.Delete(context.Background(), ids...))
require.NoError(t, indexer.Delete(t.Context(), ids...))
}()
for _, c := range cases {
t.Run(c.Name, func(t *testing.T) {
if len(c.ExtraData) > 0 {
require.NoError(t, indexer.Index(context.Background(), c.ExtraData...))
require.NoError(t, indexer.Index(t.Context(), c.ExtraData...))
for _, v := range c.ExtraData {
data[v.ID] = v
}
require.NoError(t, waitData(indexer, int64(len(data))))
defer func() {
for _, v := range c.ExtraData {
require.NoError(t, indexer.Delete(context.Background(), v.ID))
require.NoError(t, indexer.Delete(t.Context(), v.ID))
delete(data, v.ID)
}
require.NoError(t, waitData(indexer, int64(len(data))))
}()
}
result, err := indexer.Search(context.Background(), c.SearchOptions)
result, err := indexer.Search(t.Context(), c.SearchOptions)
require.NoError(t, err)
if c.Expected != nil {
@ -80,7 +80,7 @@ func TestIndexer(t *testing.T, indexer internal.Indexer) {
// test counting
c.SearchOptions.Paginator = &db.ListOptions{PageSize: 0}
countResult, err := indexer.Search(context.Background(), c.SearchOptions)
countResult, err := indexer.Search(t.Context(), c.SearchOptions)
require.NoError(t, err)
assert.Empty(t, countResult.Hits)
assert.Equal(t, result.Total, countResult.Total)

View file

@ -4,7 +4,6 @@
package stats
import (
"context"
"testing"
"time"
@ -40,7 +39,7 @@ func TestRepoStatsIndex(t *testing.T) {
err = UpdateRepoIndexer(repo)
assert.NoError(t, err)
assert.NoError(t, queue.GetManager().FlushAll(context.Background(), 5*time.Second))
assert.NoError(t, queue.GetManager().FlushAll(t.Context(), 5*time.Second))
status, err := repo_model.GetIndexerStatus(db.DefaultContext, repo, repo_model.RepoIndexerTypeStats)
assert.NoError(t, err)

View file

@ -248,7 +248,7 @@ func TestHTTPClientDownload(t *testing.T) {
},
}
err := client.Download(context.Background(), []Pointer{p}, func(p Pointer, content io.ReadCloser, objectError error) error {
err := client.Download(t.Context(), []Pointer{p}, func(p Pointer, content io.ReadCloser, objectError error) error {
if objectError != nil {
return objectError
}
@ -348,7 +348,7 @@ func TestHTTPClientUpload(t *testing.T) {
},
}
err := client.Upload(context.Background(), []Pointer{p}, func(p Pointer, objectError error) (io.ReadCloser, error) {
err := client.Upload(t.Context(), []Pointer{p}, func(p Pointer, objectError error) (io.ReadCloser, error) {
return io.NopCloser(new(bytes.Buffer)), objectError
})
if c.expectedError != "" {

View file

@ -5,7 +5,6 @@ package lfs
import (
"bytes"
"context"
"io"
"net/http"
"strings"
@ -94,7 +93,7 @@ func TestBasicTransferAdapter(t *testing.T) {
}
for n, c := range cases {
_, err := a.Download(context.Background(), c.link)
_, err := a.Download(t.Context(), c.link)
if len(c.expectederror) > 0 {
assert.Contains(t, err.Error(), c.expectederror, "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror)
} else {
@ -127,7 +126,7 @@ func TestBasicTransferAdapter(t *testing.T) {
}
for n, c := range cases {
err := a.Upload(context.Background(), c.link, p, bytes.NewBufferString("dummy"))
err := a.Upload(t.Context(), c.link, p, bytes.NewBufferString("dummy"))
if len(c.expectederror) > 0 {
assert.Contains(t, err.Error(), c.expectederror, "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror)
} else {
@ -160,7 +159,7 @@ func TestBasicTransferAdapter(t *testing.T) {
}
for n, c := range cases {
err := a.Verify(context.Background(), c.link, p)
err := a.Verify(t.Context(), c.link, p)
if len(c.expectederror) > 0 {
assert.Contains(t, err.Error(), c.expectederror, "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror)
} else {

View file

@ -4,7 +4,6 @@
package log
import (
"context"
"fmt"
"io"
"net"
@ -40,7 +39,7 @@ func TestConnLogger(t *testing.T) {
level := INFO
flags := LstdFlags | LUTC | Lfuncname
logger := NewLoggerWithWriters(context.Background(), "test", NewEventWriterConn("test-conn", WriterMode{
logger := NewLoggerWithWriters(t.Context(), "test", NewEventWriterConn("test-conn", WriterMode{
Level: level,
Prefix: prefix,
Flags: FlagsFromBits(flags),

View file

@ -4,7 +4,6 @@
package log
import (
"context"
"sync"
"testing"
"time"
@ -53,7 +52,7 @@ func newDummyWriter(name string, level Level, delay time.Duration) *dummyWriter
}
func TestLogger(t *testing.T) {
logger := NewLoggerWithWriters(context.Background(), "test")
logger := NewLoggerWithWriters(t.Context(), "test")
dump := logger.DumpWriters()
assert.Empty(t, dump)
@ -88,7 +87,7 @@ func TestLogger(t *testing.T) {
}
func TestLoggerPause(t *testing.T) {
logger := NewLoggerWithWriters(context.Background(), "test")
logger := NewLoggerWithWriters(t.Context(), "test")
w1 := newDummyWriter("dummy-1", DEBUG, 0)
logger.AddWriters(w1)
@ -125,7 +124,7 @@ func (t *testLogStringPtrReceiver) LogString() string {
}
func TestLoggerLogString(t *testing.T) {
logger := NewLoggerWithWriters(context.Background(), "test")
logger := NewLoggerWithWriters(t.Context(), "test")
w1 := newDummyWriter("dummy-1", DEBUG, 0)
w1.Mode.Colorize = true
@ -142,7 +141,7 @@ func TestLoggerLogString(t *testing.T) {
}
func TestLoggerExpressionFilter(t *testing.T) {
logger := NewLoggerWithWriters(context.Background(), "test")
logger := NewLoggerWithWriters(t.Context(), "test")
w1 := newDummyWriter("dummy-1", DEBUG, 0)
w1.Mode.Expression = "foo.*"

View file

@ -4,7 +4,6 @@
package console
import (
"context"
"strings"
"testing"
@ -24,7 +23,7 @@ func TestRenderConsole(t *testing.T) {
canRender := render.CanRender("test", strings.NewReader(k))
assert.True(t, canRender)
err := render.Render(markup.NewRenderContext(context.Background()), strings.NewReader(k), &buf)
err := render.Render(markup.NewRenderContext(t.Context()), strings.NewReader(k), &buf)
assert.NoError(t, err)
assert.EqualValues(t, v, buf.String())
}

View file

@ -4,7 +4,6 @@
package markup
import (
"context"
"strings"
"testing"
@ -24,7 +23,7 @@ func TestRenderCSV(t *testing.T) {
for k, v := range kases {
var buf strings.Builder
err := render.Render(markup.NewRenderContext(context.Background()), strings.NewReader(k), &buf)
err := render.Render(markup.NewRenderContext(t.Context()), strings.NewReader(k), &buf)
assert.NoError(t, err)
assert.EqualValues(t, v, buf.String())
}

View file

@ -522,7 +522,7 @@ func BenchmarkEmojiPostprocess(b *testing.B) {
data += data
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for b.Loop() {
var res strings.Builder
err := markup.PostProcessDefault(markup.NewTestRenderContext(localMetas), strings.NewReader(data), &res)
assert.NoError(b, err)

View file

@ -12,14 +12,14 @@ import (
func BenchmarkSpecializedMarkdown(b *testing.B) {
// 240856 4719 ns/op
for i := 0; i < b.N; i++ {
for b.Loop() {
markdown.SpecializedMarkdown(&markup.RenderContext{})
}
}
func BenchmarkMarkdownRender(b *testing.B) {
// 23202 50840 ns/op
for i := 0; i < b.N; i++ {
for b.Loop() {
_, _ = markdown.RenderString(markup.NewTestRenderContext(), "https://example.com\n- a\n- b\n")
}
}

View file

@ -4,7 +4,6 @@
package markup
import (
"context"
"testing"
"code.gitea.io/gitea/modules/setting"
@ -13,7 +12,7 @@ import (
)
func TestResolveLinkRelative(t *testing.T) {
ctx := context.Background()
ctx := t.Context()
setting.AppURL = "http://localhost:3000"
assert.Equal(t, "/a", resolveLinkRelative(ctx, "/a", "", "", false))
assert.Equal(t, "/a/b", resolveLinkRelative(ctx, "/a", "b", "", false))

View file

@ -23,7 +23,7 @@ func TestGetManager(t *testing.T) {
func TestManager_AddContext(t *testing.T) {
pm := Manager{processMap: make(map[IDType]*process), next: 1}
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
p1Ctx, _, finished := pm.AddContext(ctx, "foo")
@ -42,7 +42,7 @@ func TestManager_AddContext(t *testing.T) {
func TestManager_Cancel(t *testing.T) {
pm := Manager{processMap: make(map[IDType]*process), next: 1}
ctx, _, finished := pm.AddContext(context.Background(), "foo")
ctx, _, finished := pm.AddContext(t.Context(), "foo")
defer finished()
pm.Cancel(GetPID(ctx))
@ -54,7 +54,7 @@ func TestManager_Cancel(t *testing.T) {
}
finished()
ctx, cancel, finished := pm.AddContext(context.Background(), "foo")
ctx, cancel, finished := pm.AddContext(t.Context(), "foo")
defer finished()
cancel()
@ -70,7 +70,7 @@ func TestManager_Cancel(t *testing.T) {
func TestManager_Remove(t *testing.T) {
pm := Manager{processMap: make(map[IDType]*process), next: 1}
ctx, cancel := context.WithCancel(context.Background())
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
p1Ctx, _, finished := pm.AddContext(ctx, "foo")

View file

@ -17,7 +17,7 @@ func testQueueBasic(t *testing.T, newFn func(cfg *BaseConfig) (baseQueue, error)
q, err := newFn(cfg)
assert.NoError(t, err)
ctx := context.Background()
ctx := t.Context()
_ = q.RemoveAll(ctx)
cnt, err := q.Len(ctx)
assert.NoError(t, err)
@ -121,7 +121,7 @@ func TestBaseDummy(t *testing.T) {
q, err := newBaseDummy(&BaseConfig{}, true)
assert.NoError(t, err)
ctx := context.Background()
ctx := t.Context()
assert.NoError(t, q.PushItem(ctx, []byte("foo")))
cnt, err := q.Len(ctx)

View file

@ -4,7 +4,6 @@
package queue
import (
"context"
"path/filepath"
"testing"
@ -80,7 +79,7 @@ MAX_WORKERS = 123
assert.NoError(t, err)
q1 := createWorkerPoolQueue[string](context.Background(), "no-such", cfgProvider, nil, false)
q1 := createWorkerPoolQueue[string](t.Context(), "no-such", cfgProvider, nil, false)
assert.Equal(t, "no-such", q1.GetName())
assert.Equal(t, "dummy", q1.GetType()) // no handler, so it becomes dummy
assert.Equal(t, filepath.Join(setting.AppDataPath, "queues/dir1"), q1.baseConfig.DataFullDir)
@ -96,7 +95,7 @@ MAX_WORKERS = 123
assert.Equal(t, "string", q1.GetItemTypeName())
qid1 := GetManager().qidCounter
q2 := createWorkerPoolQueue(context.Background(), "sub", cfgProvider, func(s ...int) (unhandled []int) { return nil }, false)
q2 := createWorkerPoolQueue(t.Context(), "sub", cfgProvider, func(s ...int) (unhandled []int) { return nil }, false)
assert.Equal(t, "sub", q2.GetName())
assert.Equal(t, "level", q2.GetType())
assert.Equal(t, filepath.Join(setting.AppDataPath, "queues/dir2"), q2.baseConfig.DataFullDir)
@ -118,7 +117,7 @@ MAX_WORKERS = 123
assert.Equal(t, 120, q1.workerMaxNum)
stop := runWorkerPoolQueue(q2)
assert.NoError(t, GetManager().GetManagedQueue(qid2).FlushWithContext(context.Background(), 0))
assert.NoError(t, GetManager().FlushAll(context.Background(), 0))
assert.NoError(t, GetManager().GetManagedQueue(qid2).FlushWithContext(t.Context(), 0))
assert.NoError(t, GetManager().FlushAll(t.Context(), 0))
stop()
}

View file

@ -4,7 +4,6 @@
package queue
import (
"context"
"slices"
"strconv"
"sync"
@ -58,7 +57,7 @@ func TestWorkerPoolQueueUnhandled(t *testing.T) {
testRecorder.Record("push:%v", i)
assert.NoError(t, q.Push(i))
}
assert.NoError(t, q.FlushWithContext(context.Background(), 0))
assert.NoError(t, q.FlushWithContext(t.Context(), 0))
stop()
ok := true
@ -166,7 +165,7 @@ func testWorkerPoolQueuePersistence(t *testing.T, queueSetting setting.QueueSett
q, _ := newWorkerPoolQueueForTest("pr_patch_checker_test", queueSetting, testHandler, true)
stop := runWorkerPoolQueue(q)
assert.NoError(t, q.FlushWithContext(context.Background(), 0))
assert.NoError(t, q.FlushWithContext(t.Context(), 0))
stop()
}

View file

@ -4,7 +4,6 @@
package testlogger
import (
"context"
"fmt"
"os"
"runtime"
@ -131,7 +130,7 @@ func PrintCurrentTest(t testing.TB, skip ...int) func() {
slowFlushChecker := time.AfterFunc(TestSlowFlush, func() {
Printf("+++ %s ... still flushing after %v ...\n", log.NewColoredValue(t.Name(), log.Bold, log.FgRed), TestSlowFlush)
})
if err := queue.GetManager().FlushAll(context.Background(), -1); err != nil {
if err := queue.GetManager().FlushAll(t.Context(), -1); err != nil {
t.Errorf("Flushing queues failed with error %v", err)
}
slowFlushChecker.Stop()

View file

@ -18,14 +18,14 @@ func TestCallerFuncName(t *testing.T) {
func BenchmarkCallerFuncName(b *testing.B) {
// BenchmarkCaller/sprintf-12 12744829 95.49 ns/op
b.Run("sprintf", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for b.Loop() {
_ = fmt.Sprintf("aaaaaaaaaaaaaaaa %s %s %s", "bbbbbbbbbbbbbbbbbbb", b.Name(), "ccccccccccccccccccccc")
}
})
// BenchmarkCaller/caller-12 10625133 113.6 ns/op
// It is almost as fast as fmt.Sprintf
b.Run("caller", func(b *testing.B) {
for i := 0; i < b.N; i++ {
for b.Loop() {
CallerFuncName(1)
}
})

View file

@ -215,7 +215,7 @@ func TestToUpperASCII(t *testing.T) {
func BenchmarkToUpper(b *testing.B) {
for _, tc := range upperTests {
b.Run(tc.in, func(b *testing.B) {
for i := 0; i < b.N; i++ {
for b.Loop() {
ToUpperASCII(tc.in)
}
})