Refactor some tests (#34580)

1. use `test.MockVariableValue` as much as possible
2. avoid `time.Sleep` as much as possible
pull/34588/head^2
wxiaoguang 2025-06-03 09:26:19 +08:00 committed by GitHub
parent c5e78fc7ad
commit 2a1585b32e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
23 changed files with 58 additions and 148 deletions

View File

@ -8,6 +8,7 @@ import (
"testing"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/services/auth/source/ldap"
"github.com/stretchr/testify/assert"
@ -16,9 +17,7 @@ import (
func TestAddLdapBindDn(t *testing.T) {
// Mock cli functions to do not exit on error
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
// Test cases
cases := []struct {
@ -256,9 +255,7 @@ func TestAddLdapBindDn(t *testing.T) {
func TestAddLdapSimpleAuth(t *testing.T) {
// Mock cli functions to do not exit on error
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
// Test cases
cases := []struct {
@ -487,9 +484,7 @@ func TestAddLdapSimpleAuth(t *testing.T) {
func TestUpdateLdapBindDn(t *testing.T) {
// Mock cli functions to do not exit on error
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
// Test cases
cases := []struct {
@ -964,9 +959,7 @@ func TestUpdateLdapBindDn(t *testing.T) {
func TestUpdateLdapSimpleAuth(t *testing.T) {
// Mock cli functions to do not exit on error
osExiter := cli.OsExiter
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
// Test cases
cases := []struct {

View File

@ -23,12 +23,6 @@ func NoHTTPRedirector() {
graceful.GetManager().InformCleanup()
}
// NoMainListener tells our cleanup routine that we will not be using a possibly provided listener
// for our main HTTP/HTTPS service
func NoMainListener() {
graceful.GetManager().InformCleanup()
}
// NoInstallListener tells our cleanup routine that we will not be using a possibly provided listener
// for our install HTTP/HTTPS service
func NoInstallListener() {

View File

@ -18,7 +18,7 @@
id: 2
hook_id: 1
uuid: uuid2
is_delivered: false
is_delivered: true
-
id: 3

View File

@ -39,8 +39,6 @@ func TestPushMirrorsIterate(t *testing.T) {
Interval: 0,
})
time.Sleep(1 * time.Millisecond)
repo_model.PushMirrorsIterate(db.DefaultContext, 1, func(idx int, bean any) error {
m, ok := bean.(*repo_model.PushMirror)
assert.True(t, ok)

View File

@ -513,11 +513,8 @@ func TestIsUserVisibleToViewer(t *testing.T) {
}
func Test_ValidateUser(t *testing.T) {
oldSetting := setting.Service.AllowedUserVisibilityModesSlice
defer func() {
setting.Service.AllowedUserVisibilityModesSlice = oldSetting
}()
setting.Service.AllowedUserVisibilityModesSlice = []bool{true, false, true}
defer test.MockVariableValue(&setting.Service.AllowedUserVisibilityModesSlice, []bool{true, false, true})()
kases := map[*user_model.User]bool{
{ID: 1, Visibility: structs.VisibleTypePublic}: true,
{ID: 2, Visibility: structs.VisibleTypeLimited}: false,
@ -586,12 +583,7 @@ func TestDisabledUserFeatures(t *testing.T) {
testValues := container.SetOf(setting.UserFeatureDeletion,
setting.UserFeatureManageSSHKeys,
setting.UserFeatureManageGPGKeys)
oldSetting := setting.Admin.ExternalUserDisableFeatures
defer func() {
setting.Admin.ExternalUserDisableFeatures = oldSetting
}()
setting.Admin.ExternalUserDisableFeatures = testValues
defer test.MockVariableValue(&setting.Admin.ExternalUserDisableFeatures, testValues)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})

View File

@ -26,7 +26,8 @@ func (s *testDiscoveredInfo) OpLocalID() string {
}
func TestTimedDiscoveryCache(t *testing.T) {
dc := newTimedDiscoveryCache(1 * time.Second)
ttl := 50 * time.Millisecond
dc := newTimedDiscoveryCache(ttl)
// Put some initial values
dc.Put("foo", &testDiscoveredInfo{}) // openid.opEndpoint: "a", openid.opLocalID: "b", openid.claimedID: "c"})
@ -41,8 +42,8 @@ func TestTimedDiscoveryCache(t *testing.T) {
// Attempt to get a non-existent value
assert.Nil(t, dc.Get("bar"))
// Sleep one second and try retrieve again
time.Sleep(1 * time.Second)
// Sleep for a while and try to retrieve again
time.Sleep(ttl * 3 / 2)
assert.Nil(t, dc.Get("foo"))
}

View File

@ -8,7 +8,6 @@
package tests
import (
"context"
"fmt"
"slices"
"testing"
@ -40,7 +39,7 @@ func TestIndexer(t *testing.T, indexer internal.Indexer) {
data[v.ID] = v
}
require.NoError(t, indexer.Index(t.Context(), d...))
require.NoError(t, waitData(indexer, int64(len(data))))
waitData(t, indexer, int64(len(data)))
}
defer func() {
@ -54,13 +53,13 @@ func TestIndexer(t *testing.T, indexer internal.Indexer) {
for _, v := range c.ExtraData {
data[v.ID] = v
}
require.NoError(t, waitData(indexer, int64(len(data))))
waitData(t, indexer, int64(len(data)))
defer func() {
for _, v := range c.ExtraData {
require.NoError(t, indexer.Delete(t.Context(), v.ID))
delete(data, v.ID)
}
require.NoError(t, waitData(indexer, int64(len(data))))
waitData(t, indexer, int64(len(data)))
}()
}
@ -751,22 +750,10 @@ func countIndexerData(data map[int64]*internal.IndexerData, f func(v *internal.I
// waitData waits for the indexer to index all data.
// Some engines like Elasticsearch index data asynchronously, so we need to wait for a while.
func waitData(indexer internal.Indexer, total int64) error {
var actual int64
for i := 0; i < 100; i++ {
result, err := indexer.Search(context.Background(), &internal.SearchOptions{
Paginator: &db.ListOptions{
PageSize: 0,
},
})
if err != nil {
return err
}
actual = result.Total
if actual == total {
return nil
}
time.Sleep(100 * time.Millisecond)
}
return fmt.Errorf("waitData: expected %d, actual %d", total, actual)
func waitData(t *testing.T, indexer internal.Indexer, total int64) {
assert.Eventually(t, func() bool {
result, err := indexer.Search(t.Context(), &internal.SearchOptions{Paginator: &db.ListOptions{}})
require.NoError(t, err)
return result.Total == total
}, 10*time.Second, 100*time.Millisecond, "expected total=%d", total)
}

View File

@ -6,6 +6,8 @@ package setting
import (
"testing"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert"
)
@ -36,12 +38,8 @@ diff.algorithm = other
}
func TestGitReflog(t *testing.T) {
oldGit := Git
oldGitConfig := GitConfig
defer func() {
Git = oldGit
GitConfig = oldGitConfig
}()
defer test.MockVariableValue(&Git)
defer test.MockVariableValue(&GitConfig)
// default reflog config without legacy options
cfg, err := NewConfigProviderFromData(``)

View File

@ -7,6 +7,7 @@ import (
"testing"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert"
)
@ -47,7 +48,7 @@ func Test_IsValidURL(t *testing.T) {
}
func Test_IsValidExternalURL(t *testing.T) {
setting.AppURL = "https://try.gitea.io/"
defer test.MockVariableValue(&setting.AppURL, "https://try.gitea.io/")()
cases := []struct {
description string
@ -89,7 +90,7 @@ func Test_IsValidExternalURL(t *testing.T) {
}
func Test_IsValidExternalTrackerURLFormat(t *testing.T) {
setting.AppURL = "https://try.gitea.io/"
defer test.MockVariableValue(&setting.AppURL, "https://try.gitea.io/")()
cases := []struct {
description string

View File

@ -15,6 +15,7 @@ import (
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/services/context"
"code.gitea.io/gitea/services/contexttest"
@ -24,23 +25,8 @@ import (
"github.com/stretchr/testify/assert"
)
func createSSHAuthorizedKeysTmpPath(t *testing.T) func() {
tmpDir := t.TempDir()
oldPath := setting.SSH.RootPath
setting.SSH.RootPath = tmpDir
return func() {
setting.SSH.RootPath = oldPath
}
}
func TestAddReadOnlyDeployKey(t *testing.T) {
if deferable := createSSHAuthorizedKeysTmpPath(t); deferable != nil {
defer deferable()
} else {
return
}
defer test.MockVariableValue(&setting.SSH.RootPath, t.TempDir())()
unittest.PrepareTestEnv(t)
ctx, _ := contexttest.MockContext(t, "user2/repo1/settings/keys")
@ -64,11 +50,7 @@ func TestAddReadOnlyDeployKey(t *testing.T) {
}
func TestAddReadWriteOnlyDeployKey(t *testing.T) {
if deferable := createSSHAuthorizedKeysTmpPath(t); deferable != nil {
defer deferable()
} else {
return
}
defer test.MockVariableValue(&setting.SSH.RootPath, t.TempDir())()
unittest.PrepareTestEnv(t)

View File

@ -7,6 +7,7 @@ import (
"testing"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"github.com/gobwas/glob"
"github.com/stretchr/testify/assert"
@ -26,12 +27,7 @@ func TestRegisterForm_IsDomainAllowed_Empty(t *testing.T) {
}
func TestRegisterForm_IsDomainAllowed_InvalidEmail(t *testing.T) {
oldService := setting.Service
defer func() {
setting.Service = oldService
}()
setting.Service.EmailDomainAllowList = []glob.Glob{glob.MustCompile("gitea.io")}
defer test.MockVariableValue(&setting.Service.EmailDomainAllowList, []glob.Glob{glob.MustCompile("gitea.io")})()
tt := []struct {
email string
@ -48,12 +44,7 @@ func TestRegisterForm_IsDomainAllowed_InvalidEmail(t *testing.T) {
}
func TestRegisterForm_IsDomainAllowed_AllowedEmail(t *testing.T) {
oldService := setting.Service
defer func() {
setting.Service = oldService
}()
setting.Service.EmailDomainAllowList = []glob.Glob{glob.MustCompile("gitea.io"), glob.MustCompile("*.allow")}
defer test.MockVariableValue(&setting.Service.EmailDomainAllowList, []glob.Glob{glob.MustCompile("gitea.io"), glob.MustCompile("*.allow")})()
tt := []struct {
email string
@ -76,13 +67,7 @@ func TestRegisterForm_IsDomainAllowed_AllowedEmail(t *testing.T) {
}
func TestRegisterForm_IsDomainAllowed_BlockedEmail(t *testing.T) {
oldService := setting.Service
defer func() {
setting.Service = oldService
}()
setting.Service.EmailDomainAllowList = nil
setting.Service.EmailDomainBlockList = []glob.Glob{glob.MustCompile("gitea.io"), glob.MustCompile("*.block")}
defer test.MockVariableValue(&setting.Service.EmailDomainBlockList, []glob.Glob{glob.MustCompile("gitea.io"), glob.MustCompile("*.block")})()
tt := []struct {
email string

View File

@ -13,6 +13,7 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert"
@ -38,7 +39,7 @@ func TestForkRepository(t *testing.T) {
assert.False(t, repo_model.IsErrReachLimitOfRepo(err))
// change AllowForkWithoutMaximumLimit to false for the test
setting.Repository.AllowForkWithoutMaximumLimit = false
defer test.MockVariableValue(&setting.Repository.AllowForkWithoutMaximumLimit, false)()
// user has reached maximum limit of repositories
user.MaxRepoCreation = 0
fork2, err := ForkRepository(git.DefaultContext, user, user, ForkRepoOptions{

View File

@ -13,6 +13,7 @@ import (
webhook_model "code.gitea.io/gitea/models/webhook"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
webhook_module "code.gitea.io/gitea/modules/webhook"
"code.gitea.io/gitea/services/convert"
@ -84,7 +85,8 @@ func TestPrepareWebhooksBranchFilterNoMatch(t *testing.T) {
func TestWebhookUserMail(t *testing.T) {
require.NoError(t, unittest.PrepareTestDatabase())
setting.Service.NoReplyAddress = "no-reply.com"
defer test.MockVariableValue(&setting.Service.NoReplyAddress, "no-reply.com")()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
assert.Equal(t, user.GetPlaceholderEmail(), convert.ToUser(db.DefaultContext, user, nil).Email)
assert.Equal(t, user.Email, convert.ToUser(db.DefaultContext, user, user).Email)

View File

@ -115,10 +115,9 @@ func (r *mockRunner) fetchTask(t *testing.T, timeout ...time.Duration) *runnerv1
}
type mockTaskOutcome struct {
result runnerv1.Result
outputs map[string]string
logRows []*runnerv1.LogRow
execTime time.Duration
result runnerv1.Result
outputs map[string]string
logRows []*runnerv1.LogRow
}
func (r *mockRunner) execTask(t *testing.T, task *runnerv1.Task, outcome *mockTaskOutcome) {
@ -145,7 +144,6 @@ func (r *mockRunner) execTask(t *testing.T, task *runnerv1.Task, outcome *mockTa
sentOutputKeys = append(sentOutputKeys, outputKey)
assert.ElementsMatch(t, sentOutputKeys, resp.Msg.SentOutputs)
}
time.Sleep(outcome.execTime)
resp, err := r.client.runnerServiceClient.UpdateTask(t.Context(), connect.NewRequest(&runnerv1.UpdateTaskRequest{
State: &runnerv1.TaskState{
Id: task.Id,

View File

@ -87,7 +87,7 @@ func TestPackageGo(t *testing.T) {
AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusConflict)
time.Sleep(time.Second)
time.Sleep(time.Second) // Ensure the timestamp is different, then the "list" below can have stable order
content = createArchive(map[string][]byte{
packageName + "@" + packageVersion2 + "/go.mod": []byte(goModContent),

View File

@ -20,6 +20,7 @@ import (
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
@ -226,9 +227,7 @@ func TestAPILFSBatch(t *testing.T) {
t.Run("FileTooBig", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
oldMaxFileSize := setting.LFS.MaxFileSize
setting.LFS.MaxFileSize = 2
defer test.MockVariableValue(&setting.LFS.MaxFileSize, 2)()
req := newRequest(t, &lfs.BatchRequest{
Operation: "upload",
@ -243,8 +242,6 @@ func TestAPILFSBatch(t *testing.T) {
assert.NotNil(t, br.Objects[0].Error)
assert.Equal(t, http.StatusUnprocessableEntity, br.Objects[0].Error.Code)
assert.Equal(t, "Size must be less than or equal to 2", br.Objects[0].Error.Message)
setting.LFS.MaxFileSize = oldMaxFileSize
})
t.Run("AddMeta", func(t *testing.T) {

View File

@ -983,8 +983,6 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing.
})
assert.NoError(t, err)
time.Sleep(2 * time.Second)
// reload pr again
pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID})
assert.False(t, pr.HasMerged)
@ -997,8 +995,6 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing.
htmlDoc := NewHTMLParser(t, resp.Body)
testSubmitReview(t, approveSession, htmlDoc.GetCSRF(), "user2", "repo1", strconv.Itoa(int(pr.Index)), sha, "approve", http.StatusOK)
time.Sleep(2 * time.Second)
// realod pr again
pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID})
assert.True(t, pr.HasMerged)

View File

@ -7,7 +7,6 @@ import (
"fmt"
"net/http"
"testing"
"time"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
@ -68,9 +67,6 @@ func TestViewReleases(t *testing.T) {
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user2/repo1/releases")
session.MakeRequest(t, req, http.StatusOK)
// if CI is to slow this test fail, so lets wait a bit
time.Sleep(time.Millisecond * 100)
}
func TestViewReleasesNoLogin(t *testing.T) {

View File

@ -11,7 +11,6 @@ import (
"net/url"
"strings"
"testing"
"time"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/repo"
@ -889,8 +888,7 @@ jobs:
// 4. Execute a single Job
task := runner.fetchTask(t)
outcome := &mockTaskOutcome{
result: runnerv1.Result_RESULT_SUCCESS,
execTime: time.Millisecond,
result: runnerv1.Result_RESULT_SUCCESS,
}
runner.execTask(t, task, outcome)
@ -926,8 +924,7 @@ jobs:
// 6. Execute a single Job
task = runner.fetchTask(t)
outcome = &mockTaskOutcome{
result: runnerv1.Result_RESULT_FAILURE,
execTime: time.Millisecond,
result: runnerv1.Result_RESULT_FAILURE,
}
runner.execTask(t, task, outcome)

View File

@ -8,6 +8,7 @@ import (
"testing"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
@ -92,8 +93,7 @@ func TestSettingShowUserEmailProfile(t *testing.T) {
func TestSettingLandingPage(t *testing.T) {
defer tests.PrepareTestEnv(t)()
landingPage := setting.LandingPageURL
defer test.MockVariableValue(&setting.LandingPageURL)()
setting.LandingPageURL = setting.LandingPageHome
req := NewRequest(t, "GET", "/")
@ -113,6 +113,4 @@ func TestSettingLandingPage(t *testing.T) {
req = NewRequest(t, "GET", "/")
resp = MakeRequest(t, req, http.StatusSeeOther)
assert.Equal(t, "/user/login", resp.Header().Get("Location"))
setting.LandingPageURL = landingPage
}

View File

@ -22,8 +22,7 @@ import (
func TestSignup(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.Service.EnableCaptcha = false
defer test.MockVariableValue(&setting.Service.EnableCaptcha, false)()
req := NewRequestWithValues(t, "POST", "/user/sign_up", map[string]string{
"user_name": "exampleUser",
@ -40,9 +39,8 @@ func TestSignup(t *testing.T) {
func TestSignupAsRestricted(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.Service.EnableCaptcha = false
setting.Service.DefaultUserIsRestricted = true
defer test.MockVariableValue(&setting.Service.EnableCaptcha, false)()
defer test.MockVariableValue(&setting.Service.DefaultUserIsRestricted, true)()
req := NewRequestWithValues(t, "POST", "/user/sign_up", map[string]string{
"user_name": "restrictedUser",
@ -62,8 +60,7 @@ func TestSignupAsRestricted(t *testing.T) {
func TestSignupEmailValidation(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.Service.EnableCaptcha = false
defer test.MockVariableValue(&setting.Service.EnableCaptcha, false)()
tests := []struct {
email string

View File

@ -257,8 +257,8 @@ func TestListStopWatches(t *testing.T) {
}
func TestUserLocationMapLink(t *testing.T) {
setting.Service.UserLocationMapURL = "https://example/foo/"
defer tests.PrepareTestEnv(t)()
defer test.MockVariableValue(&setting.Service.UserLocationMapURL, "https://example/foo/")()
session := loginUser(t, "user2")
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{

View File

@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
@ -20,11 +21,7 @@ import (
func TestWebfinger(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.Federation.Enabled = true
defer func() {
setting.Federation.Enabled = false
}()
defer test.MockVariableValue(&setting.Federation.Enabled, true)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})