From 2a1585b32ea2c3cb961cd1aedf4117d880255a53 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Tue, 3 Jun 2025 09:26:19 +0800 Subject: [PATCH] Refactor some tests (#34580) 1. use `test.MockVariableValue` as much as possible 2. avoid `time.Sleep` as much as possible --- cmd/admin_auth_ldap_test.go | 17 +++------- cmd/web_graceful.go | 6 ---- models/fixtures/hook_task.yml | 2 +- models/repo/pushmirror_test.go | 2 -- models/user/user_test.go | 14 ++------- modules/auth/openid/discovery_cache_test.go | 7 +++-- .../indexer/issues/internal/tests/tests.go | 31 ++++++------------- modules/setting/git_test.go | 10 +++--- modules/validation/helpers_test.go | 5 +-- routers/web/repo/setting/settings_test.go | 24 ++------------ services/forms/user_form_test.go | 23 +++----------- services/repository/fork_test.go | 3 +- services/webhook/webhook_test.go | 4 ++- tests/integration/actions_runner_test.go | 8 ++--- .../integration/api_packages_goproxy_test.go | 2 +- tests/integration/api_repo_lfs_test.go | 7 ++--- tests/integration/pull_merge_test.go | 4 --- tests/integration/release_test.go | 4 --- tests/integration/repo_webhook_test.go | 7 ++--- tests/integration/setting_test.go | 6 ++-- tests/integration/signup_test.go | 11 +++---- tests/integration/user_test.go | 2 +- tests/integration/webfinger_test.go | 7 ++--- 23 files changed, 58 insertions(+), 148 deletions(-) diff --git a/cmd/admin_auth_ldap_test.go b/cmd/admin_auth_ldap_test.go index ea9a83ef76..52ab78fe13 100644 --- a/cmd/admin_auth_ldap_test.go +++ b/cmd/admin_auth_ldap_test.go @@ -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 { diff --git a/cmd/web_graceful.go b/cmd/web_graceful.go index 996537be3b..5e06d2c216 100644 --- a/cmd/web_graceful.go +++ b/cmd/web_graceful.go @@ -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() { diff --git a/models/fixtures/hook_task.yml b/models/fixtures/hook_task.yml index d573406b36..6023719b1e 100644 --- a/models/fixtures/hook_task.yml +++ b/models/fixtures/hook_task.yml @@ -18,7 +18,7 @@ id: 2 hook_id: 1 uuid: uuid2 - is_delivered: false + is_delivered: true - id: 3 diff --git a/models/repo/pushmirror_test.go b/models/repo/pushmirror_test.go index e19749d93a..9fb7471147 100644 --- a/models/repo/pushmirror_test.go +++ b/models/repo/pushmirror_test.go @@ -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) diff --git a/models/user/user_test.go b/models/user/user_test.go index 26192f8d55..15412f94c5 100644 --- a/models/user/user_test.go +++ b/models/user/user_test.go @@ -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}) diff --git a/modules/auth/openid/discovery_cache_test.go b/modules/auth/openid/discovery_cache_test.go index 7d4b27c5df..f3d7dd226e 100644 --- a/modules/auth/openid/discovery_cache_test.go +++ b/modules/auth/openid/discovery_cache_test.go @@ -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")) } diff --git a/modules/indexer/issues/internal/tests/tests.go b/modules/indexer/issues/internal/tests/tests.go index a42ec9a2bc..7aebbbcd58 100644 --- a/modules/indexer/issues/internal/tests/tests.go +++ b/modules/indexer/issues/internal/tests/tests.go @@ -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) } diff --git a/modules/setting/git_test.go b/modules/setting/git_test.go index 818bcf9df6..0d7f634abf 100644 --- a/modules/setting/git_test.go +++ b/modules/setting/git_test.go @@ -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(``) diff --git a/modules/validation/helpers_test.go b/modules/validation/helpers_test.go index 52f383f698..6a982965f6 100644 --- a/modules/validation/helpers_test.go +++ b/modules/validation/helpers_test.go @@ -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 diff --git a/routers/web/repo/setting/settings_test.go b/routers/web/repo/setting/settings_test.go index ba6b0d1efc..15ebea888c 100644 --- a/routers/web/repo/setting/settings_test.go +++ b/routers/web/repo/setting/settings_test.go @@ -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) diff --git a/services/forms/user_form_test.go b/services/forms/user_form_test.go index b4120f20ed..09e9ec0f65 100644 --- a/services/forms/user_form_test.go +++ b/services/forms/user_form_test.go @@ -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 diff --git a/services/repository/fork_test.go b/services/repository/fork_test.go index 9edc0aa39f..35c6effca5 100644 --- a/services/repository/fork_test.go +++ b/services/repository/fork_test.go @@ -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{ diff --git a/services/webhook/webhook_test.go b/services/webhook/webhook_test.go index 6bac02712b..5a805347e3 100644 --- a/services/webhook/webhook_test.go +++ b/services/webhook/webhook_test.go @@ -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) diff --git a/tests/integration/actions_runner_test.go b/tests/integration/actions_runner_test.go index 75402929a1..6cc5a10e0f 100644 --- a/tests/integration/actions_runner_test.go +++ b/tests/integration/actions_runner_test.go @@ -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, diff --git a/tests/integration/api_packages_goproxy_test.go b/tests/integration/api_packages_goproxy_test.go index dab9fefc5e..fa0ee5b901 100644 --- a/tests/integration/api_packages_goproxy_test.go +++ b/tests/integration/api_packages_goproxy_test.go @@ -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), diff --git a/tests/integration/api_repo_lfs_test.go b/tests/integration/api_repo_lfs_test.go index 6b42b83bc5..ec6a3a3b57 100644 --- a/tests/integration/api_repo_lfs_test.go +++ b/tests/integration/api_repo_lfs_test.go @@ -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) { diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index cf50d5e639..bf7ca3e42e 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -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) diff --git a/tests/integration/release_test.go b/tests/integration/release_test.go index 125f0810a7..05b90c4c68 100644 --- a/tests/integration/release_test.go +++ b/tests/integration/release_test.go @@ -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) { diff --git a/tests/integration/repo_webhook_test.go b/tests/integration/repo_webhook_test.go index 438dd3211d..57162de363 100644 --- a/tests/integration/repo_webhook_test.go +++ b/tests/integration/repo_webhook_test.go @@ -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) diff --git a/tests/integration/setting_test.go b/tests/integration/setting_test.go index 9dad9ca716..64fd28c5e9 100644 --- a/tests/integration/setting_test.go +++ b/tests/integration/setting_test.go @@ -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 } diff --git a/tests/integration/signup_test.go b/tests/integration/signup_test.go index e86851352e..c08f57d33e 100644 --- a/tests/integration/signup_test.go +++ b/tests/integration/signup_test.go @@ -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 diff --git a/tests/integration/user_test.go b/tests/integration/user_test.go index 2c9a916ec2..34692d9cab 100644 --- a/tests/integration/user_test.go +++ b/tests/integration/user_test.go @@ -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{ diff --git a/tests/integration/webfinger_test.go b/tests/integration/webfinger_test.go index 2afaed4a45..757d442cd2 100644 --- a/tests/integration/webfinger_test.go +++ b/tests/integration/webfinger_test.go @@ -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})