[v15.0/forgejo]: chore: add modernizer linter (#11949)

**Backport: !11936**

- Go has a suite of small linters that helps with modernizing Go code by using newer functions and catching small mistakes, https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/modernize.
- Enable this linter in golangci-lint.
- There's also [`go fix`](https://go.dev/blog/gofix), which is not yet released as a linter in golangci-lint: https://github.com/golangci/golangci-lint/pull/6385

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/11949
Reviewed-by: Mathieu Fenniak <mfenniak@noreply.codeberg.org>
Co-authored-by: Gusted <postmaster@gusted.xyz>
Co-committed-by: Gusted <postmaster@gusted.xyz>
This commit is contained in:
Gusted 2026-04-02 16:54:46 +02:00 committed by Mathieu Fenniak
parent a32804bebe
commit 607d031069
247 changed files with 650 additions and 1001 deletions

View file

@ -88,7 +88,7 @@ jobs:
labelStr := "/api/v1/repos/user2/repo-pull-request/labels"
labelsCount := 2
labels := make([]*api.Label, labelsCount)
for i := 0; i < labelsCount; i++ {
for i := range labelsCount {
color := "abcdef"
req := NewRequestWithJSON(t, "POST", labelStr, &api.CreateLabelOption{
Name: fmt.Sprintf("label%d", i),

View file

@ -48,13 +48,13 @@ func TestActivityPubPersonInboxFollow(t *testing.T) {
ctx, _ := contexttest.MockAPIContext(t, localUser2Inbox)
// distant follows local
followActivity := []byte(fmt.Sprintf(
followActivity := fmt.Appendf(nil,
`{"type":"Follow",`+
`"actor":"%s",`+
`"object":"%s"}`,
distantUser15URL,
localUser2URL,
))
)
cf, err := activitypub.NewClientFactoryWithTimeout(60 * time.Second)
require.NoError(t, err)
c, err := cf.WithKeysDirect(ctx, mock.ApActor.PrivKey,
@ -84,7 +84,7 @@ func TestActivityPubPersonInboxFollow(t *testing.T) {
assert.Contains(t, mock.LastPost, "\"type\":\"Accept\"")
// distant undoes follow
undoFollowActivity := []byte(fmt.Sprintf(
undoFollowActivity := fmt.Appendf(nil,
`{"type":"Undo",`+
`"actor":"%s",`+
`"object":{"type":"Follow",`+
@ -93,7 +93,7 @@ func TestActivityPubPersonInboxFollow(t *testing.T) {
distantUser15URL,
distantUser15URL,
localUser2URL,
))
)
c, err = cf.WithKeysDirect(ctx, mock.ApActor.PrivKey,
mock.ApActor.KeyID(federatedSrv.URL))
require.NoError(t, err)

View file

@ -53,13 +53,13 @@ func TestActivityPubPersonInboxNoteToDistant(t *testing.T) {
defer f()
// follow (distant follows local)
followActivity := []byte(fmt.Sprintf(
followActivity := fmt.Appendf(nil,
`{"type":"Follow",`+
`"actor":"%s",`+
`"object":"%s"}`,
distantUser15URL,
localUser2URL,
))
)
ctx, _ := contexttest.MockAPIContext(t, localUser2Inbox)
cf, err := activitypub.NewClientFactoryWithTimeout(60 * time.Second)
require.NoError(t, err)

View file

@ -89,13 +89,13 @@ func TestActivityPubRepositoryInboxValid(t *testing.T) {
mock.Persons[0].KeyID(federatedSrv.URL))
require.NoError(t, err)
activity1 := []byte(fmt.Sprintf(
activity1 := fmt.Appendf(nil,
`{"type":"Like",`+
`"startTime":"%s",`+
`"actor":"%s/api/v1/activitypub/user-id/15",`+
`"object":"%s"}`,
timeNow.Format(time.RFC3339),
federatedSrv.URL, u.JoinPath(fmt.Sprintf("/api/v1/activitypub/repository-id/%d", repositoryID)).String()))
federatedSrv.URL, u.JoinPath(fmt.Sprintf("/api/v1/activitypub/repository-id/%d", repositoryID)).String())
t.Logf("activity: %s", activity1)
resp, err := c.Post(activity1, localRepoInbox)
@ -107,14 +107,14 @@ func TestActivityPubRepositoryInboxValid(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &user.User{ID: federatedUser.UserID})
// A like activity by a different user of the same federated host.
activity2 := []byte(fmt.Sprintf(
activity2 := fmt.Appendf(nil,
`{"type":"Like",`+
`"startTime":"%s",`+
`"actor":"%s/api/v1/activitypub/user-id/30",`+
`"object":"%s"}`,
// Make sure this activity happens later then the one before
timeNow.Add(time.Second).Format(time.RFC3339),
federatedSrv.URL, u.JoinPath(fmt.Sprintf("/api/v1/activitypub/repository-id/%d", repositoryID)).String()))
federatedSrv.URL, u.JoinPath(fmt.Sprintf("/api/v1/activitypub/repository-id/%d", repositoryID)).String())
t.Logf("activity: %s", activity2)
resp, err = c.Post(activity2, localRepoInbox)
@ -127,14 +127,14 @@ func TestActivityPubRepositoryInboxValid(t *testing.T) {
// The same user sends another like activity
otherRepositoryID := 3
otherRepoInboxURL := u.JoinPath(fmt.Sprintf("/api/v1/activitypub/repository-id/%d/inbox", otherRepositoryID)).String()
activity3 := []byte(fmt.Sprintf(
activity3 := fmt.Appendf(nil,
`{"type":"Like",`+
`"startTime":"%s",`+
`"actor":"%s/api/v1/activitypub/user-id/30",`+
`"object":"%s"}`,
// Make sure this activity happens later then the ones before
timeNow.Add(time.Second*2).Format(time.RFC3339),
federatedSrv.URL, u.JoinPath(fmt.Sprintf("/api/v1/activitypub/repository-id/%d", otherRepositoryID)).String()))
federatedSrv.URL, u.JoinPath(fmt.Sprintf("/api/v1/activitypub/repository-id/%d", otherRepositoryID)).String())
t.Logf("activity: %s", activity3)
resp, err = c.Post(activity3, otherRepoInboxURL)

View file

@ -273,7 +273,7 @@ func doAPIMergePullRequestForm(t *testing.T, ctx APITestContext, owner, repo str
var req *RequestWrapper
var resp *httptest.ResponseRecorder
for i := 0; i < 6; i++ {
for range 6 {
req = NewRequestWithJSON(t, http.MethodPost, urlStr, merge).AddTokenAuth(ctx.Token)
resp = ctx.Session.MakeRequest(t, req, NoExpectedStatus)

View file

@ -228,7 +228,7 @@ func TestAPICreateIssueParallel(t *testing.T) {
urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues?state=all", owner.Name, repoBefore.Name)
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
for i := range 100 {
wg.Add(1)
go func(parentT *testing.T, i int) {
parentT.Run(fmt.Sprintf("ParallelCreateIssue_%d", i), func(t *testing.T) {
@ -499,10 +499,9 @@ func TestAPISearchIssues(t *testing.T) {
defer tests.PrepareTestEnv(t)()
// as this API was used in the frontend, it uses UI page size
expectedIssueCount := 20 // from the fixtures
if expectedIssueCount > setting.UI.IssuePagingNum {
expectedIssueCount = setting.UI.IssuePagingNum
}
expectedIssueCount := min(
// from the fixtures
20, setting.UI.IssuePagingNum)
link, _ := url.Parse("/api/v1/repos/issues/search")
token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadIssue)
@ -603,10 +602,9 @@ func TestAPISearchIssuesWithLabels(t *testing.T) {
defer tests.PrepareTestEnv(t)()
// as this API was used in the frontend, it uses UI page size
expectedIssueCount := 20 // from the fixtures
if expectedIssueCount > setting.UI.IssuePagingNum {
expectedIssueCount = setting.UI.IssuePagingNum
}
expectedIssueCount := min(
// from the fixtures
20, setting.UI.IssuePagingNum)
link, _ := url.Parse("/api/v1/repos/issues/search")
token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadIssue)

View file

@ -181,9 +181,9 @@ enabled=1`,
var result ReleaseClassic
lines := strings.Split(resp, "\n")
lines := strings.SplitSeq(resp, "\n")
for _, line := range lines {
for line := range lines {
parts := strings.SplitN(line, ": ", 2)
if len(parts) < 2 {
continue
@ -406,7 +406,7 @@ enabled=1`,
if typ == 6 || typ == 8 || typ == 9 {
elem := data[offset:]
for j := uint32(0); j < count; j++ {
for range count {
strEnd := bytes.IndexByte(elem, 0)
if strEnd == -1 {
require.NoError(t, err)
@ -420,13 +420,13 @@ enabled=1`,
result.Release = string(elem[:strEnd])
case 1004:
var summaries []string
for i := uint32(0); i < count; i++ {
for range count {
summaries = append(summaries, string(elem[:strEnd]))
}
result.Summary = summaries
case 1005:
var descriptions []string
for i := uint32(0); i < count; i++ {
for range count {
descriptions = append(descriptions, string(elem[:strEnd]))
}
result.Description = descriptions
@ -436,7 +436,7 @@ enabled=1`,
result.Packager = string(elem[:strEnd])
case 1016:
var groups []string
for i := uint32(0); i < count; i++ {
for range count {
groups = append(groups, string(elem[:strEnd]))
}
result.Group = groups
@ -448,49 +448,49 @@ enabled=1`,
result.SourceRpm = string(elem[:strEnd])
case 1047:
var provideNames []string
for i := uint32(0); i < count; i++ {
for range count {
provideNames = append(provideNames, string(elem[:strEnd]))
}
result.ProvideNames = provideNames
case 1049:
var requireNames []string
for i := uint32(0); i < count; i++ {
for range count {
requireNames = append(requireNames, string(elem[:strEnd]))
}
result.RequireNames = requireNames
case 1050:
var requireVersions []string
for i := uint32(0); i < count; i++ {
for range count {
requireVersions = append(requireVersions, string(elem[:strEnd]))
}
result.RequireVersions = requireVersions
case 1081:
var changeLogNames []string
for i := uint32(0); i < count; i++ {
for range count {
changeLogNames = append(changeLogNames, string(elem[:strEnd]))
}
result.ChangeLogNames = changeLogNames
case 1082:
var changeLogTexts []string
for i := uint32(0); i < count; i++ {
for range count {
changeLogTexts = append(changeLogTexts, string(elem[:strEnd]))
}
result.ChangeLogTexts = changeLogTexts
case 1113:
var provideVersions []string
for i := uint32(0); i < count; i++ {
for range count {
provideVersions = append(provideVersions, string(elem[:strEnd]))
}
result.ProvideVersions = provideVersions
case 1117:
var baseNames []string
for i := uint32(0); i < count; i++ {
for range count {
baseNames = append(baseNames, string(elem[:strEnd]))
}
result.BaseNames = baseNames
case 1118:
var dirNames []string
for i := uint32(0); i < count; i++ {
for range count {
dirNames = append(dirNames, string(elem[:strEnd]))
}
result.DirNames = dirNames
@ -509,7 +509,7 @@ enabled=1`,
}
} else if typ == 4 {
elem := data[offset:]
for j := uint32(0); j < count; j++ {
for range count {
val := binary.BigEndian.Uint32(elem)
switch tag {
case 1006:
@ -518,25 +518,25 @@ enabled=1`,
result.Size = int(val)
case 1048:
var requireFlags []int
for i := uint32(0); i < count; i++ {
for range count {
requireFlags = append(requireFlags, int(val))
}
result.RequireFlags = requireFlags
case 1080:
var changeLogTimes []int
for i := uint32(0); i < count; i++ {
for range count {
changeLogTimes = append(changeLogTimes, int(val))
}
result.ChangeLogTimes = changeLogTimes
case 1112:
var provideFlags []int
for i := uint32(0); i < count; i++ {
for range count {
provideFlags = append(provideFlags, int(val))
}
result.ProvideFlags = provideFlags
case 1116:
var dirIndexes []int
for i := uint32(0); i < count; i++ {
for range count {
dirIndexes = append(dirIndexes, int(val))
}
result.DirIndexes = dirIndexes

View file

@ -182,7 +182,7 @@ nwIDAQAB
var data []byte
if version == "1.3" {
data = []byte(fmt.Sprintf(
data = fmt.Appendf(nil,
"Method:%s\nPath:%s\nX-Ops-Content-Hash:%s\nX-Ops-Sign:version=%s\nX-Ops-Timestamp:%s\nX-Ops-UserId:%s\nX-Ops-Server-API-Version:%s",
req.Method,
path.Clean(req.URL.Path),
@ -191,17 +191,17 @@ nwIDAQAB
req.Header.Get("X-Ops-Timestamp"),
username,
req.Header.Get("X-Ops-Server-Api-Version"),
))
)
} else {
sum := sha1.Sum([]byte(path.Clean(req.URL.Path)))
data = []byte(fmt.Sprintf(
data = fmt.Appendf(nil,
"Method:%s\nHashed Path:%s\nX-Ops-Content-Hash:%s\nX-Ops-Timestamp:%s\nX-Ops-UserId:%s",
req.Method,
base64.StdEncoding.EncodeToString(sum[:]),
req.Header.Get("X-Ops-Content-Hash"),
req.Header.Get("X-Ops-Timestamp"),
username,
))
)
}
for k := range req.Header {

View file

@ -873,7 +873,7 @@ func TestPackageContainer(t *testing.T) {
url := fmt.Sprintf("%sv2/%s/parallel", setting.AppURL, user.Name)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
for i := range 10 {
wg.Add(1)
content := []byte{byte(i)}

View file

@ -291,7 +291,7 @@ func TestPackageMavenConcurrent(t *testing.T) {
defer tests.PrintCurrentTest(t)()
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
for i := range 10 {
wg.Add(1)
go func(i int) {
putFile(t, fmt.Sprintf("/%s/%s.jar", packageVersion, strconv.Itoa(i)), "test", http.StatusCreated)

View file

@ -31,7 +31,7 @@ func TestAPITopicSearchPaging(t *testing.T) {
token2 := getUserToken(t, user2.Name, auth_model.AccessTokenScopeWriteRepository)
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
for i := 0; i < 20; i++ {
for i := range 20 {
req := NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/paging-topic-%d", user2.Name, repo2.Name, i).
AddTokenAuth(token2)
MakeRequest(t, req, http.StatusNoContent)

View file

@ -183,7 +183,7 @@ func TestActions_CmdForgejo_Actions(t *testing.T) {
//
// Run twice to verify it is idempotent
//
for i := 0; i < 2; i++ {
for range 2 {
uuid, err := runMainApp("forgejo-cli", cmd...)
require.NoError(t, err)
if assert.Equal(t, testCase.uuid, uuid) {

View file

@ -143,7 +143,7 @@ func doGitInitTestRepository(dstPath string, objectFormat git.ObjectFormat) func
// forcibly set default branch to master
_, _, err := git.NewCommand(git.DefaultContext, "symbolic-ref", "HEAD", git.BranchPrefix+"master").RunStdString(&git.RunOpts{Dir: dstPath})
require.NoError(t, err)
require.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), fmt.Appendf(nil, "# Testing Repository\n\nOriginally created in: %s", dstPath), 0o644))
require.NoError(t, git.AddChanges(dstPath, true))
signature := git.Signature{
Email: "test@example.com",
@ -194,7 +194,7 @@ func doGitAddSomeCommits(dstPath, branch string) func(*testing.T) {
return func(t *testing.T) {
doGitCheckoutBranch(dstPath, branch)(t)
require.NoError(t, os.WriteFile(filepath.Join(dstPath, fmt.Sprintf("file-%s.txt", branch)), []byte(fmt.Sprintf("file %s", branch)), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(dstPath, fmt.Sprintf("file-%s.txt", branch)), fmt.Appendf(nil, "file %s", branch), 0o644))
require.NoError(t, git.AddChanges(dstPath, true))
signature := git.Signature{
Email: "test@test.test",

View file

@ -45,7 +45,7 @@ func testGitPush(t *testing.T, u *url.URL) {
forEachObjectFormat(t, func(t *testing.T, objectFormat git.ObjectFormat) {
t.Run("Push branches at once", func(t *testing.T) {
runTestGitPush(t, u, objectFormat, func(t *testing.T, gitPath string) (pushed, deleted []string) {
for i := 0; i < 10; i++ {
for i := range 10 {
branchName := fmt.Sprintf("branch-%d", i)
pushed = append(pushed, branchName)
doGitCreateBranch(gitPath, branchName)(t)
@ -58,7 +58,7 @@ func testGitPush(t *testing.T, u *url.URL) {
t.Run("Push branches exists", func(t *testing.T) {
runTestGitPush(t, u, objectFormat, func(t *testing.T, gitPath string) (pushed, deleted []string) {
for i := 0; i < 10; i++ {
for i := range 10 {
branchName := fmt.Sprintf("branch-%d", i)
if i < 5 {
pushed = append(pushed, branchName)
@ -72,7 +72,7 @@ func testGitPush(t *testing.T, u *url.URL) {
pushed = pushed[:0]
// do some changes for the first 5 branches created above
for i := 0; i < 5; i++ {
for i := range 5 {
branchName := fmt.Sprintf("branch-%d", i)
pushed = append(pushed, branchName)
@ -93,7 +93,7 @@ func testGitPush(t *testing.T, u *url.URL) {
t.Run("Push branches one by one", func(t *testing.T) {
runTestGitPush(t, u, objectFormat, func(t *testing.T, gitPath string) (pushed, deleted []string) {
for i := 0; i < 10; i++ {
for i := range 10 {
branchName := fmt.Sprintf("branch-%d", i)
doGitCreateBranch(gitPath, branchName)(t)
doGitPushTestRepository(gitPath, "origin", branchName)(t)
@ -108,14 +108,14 @@ func testGitPush(t *testing.T, u *url.URL) {
doGitPushTestRepository(gitPath, "origin", "master")(t) // make sure master is the default branch instead of a branch we are going to delete
pushed = append(pushed, "master")
for i := 0; i < 10; i++ {
for i := range 10 {
branchName := fmt.Sprintf("branch-%d", i)
pushed = append(pushed, branchName)
doGitCreateBranch(gitPath, branchName)(t)
}
doGitPushTestRepository(gitPath, "origin", "--all")(t)
for i := 0; i < 10; i++ {
for i := range 10 {
branchName := fmt.Sprintf("branch-%d", i)
doGitPushTestRepository(gitPath, "origin", "--delete", branchName)(t)
deleted = append(deleted, branchName)

View file

@ -9,6 +9,7 @@ import (
"encoding/hex"
"fmt"
"io"
"maps"
"net/http"
"net/url"
"os"
@ -487,9 +488,7 @@ func doProtectBranch(ctx APITestContext, branch string, addParameter ...paramete
"rule_name": branch,
}
if len(addParameter) > 0 {
for k, v := range addParameter[0] {
parameter[k] = v
}
maps.Copy(parameter, addParameter[0])
}
// Change branch to protected
@ -1162,15 +1161,15 @@ func doLFSNoAccess(ctx APITestContext, publicKeyID int64, objectFormat git.Objec
}
func extractRemoteMessages(stderr string) string {
var remoteMsg string
var remoteMsg strings.Builder
for line := range strings.SplitSeq(stderr, "\n") {
msg, found := strings.CutPrefix(line, "remote: ")
if found {
remoteMsg += msg
remoteMsg += "\n"
remoteMsg.WriteString(msg)
remoteMsg.WriteString("\n")
}
}
return remoteMsg
return remoteMsg.String()
}
func doTestForkPushMessages(apictx APITestContext, dstPath string) func(*testing.T) {

View file

@ -471,14 +471,14 @@ func loginUserMaybeTOTP(t testing.TB, user *user_model.User, useTOTP bool) *Test
}
// token has to be unique this counter take care of
var tokenCounter int64
var tokenCounter atomic.Int64
// getTokenForLoggedInUser returns a token for a logged in user.
// The scope is an optional list of snake_case strings like the frontend form fields,
// but without the "scope_" prefix.
func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...auth.AccessTokenScope) string {
t.Helper()
accessTokenName := fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1))
accessTokenName := fmt.Sprintf("api-testing-token-%d", tokenCounter.Add(1))
createApplicationSettingsToken(t, session, accessTokenName, scopes...)
token := assertAccessToken(t, session)
return token

View file

@ -5,6 +5,7 @@ package integration
import (
"net/http"
"slices"
"strconv"
"strings"
"testing"
@ -71,13 +72,7 @@ func testIssueCommentChangeEvent(t *testing.T, htmlDoc *HTMLDoc, commentID, badg
// Check links (href)
issueCommentLink := "#issuecomment-" + commentID
found := false
for _, link := range links {
if link == issueCommentLink {
found = true
break
}
}
found := slices.Contains(links, issueCommentLink)
if !found {
links = append(links, issueCommentLink)
}

View file

@ -114,14 +114,11 @@ func TestViewIssuesSortByType(t *testing.T) {
htmlDoc := NewHTMLParser(t, resp.Body)
issuesSelection := getIssuesSelection(t, htmlDoc)
expectedNumIssues := unittest.GetCount(t,
expectedNumIssues := min(unittest.GetCount(t,
&issues_model.Issue{RepoID: repo.ID, PosterID: user.ID},
unittest.Cond("is_closed=?", false),
unittest.Cond("is_pull=?", false),
)
if expectedNumIssues > setting.UI.IssuePagingNum {
expectedNumIssues = setting.UI.IssuePagingNum
}
), setting.UI.IssuePagingNum)
assert.Equal(t, expectedNumIssues, issuesSelection.Length())
issuesSelection.Each(func(_ int, selection *goquery.Selection) {
@ -891,10 +888,9 @@ func TestSearchIssues(t *testing.T) {
session := loginUser(t, "user2")
expectedIssueCount := 20 // from the fixtures
if expectedIssueCount > setting.UI.IssuePagingNum {
expectedIssueCount = setting.UI.IssuePagingNum
}
expectedIssueCount := min(
// from the fixtures
20, setting.UI.IssuePagingNum)
req := NewRequest(t, "GET", "/issues/search")
resp := session.MakeRequest(t, req, http.StatusOK)
@ -1017,10 +1013,9 @@ func TestSearchIssues(t *testing.T) {
func TestSearchIssuesWithLabels(t *testing.T) {
defer tests.PrepareTestEnv(t)()
expectedIssueCount := 20 // from the fixtures
if expectedIssueCount > setting.UI.IssuePagingNum {
expectedIssueCount = setting.UI.IssuePagingNum
}
expectedIssueCount := min(
// from the fixtures
20, setting.UI.IssuePagingNum)
session := loginUser(t, "user1")
link, _ := url.Parse("/issues/search")

View file

@ -46,7 +46,7 @@ func TestOrgRepos(t *testing.T) {
sel := htmlDoc.doc.Find("a.name")
assert.Len(t, repos, len(sel.Nodes))
for i := 0; i < len(repos); i++ {
for i := range repos {
assert.Equal(t, repos[i], strings.TrimSpace(sel.Eq(i).Text()))
}
}

View file

@ -45,7 +45,7 @@ func TestMoveRepoProjectColumns(t *testing.T) {
err := project_model.NewProject(db.DefaultContext, &project1)
require.NoError(t, err)
for i := 0; i < 3; i++ {
for i := range 3 {
err = project_model.NewColumn(db.DefaultContext, &project_model.Column{
Title: fmt.Sprintf("column %d", i+1),
ProjectID: project1.ID,

View file

@ -8,6 +8,7 @@ import (
"context"
"encoding/base64"
"fmt"
"maps"
"math/rand/v2"
"net/http"
"net/http/httptest"
@ -71,9 +72,7 @@ func testPullMergeForm(t *testing.T, session *TestSession, expectedCode int, use
link := path.Join(user, repo, "pulls", pullnum, "merge")
options := map[string]string{}
for k, v := range addOptions {
options[k] = v
}
maps.Copy(options, addOptions)
req := NewRequestWithValues(t, "POST", link, options)
resp := session.MakeRequest(t, req, expectedCode)

View file

@ -7,6 +7,7 @@ import (
"bytes"
"fmt"
"io"
"maps"
"mime/multipart"
"net/http"
"net/http/httptest"
@ -656,9 +657,7 @@ func (ctx *quotaWebEnvAsContext) With(opts Context) *quotaWebEnvAsContext {
ctx.Repo = opts.Repo
}
if opts.Payload != nil {
for key, value := range *opts.Payload {
ctx.Payload[key] = value
}
maps.Copy(ctx.Payload, *opts.Payload)
}
return ctx
}

View file

@ -231,7 +231,7 @@ func TestCreateReleasePaging(t *testing.T) {
session := loginUser(t, "user2")
// Create enough releases to have paging
for i := 0; i < 12; i++ {
for i := range 12 {
version := fmt.Sprintf("v0.0.%d", i)
createNewRelease(t, session, "/user2/repo1", version, version, false, false)
}

View file

@ -146,7 +146,7 @@ func TestRepoCommitsStatusParallel(t *testing.T) {
assert.NotEmpty(t, commitURL)
var wg sync.WaitGroup
for i := 0; i < 10; i++ {
for i := range 10 {
wg.Add(1)
go func(parentT *testing.T, i int) {
parentT.Run(fmt.Sprintf("ParallelCreateStatus_%d", i), func(t *testing.T) {

View file

@ -135,7 +135,7 @@ func TestRepositoryFlagsAPI(t *testing.T) {
assert.Empty(t, flags)
// Replacing all tags works, twice in a row
for i := 0; i < 2; i++ {
for range 2 {
req = NewRequestWithJSON(t, "PUT", fmt.Sprintf(baseURLFmtStr, ""), &api.ReplaceFlagsOption{
Flags: []string{"flag-1", "flag-2", "flag-3"},
}).AddTokenAuth(token)
@ -160,7 +160,7 @@ func TestRepositoryFlagsAPI(t *testing.T) {
MakeRequest(t, req, http.StatusNotFound)
// We can add the same flag twice
for i := 0; i < 2; i++ {
for range 2 {
req = NewRequestf(t, "PUT", baseURLFmtStr, "/brand-new-flag").AddTokenAuth(token)
MakeRequest(t, req, http.StatusNoContent)
}
@ -170,7 +170,7 @@ func TestRepositoryFlagsAPI(t *testing.T) {
MakeRequest(t, req, http.StatusNoContent)
// We can delete a flag, twice
for i := 0; i < 2; i++ {
for range 2 {
req = NewRequestf(t, "DELETE", baseURLFmtStr, "/flag-3").AddTokenAuth(token)
MakeRequest(t, req, http.StatusNoContent)
}

View file

@ -62,7 +62,7 @@ func TestTopicSearchPaging(t *testing.T) {
token2 := getUserToken(t, user2.Name, auth_model.AccessTokenScopeWriteRepository)
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
for i := 0; i < 20; i++ {
for i := range 20 {
req := NewRequestf(t, "PUT", "/api/v1/repos/%s/%s/topics/paging-topic-%d", user2.Name, repo2.Name, i).
AddTokenAuth(token2)
MakeRequest(t, req, http.StatusNoContent)

View file

@ -4,6 +4,7 @@
package integration
import (
"maps"
"net/http"
"net/http/httptest"
"net/url"
@ -408,9 +409,7 @@ func testWebhookFormsShared(t *testing.T, endpoint, name string, session *TestSe
payload := map[string]string{
"events": "send_everything",
}
for k, v := range validFields {
payload[k] = v
}
maps.Copy(payload, validFields)
for k, v := range invalidPatch {
if v == "" {
delete(payload, k)
@ -448,9 +447,7 @@ func assertHasFlashMessages(t *testing.T, resp *httptest.ResponseRecorder, expec
for key, value := range flash {
// the key is itself url-encoded
if flash, err := url.ParseQuery(key); err == nil {
for key, value := range flash {
seenKeys[key] = value
}
maps.Copy(seenKeys, flash)
} else {
seenKeys[key] = value
}

View file

@ -433,7 +433,7 @@ func crudActionCreateFile(_ *testing.T, ctx APITestContext, user *user_model.Use
Email: user.Email,
},
},
ContentBase64: base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("This is new text for %s", path))),
ContentBase64: base64.StdEncoding.EncodeToString(fmt.Appendf(nil, "This is new text for %s", path)),
}, callback...)
}

View file

@ -185,10 +185,10 @@ func TestSignupImageCaptcha(t *testing.T) {
assert.True(t, ok)
assert.Len(t, digits, 6)
digitStr := ""
var digitStr strings.Builder
// Convert digits to ASCII digits.
for _, digit := range digits {
digitStr += string(digit + '0')
digitStr.WriteString(string(digit + '0'))
}
req = NewRequestWithValues(t, "POST", "/user/sign_up", map[string]string{
@ -197,7 +197,7 @@ func TestSignupImageCaptcha(t *testing.T) {
"password": "examplePassword!1",
"retype": "examplePassword!1",
"img-captcha-id": idCaptcha,
"img-captcha-response": digitStr,
"img-captcha-response": digitStr.String(),
})
MakeRequest(t, req, http.StatusSeeOther)

View file

@ -28,7 +28,7 @@ func doCheckRepositoryEmptyStatus(ctx APITestContext, isEmpty bool) func(*testin
func doAddChangesToCheckout(dstPath, filename string) func(*testing.T) {
return func(t *testing.T) {
require.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0o644))
require.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), fmt.Appendf(nil, "# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now()), 0o644))
require.NoError(t, git.AddChanges(dstPath, true))
signature := git.Signature{
Email: "test@example.com",

View file

@ -1030,7 +1030,7 @@ func TestUserRepos(t *testing.T) {
sel := htmlDoc.doc.Find("a.name")
assert.Len(t, repos, len(sel.Nodes))
for i := 0; i < len(repos); i++ {
for i := range repos {
assert.Equal(t, repos[i], strings.TrimSpace(sel.Eq(i).Text()))
}
}

View file

@ -15,6 +15,7 @@ import (
"path"
"path/filepath"
"runtime"
"slices"
"strings"
"sync/atomic"
"testing"
@ -524,23 +525,20 @@ func CreateDeclarativeRepo(t *testing.T, owner *user_model.User, name string, en
if enabledUnits != nil {
opts.EnabledUnits = optional.Some(enabledUnits)
for _, unitType := range enabledUnits {
if unitType == unit_model.TypePullRequests {
opts.UnitConfig = optional.Some(map[unit_model.Type]convert.Conversion{
unit_model.TypePullRequests: &repo_model.PullRequestsConfig{
AllowMerge: true,
AllowRebase: true,
AllowRebaseMerge: true,
AllowSquash: true,
AllowFastForwardOnly: true,
AllowManualMerge: true,
AllowRebaseUpdate: true,
DefaultMergeStyle: repo_model.MergeStyleMerge,
DefaultUpdateStyle: repo_model.UpdateStyleMerge,
},
})
break
}
if slices.Contains(enabledUnits, unit_model.TypePullRequests) {
opts.UnitConfig = optional.Some(map[unit_model.Type]convert.Conversion{
unit_model.TypePullRequests: &repo_model.PullRequestsConfig{
AllowMerge: true,
AllowRebase: true,
AllowRebaseMerge: true,
AllowSquash: true,
AllowFastForwardOnly: true,
AllowManualMerge: true,
AllowRebaseUpdate: true,
DefaultMergeStyle: repo_model.MergeStyleMerge,
DefaultUpdateStyle: repo_model.UpdateStyleMerge,
},
})
}
}
if disabledUnits != nil {