Refactor some tests (#34580)

1. use `test.MockVariableValue` as much as possible
2. avoid `time.Sleep` as much as possible
This commit is contained in:
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" "testing"
"code.gitea.io/gitea/models/auth" "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/services/auth/source/ldap" "code.gitea.io/gitea/services/auth/source/ldap"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -16,9 +17,7 @@ import (
func TestAddLdapBindDn(t *testing.T) { func TestAddLdapBindDn(t *testing.T) {
// Mock cli functions to do not exit on error // Mock cli functions to do not exit on error
osExiter := cli.OsExiter defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases // Test cases
cases := []struct { cases := []struct {
@ -256,9 +255,7 @@ func TestAddLdapBindDn(t *testing.T) {
func TestAddLdapSimpleAuth(t *testing.T) { func TestAddLdapSimpleAuth(t *testing.T) {
// Mock cli functions to do not exit on error // Mock cli functions to do not exit on error
osExiter := cli.OsExiter defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases // Test cases
cases := []struct { cases := []struct {
@ -487,9 +484,7 @@ func TestAddLdapSimpleAuth(t *testing.T) {
func TestUpdateLdapBindDn(t *testing.T) { func TestUpdateLdapBindDn(t *testing.T) {
// Mock cli functions to do not exit on error // Mock cli functions to do not exit on error
osExiter := cli.OsExiter defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases // Test cases
cases := []struct { cases := []struct {
@ -964,9 +959,7 @@ func TestUpdateLdapBindDn(t *testing.T) {
func TestUpdateLdapSimpleAuth(t *testing.T) { func TestUpdateLdapSimpleAuth(t *testing.T) {
// Mock cli functions to do not exit on error // Mock cli functions to do not exit on error
osExiter := cli.OsExiter defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
defer func() { cli.OsExiter = osExiter }()
cli.OsExiter = func(code int) {}
// Test cases // Test cases
cases := []struct { cases := []struct {

View File

@ -23,12 +23,6 @@ func NoHTTPRedirector() {
graceful.GetManager().InformCleanup() 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 // NoInstallListener tells our cleanup routine that we will not be using a possibly provided listener
// for our install HTTP/HTTPS service // for our install HTTP/HTTPS service
func NoInstallListener() { func NoInstallListener() {

View File

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

View File

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

View File

@ -513,11 +513,8 @@ func TestIsUserVisibleToViewer(t *testing.T) {
} }
func Test_ValidateUser(t *testing.T) { func Test_ValidateUser(t *testing.T) {
oldSetting := setting.Service.AllowedUserVisibilityModesSlice defer test.MockVariableValue(&setting.Service.AllowedUserVisibilityModesSlice, []bool{true, false, true})()
defer func() {
setting.Service.AllowedUserVisibilityModesSlice = oldSetting
}()
setting.Service.AllowedUserVisibilityModesSlice = []bool{true, false, true}
kases := map[*user_model.User]bool{ kases := map[*user_model.User]bool{
{ID: 1, Visibility: structs.VisibleTypePublic}: true, {ID: 1, Visibility: structs.VisibleTypePublic}: true,
{ID: 2, Visibility: structs.VisibleTypeLimited}: false, {ID: 2, Visibility: structs.VisibleTypeLimited}: false,
@ -586,12 +583,7 @@ func TestDisabledUserFeatures(t *testing.T) {
testValues := container.SetOf(setting.UserFeatureDeletion, testValues := container.SetOf(setting.UserFeatureDeletion,
setting.UserFeatureManageSSHKeys, setting.UserFeatureManageSSHKeys,
setting.UserFeatureManageGPGKeys) setting.UserFeatureManageGPGKeys)
defer test.MockVariableValue(&setting.Admin.ExternalUserDisableFeatures, testValues)()
oldSetting := setting.Admin.ExternalUserDisableFeatures
defer func() {
setting.Admin.ExternalUserDisableFeatures = oldSetting
}()
setting.Admin.ExternalUserDisableFeatures = testValues
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) 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) { func TestTimedDiscoveryCache(t *testing.T) {
dc := newTimedDiscoveryCache(1 * time.Second) ttl := 50 * time.Millisecond
dc := newTimedDiscoveryCache(ttl)
// Put some initial values // Put some initial values
dc.Put("foo", &testDiscoveredInfo{}) // openid.opEndpoint: "a", openid.opLocalID: "b", openid.claimedID: "c"}) 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 // Attempt to get a non-existent value
assert.Nil(t, dc.Get("bar")) assert.Nil(t, dc.Get("bar"))
// Sleep one second and try retrieve again // Sleep for a while and try to retrieve again
time.Sleep(1 * time.Second) time.Sleep(ttl * 3 / 2)
assert.Nil(t, dc.Get("foo")) assert.Nil(t, dc.Get("foo"))
} }

View File

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

View File

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

View File

@ -7,6 +7,7 @@ import (
"testing" "testing"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -47,7 +48,7 @@ func Test_IsValidURL(t *testing.T) {
} }
func Test_IsValidExternalURL(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 { cases := []struct {
description string description string
@ -89,7 +90,7 @@ func Test_IsValidExternalURL(t *testing.T) {
} }
func Test_IsValidExternalTrackerURLFormat(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 { cases := []struct {
description string description string

View File

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

View File

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

View File

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

View File

@ -13,6 +13,7 @@ import (
webhook_model "code.gitea.io/gitea/models/webhook" webhook_model "code.gitea.io/gitea/models/webhook"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs" api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
webhook_module "code.gitea.io/gitea/modules/webhook" webhook_module "code.gitea.io/gitea/modules/webhook"
"code.gitea.io/gitea/services/convert" "code.gitea.io/gitea/services/convert"
@ -84,7 +85,8 @@ func TestPrepareWebhooksBranchFilterNoMatch(t *testing.T) {
func TestWebhookUserMail(t *testing.T) { func TestWebhookUserMail(t *testing.T) {
require.NoError(t, unittest.PrepareTestDatabase()) 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}) 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.GetPlaceholderEmail(), convert.ToUser(db.DefaultContext, user, nil).Email)
assert.Equal(t, user.Email, convert.ToUser(db.DefaultContext, user, user).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 { type mockTaskOutcome struct {
result runnerv1.Result result runnerv1.Result
outputs map[string]string outputs map[string]string
logRows []*runnerv1.LogRow logRows []*runnerv1.LogRow
execTime time.Duration
} }
func (r *mockRunner) execTask(t *testing.T, task *runnerv1.Task, outcome *mockTaskOutcome) { 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) sentOutputKeys = append(sentOutputKeys, outputKey)
assert.ElementsMatch(t, sentOutputKeys, resp.Msg.SentOutputs) assert.ElementsMatch(t, sentOutputKeys, resp.Msg.SentOutputs)
} }
time.Sleep(outcome.execTime)
resp, err := r.client.runnerServiceClient.UpdateTask(t.Context(), connect.NewRequest(&runnerv1.UpdateTaskRequest{ resp, err := r.client.runnerServiceClient.UpdateTask(t.Context(), connect.NewRequest(&runnerv1.UpdateTaskRequest{
State: &runnerv1.TaskState{ State: &runnerv1.TaskState{
Id: task.Id, Id: task.Id,

View File

@ -87,7 +87,7 @@ func TestPackageGo(t *testing.T) {
AddBasicAuth(user.Name) AddBasicAuth(user.Name)
MakeRequest(t, req, http.StatusConflict) 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{ content = createArchive(map[string][]byte{
packageName + "@" + packageVersion2 + "/go.mod": []byte(goModContent), packageName + "@" + packageVersion2 + "/go.mod": []byte(goModContent),

View File

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

View File

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

View File

@ -7,7 +7,6 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"testing" "testing"
"time"
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
@ -68,9 +67,6 @@ func TestViewReleases(t *testing.T) {
session := loginUser(t, "user2") session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user2/repo1/releases") req := NewRequest(t, "GET", "/user2/repo1/releases")
session.MakeRequest(t, req, http.StatusOK) 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) { func TestViewReleasesNoLogin(t *testing.T) {

View File

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

View File

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

View File

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

View File

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

View File

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