Skip to content

Commit d897f27

Browse files
committed
fix
1 parent 82ea238 commit d897f27

File tree

23 files changed

+57
-149
lines changed

23 files changed

+57
-149
lines changed

cmd/admin_auth_ldap_test.go

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"testing"
99

1010
"code.gitea.io/gitea/models/auth"
11+
"code.gitea.io/gitea/modules/test"
1112
"code.gitea.io/gitea/services/auth/source/ldap"
1213

1314
"github.com/stretchr/testify/assert"
@@ -16,9 +17,7 @@ import (
1617

1718
func TestAddLdapBindDn(t *testing.T) {
1819
// Mock cli functions to do not exit on error
19-
osExiter := cli.OsExiter
20-
defer func() { cli.OsExiter = osExiter }()
21-
cli.OsExiter = func(code int) {}
20+
defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
2221

2322
// Test cases
2423
cases := []struct {
@@ -256,9 +255,7 @@ func TestAddLdapBindDn(t *testing.T) {
256255

257256
func TestAddLdapSimpleAuth(t *testing.T) {
258257
// Mock cli functions to do not exit on error
259-
osExiter := cli.OsExiter
260-
defer func() { cli.OsExiter = osExiter }()
261-
cli.OsExiter = func(code int) {}
258+
defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
262259

263260
// Test cases
264261
cases := []struct {
@@ -487,9 +484,7 @@ func TestAddLdapSimpleAuth(t *testing.T) {
487484

488485
func TestUpdateLdapBindDn(t *testing.T) {
489486
// Mock cli functions to do not exit on error
490-
osExiter := cli.OsExiter
491-
defer func() { cli.OsExiter = osExiter }()
492-
cli.OsExiter = func(code int) {}
487+
defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
493488

494489
// Test cases
495490
cases := []struct {
@@ -964,9 +959,7 @@ func TestUpdateLdapBindDn(t *testing.T) {
964959

965960
func TestUpdateLdapSimpleAuth(t *testing.T) {
966961
// Mock cli functions to do not exit on error
967-
osExiter := cli.OsExiter
968-
defer func() { cli.OsExiter = osExiter }()
969-
cli.OsExiter = func(code int) {}
962+
defer test.MockVariableValue(&cli.OsExiter, func(code int) {})()
970963

971964
// Test cases
972965
cases := []struct {

cmd/web_graceful.go

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -23,12 +23,6 @@ func NoHTTPRedirector() {
2323
graceful.GetManager().InformCleanup()
2424
}
2525

26-
// NoMainListener tells our cleanup routine that we will not be using a possibly provided listener
27-
// for our main HTTP/HTTPS service
28-
func NoMainListener() {
29-
graceful.GetManager().InformCleanup()
30-
}
31-
3226
// NoInstallListener tells our cleanup routine that we will not be using a possibly provided listener
3327
// for our install HTTP/HTTPS service
3428
func NoInstallListener() {

models/fixtures/hook_task.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
id: 2
1919
hook_id: 1
2020
uuid: uuid2
21-
is_delivered: false
21+
is_delivered: true
2222

2323
-
2424
id: 3

models/repo/pushmirror_test.go

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,8 +39,6 @@ func TestPushMirrorsIterate(t *testing.T) {
3939
Interval: 0,
4040
})
4141

42-
time.Sleep(1 * time.Millisecond)
43-
4442
repo_model.PushMirrorsIterate(db.DefaultContext, 1, func(idx int, bean any) error {
4543
m, ok := bean.(*repo_model.PushMirror)
4644
assert.True(t, ok)

models/user/user_test.go

Lines changed: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -513,11 +513,8 @@ func TestIsUserVisibleToViewer(t *testing.T) {
513513
}
514514

515515
func Test_ValidateUser(t *testing.T) {
516-
oldSetting := setting.Service.AllowedUserVisibilityModesSlice
517-
defer func() {
518-
setting.Service.AllowedUserVisibilityModesSlice = oldSetting
519-
}()
520-
setting.Service.AllowedUserVisibilityModesSlice = []bool{true, false, true}
516+
defer test.MockVariableValue(&setting.Service.AllowedUserVisibilityModesSlice, []bool{true, false, true})()
517+
521518
kases := map[*user_model.User]bool{
522519
{ID: 1, Visibility: structs.VisibleTypePublic}: true,
523520
{ID: 2, Visibility: structs.VisibleTypeLimited}: false,
@@ -586,12 +583,7 @@ func TestDisabledUserFeatures(t *testing.T) {
586583
testValues := container.SetOf(setting.UserFeatureDeletion,
587584
setting.UserFeatureManageSSHKeys,
588585
setting.UserFeatureManageGPGKeys)
589-
590-
oldSetting := setting.Admin.ExternalUserDisableFeatures
591-
defer func() {
592-
setting.Admin.ExternalUserDisableFeatures = oldSetting
593-
}()
594-
setting.Admin.ExternalUserDisableFeatures = testValues
586+
defer test.MockVariableValue(&setting.Admin.ExternalUserDisableFeatures, testValues)()
595587

596588
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
597589

modules/auth/openid/discovery_cache_test.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,8 @@ func (s *testDiscoveredInfo) OpLocalID() string {
2626
}
2727

2828
func TestTimedDiscoveryCache(t *testing.T) {
29-
dc := newTimedDiscoveryCache(1 * time.Second)
29+
ttl := 50 * time.Millisecond
30+
dc := newTimedDiscoveryCache(ttl)
3031

3132
// Put some initial values
3233
dc.Put("foo", &testDiscoveredInfo{}) // openid.opEndpoint: "a", openid.opLocalID: "b", openid.claimedID: "c"})
@@ -41,8 +42,8 @@ func TestTimedDiscoveryCache(t *testing.T) {
4142
// Attempt to get a non-existent value
4243
assert.Nil(t, dc.Get("bar"))
4344

44-
// Sleep one second and try retrieve again
45-
time.Sleep(1 * time.Second)
45+
// Sleep for a while and try to retrieve again
46+
time.Sleep(ttl * 3 / 2)
4647

4748
assert.Nil(t, dc.Get("foo"))
4849
}

modules/indexer/issues/internal/tests/tests.go

Lines changed: 9 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
package tests
99

1010
import (
11-
"context"
1211
"fmt"
1312
"slices"
1413
"testing"
@@ -40,7 +39,7 @@ func TestIndexer(t *testing.T, indexer internal.Indexer) {
4039
data[v.ID] = v
4140
}
4241
require.NoError(t, indexer.Index(t.Context(), d...))
43-
require.NoError(t, waitData(indexer, int64(len(data))))
42+
waitData(t, indexer, int64(len(data)))
4443
}
4544

4645
defer func() {
@@ -54,13 +53,13 @@ func TestIndexer(t *testing.T, indexer internal.Indexer) {
5453
for _, v := range c.ExtraData {
5554
data[v.ID] = v
5655
}
57-
require.NoError(t, waitData(indexer, int64(len(data))))
56+
waitData(t, indexer, int64(len(data)))
5857
defer func() {
5958
for _, v := range c.ExtraData {
6059
require.NoError(t, indexer.Delete(t.Context(), v.ID))
6160
delete(data, v.ID)
6261
}
63-
require.NoError(t, waitData(indexer, int64(len(data))))
62+
waitData(t, indexer, int64(len(data)))
6463
}()
6564
}
6665

@@ -751,22 +750,10 @@ func countIndexerData(data map[int64]*internal.IndexerData, f func(v *internal.I
751750

752751
// waitData waits for the indexer to index all data.
753752
// Some engines like Elasticsearch index data asynchronously, so we need to wait for a while.
754-
func waitData(indexer internal.Indexer, total int64) error {
755-
var actual int64
756-
for i := 0; i < 100; i++ {
757-
result, err := indexer.Search(context.Background(), &internal.SearchOptions{
758-
Paginator: &db.ListOptions{
759-
PageSize: 0,
760-
},
761-
})
762-
if err != nil {
763-
return err
764-
}
765-
actual = result.Total
766-
if actual == total {
767-
return nil
768-
}
769-
time.Sleep(100 * time.Millisecond)
770-
}
771-
return fmt.Errorf("waitData: expected %d, actual %d", total, actual)
753+
func waitData(t *testing.T, indexer internal.Indexer, total int64) {
754+
assert.Eventually(t, func() bool {
755+
result, err := indexer.Search(t.Context(), &internal.SearchOptions{Paginator: &db.ListOptions{}})
756+
require.NoError(t, err)
757+
return result.Total == total
758+
}, 10*time.Second, 100*time.Millisecond, "expected total=%d", total)
772759
}

modules/setting/git_test.go

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ package setting
66
import (
77
"testing"
88

9+
"code.gitea.io/gitea/modules/test"
10+
911
"github.com/stretchr/testify/assert"
1012
)
1113

@@ -36,12 +38,8 @@ diff.algorithm = other
3638
}
3739

3840
func TestGitReflog(t *testing.T) {
39-
oldGit := Git
40-
oldGitConfig := GitConfig
41-
defer func() {
42-
Git = oldGit
43-
GitConfig = oldGitConfig
44-
}()
41+
defer test.MockVariableValue(&Git)
42+
defer test.MockVariableValue(&GitConfig)
4543

4644
// default reflog config without legacy options
4745
cfg, err := NewConfigProviderFromData(``)

modules/validation/helpers_test.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"testing"
88

99
"code.gitea.io/gitea/modules/setting"
10+
"code.gitea.io/gitea/modules/test"
1011

1112
"github.com/stretchr/testify/assert"
1213
)
@@ -47,7 +48,7 @@ func Test_IsValidURL(t *testing.T) {
4748
}
4849

4950
func Test_IsValidExternalURL(t *testing.T) {
50-
setting.AppURL = "https://try.gitea.io/"
51+
defer test.MockVariableValue(&setting.AppURL, "https://try.gitea.io/")()
5152

5253
cases := []struct {
5354
description string
@@ -89,7 +90,7 @@ func Test_IsValidExternalURL(t *testing.T) {
8990
}
9091

9192
func Test_IsValidExternalTrackerURLFormat(t *testing.T) {
92-
setting.AppURL = "https://try.gitea.io/"
93+
defer test.MockVariableValue(&setting.AppURL, "https://try.gitea.io/")()
9394

9495
cases := []struct {
9596
description string

routers/web/repo/setting/settings_test.go

Lines changed: 3 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"code.gitea.io/gitea/models/unittest"
1616
user_model "code.gitea.io/gitea/models/user"
1717
"code.gitea.io/gitea/modules/setting"
18+
"code.gitea.io/gitea/modules/test"
1819
"code.gitea.io/gitea/modules/web"
1920
"code.gitea.io/gitea/services/context"
2021
"code.gitea.io/gitea/services/contexttest"
@@ -24,23 +25,8 @@ import (
2425
"github.com/stretchr/testify/assert"
2526
)
2627

27-
func createSSHAuthorizedKeysTmpPath(t *testing.T) func() {
28-
tmpDir := t.TempDir()
29-
30-
oldPath := setting.SSH.RootPath
31-
setting.SSH.RootPath = tmpDir
32-
33-
return func() {
34-
setting.SSH.RootPath = oldPath
35-
}
36-
}
37-
3828
func TestAddReadOnlyDeployKey(t *testing.T) {
39-
if deferable := createSSHAuthorizedKeysTmpPath(t); deferable != nil {
40-
defer deferable()
41-
} else {
42-
return
43-
}
29+
defer test.MockVariableValue(&setting.SSH.RootPath, t.TempDir())()
4430
unittest.PrepareTestEnv(t)
4531

4632
ctx, _ := contexttest.MockContext(t, "user2/repo1/settings/keys")
@@ -64,11 +50,7 @@ func TestAddReadOnlyDeployKey(t *testing.T) {
6450
}
6551

6652
func TestAddReadWriteOnlyDeployKey(t *testing.T) {
67-
if deferable := createSSHAuthorizedKeysTmpPath(t); deferable != nil {
68-
defer deferable()
69-
} else {
70-
return
71-
}
53+
defer test.MockVariableValue(&setting.SSH.RootPath, t.TempDir())()
7254

7355
unittest.PrepareTestEnv(t)
7456

services/forms/user_form_test.go

Lines changed: 4 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"testing"
88

99
"code.gitea.io/gitea/modules/setting"
10+
"code.gitea.io/gitea/modules/test"
1011

1112
"github.com/gobwas/glob"
1213
"github.com/stretchr/testify/assert"
@@ -26,12 +27,7 @@ func TestRegisterForm_IsDomainAllowed_Empty(t *testing.T) {
2627
}
2728

2829
func TestRegisterForm_IsDomainAllowed_InvalidEmail(t *testing.T) {
29-
oldService := setting.Service
30-
defer func() {
31-
setting.Service = oldService
32-
}()
33-
34-
setting.Service.EmailDomainAllowList = []glob.Glob{glob.MustCompile("gitea.io")}
30+
defer test.MockVariableValue(&setting.Service.EmailDomainAllowList, []glob.Glob{glob.MustCompile("gitea.io")})()
3531

3632
tt := []struct {
3733
email string
@@ -48,12 +44,7 @@ func TestRegisterForm_IsDomainAllowed_InvalidEmail(t *testing.T) {
4844
}
4945

5046
func TestRegisterForm_IsDomainAllowed_AllowedEmail(t *testing.T) {
51-
oldService := setting.Service
52-
defer func() {
53-
setting.Service = oldService
54-
}()
55-
56-
setting.Service.EmailDomainAllowList = []glob.Glob{glob.MustCompile("gitea.io"), glob.MustCompile("*.allow")}
47+
defer test.MockVariableValue(&setting.Service.EmailDomainAllowList, []glob.Glob{glob.MustCompile("gitea.io"), glob.MustCompile("*.allow")})()
5748

5849
tt := []struct {
5950
email string
@@ -76,13 +67,7 @@ func TestRegisterForm_IsDomainAllowed_AllowedEmail(t *testing.T) {
7667
}
7768

7869
func TestRegisterForm_IsDomainAllowed_BlockedEmail(t *testing.T) {
79-
oldService := setting.Service
80-
defer func() {
81-
setting.Service = oldService
82-
}()
83-
84-
setting.Service.EmailDomainAllowList = nil
85-
setting.Service.EmailDomainBlockList = []glob.Glob{glob.MustCompile("gitea.io"), glob.MustCompile("*.block")}
70+
defer test.MockVariableValue(&setting.Service.EmailDomainBlockList, []glob.Glob{glob.MustCompile("gitea.io"), glob.MustCompile("*.block")})()
8671

8772
tt := []struct {
8873
email string

services/repository/fork_test.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
user_model "code.gitea.io/gitea/models/user"
1414
"code.gitea.io/gitea/modules/git"
1515
"code.gitea.io/gitea/modules/setting"
16+
"code.gitea.io/gitea/modules/test"
1617
"code.gitea.io/gitea/modules/util"
1718

1819
"github.com/stretchr/testify/assert"
@@ -38,7 +39,7 @@ func TestForkRepository(t *testing.T) {
3839
assert.False(t, repo_model.IsErrReachLimitOfRepo(err))
3940

4041
// change AllowForkWithoutMaximumLimit to false for the test
41-
setting.Repository.AllowForkWithoutMaximumLimit = false
42+
defer test.MockVariableValue(&setting.Repository.AllowForkWithoutMaximumLimit, false)()
4243
// user has reached maximum limit of repositories
4344
user.MaxRepoCreation = 0
4445
fork2, err := ForkRepository(git.DefaultContext, user, user, ForkRepoOptions{

services/webhook/webhook_test.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
webhook_model "code.gitea.io/gitea/models/webhook"
1414
"code.gitea.io/gitea/modules/setting"
1515
api "code.gitea.io/gitea/modules/structs"
16+
"code.gitea.io/gitea/modules/test"
1617
webhook_module "code.gitea.io/gitea/modules/webhook"
1718
"code.gitea.io/gitea/services/convert"
1819

@@ -84,7 +85,8 @@ func TestPrepareWebhooksBranchFilterNoMatch(t *testing.T) {
8485

8586
func TestWebhookUserMail(t *testing.T) {
8687
require.NoError(t, unittest.PrepareTestDatabase())
87-
setting.Service.NoReplyAddress = "no-reply.com"
88+
defer test.MockVariableValue(&setting.Service.NoReplyAddress, "no-reply.com")()
89+
8890
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
8991
assert.Equal(t, user.GetPlaceholderEmail(), convert.ToUser(db.DefaultContext, user, nil).Email)
9092
assert.Equal(t, user.Email, convert.ToUser(db.DefaultContext, user, user).Email)

tests/integration/actions_runner_test.go

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -115,10 +115,9 @@ func (r *mockRunner) fetchTask(t *testing.T, timeout ...time.Duration) *runnerv1
115115
}
116116

117117
type mockTaskOutcome struct {
118-
result runnerv1.Result
119-
outputs map[string]string
120-
logRows []*runnerv1.LogRow
121-
execTime time.Duration
118+
result runnerv1.Result
119+
outputs map[string]string
120+
logRows []*runnerv1.LogRow
122121
}
123122

124123
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
145144
sentOutputKeys = append(sentOutputKeys, outputKey)
146145
assert.ElementsMatch(t, sentOutputKeys, resp.Msg.SentOutputs)
147146
}
148-
time.Sleep(outcome.execTime)
149147
resp, err := r.client.runnerServiceClient.UpdateTask(t.Context(), connect.NewRequest(&runnerv1.UpdateTaskRequest{
150148
State: &runnerv1.TaskState{
151149
Id: task.Id,

0 commit comments

Comments
 (0)