Skip to content

Refactor some tests #34580

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 5 additions & 12 deletions cmd/admin_auth_ldap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
6 changes: 0 additions & 6 deletions cmd/web_graceful.go
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
2 changes: 1 addition & 1 deletion models/fixtures/hook_task.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
id: 2
hook_id: 1
uuid: uuid2
is_delivered: false
is_delivered: true

-
id: 3
Expand Down
2 changes: 0 additions & 2 deletions models/repo/pushmirror_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
14 changes: 3 additions & 11 deletions models/user/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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})

Expand Down
7 changes: 4 additions & 3 deletions modules/auth/openid/discovery_cache_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"})
Expand All @@ -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"))
}
31 changes: 9 additions & 22 deletions modules/indexer/issues/internal/tests/tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
package tests

import (
"context"
"fmt"
"slices"
"testing"
Expand Down Expand Up @@ -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() {
Expand All @@ -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)))
}()
}

Expand Down Expand Up @@ -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)
}
10 changes: 4 additions & 6 deletions modules/setting/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ package setting
import (
"testing"

"code.gitea.io/gitea/modules/test"

"github.com/stretchr/testify/assert"
)

Expand Down Expand Up @@ -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(``)
Expand Down
5 changes: 3 additions & 2 deletions modules/validation/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"testing"

"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"

"github.com/stretchr/testify/assert"
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
24 changes: 3 additions & 21 deletions routers/web/repo/setting/settings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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")
Expand All @@ -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)

Expand Down
23 changes: 4 additions & 19 deletions services/forms/user_form_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion services/repository/fork_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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{
Expand Down
4 changes: 3 additions & 1 deletion services/webhook/webhook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down Expand Up @@ -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)
Expand Down
8 changes: 3 additions & 5 deletions tests/integration/actions_runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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,
Expand Down
Loading