chore: clean up tests (#37715)

1. use MockVariableValue as much as possible
2. use wg.Go as much as possible instead of Add/Done
3. simplify global lock's DefaultLocker logic to make it easier to test
4. introduce a general approach for getting external service config in
CI
5. remove unclear & unnecessary "t.Skip"
6. use modern generic syntax for remaining "DecodeJSON" calls
7. clarify test result for "list gitignore templates" and "list
licenses"
This commit is contained in:
wxiaoguang
2026-05-15 22:26:36 +08:00
committed by GitHub
parent cf0f25b798
commit 59db4154eb
39 changed files with 208 additions and 313 deletions

View File

@@ -6,31 +6,39 @@ package globallock
import (
"context"
"sync"
"sync/atomic"
"code.gitea.io/gitea/modules/setting"
)
var (
defaultLocker Locker
initOnce sync.Once
initFunc = func() {
switch setting.GlobalLock.ServiceType {
case "redis":
defaultLocker = NewRedisLocker(setting.GlobalLock.ServiceConnStr)
case "memory":
fallthrough
default:
defaultLocker = NewMemoryLocker()
}
} // define initFunc as a variable to make it possible to change it in tests
defaultLocker atomic.Pointer[Locker]
defaultMutex sync.Mutex
)
func initDefaultLocker() Locker {
switch setting.GlobalLock.ServiceType {
case "redis":
return NewRedisLocker(setting.GlobalLock.ServiceConnStr)
default: // "memory"
return NewMemoryLocker()
}
}
// DefaultLocker returns the default locker.
func DefaultLocker() Locker {
initOnce.Do(func() {
initFunc()
})
return defaultLocker
ptr := defaultLocker.Load()
if ptr == nil {
defaultMutex.Lock()
ptr = defaultLocker.Load()
if ptr == nil {
ptr = new(initDefaultLocker())
defaultLocker.Store(ptr)
}
defaultMutex.Unlock()
ptr = defaultLocker.Load()
}
return *ptr
}
// Lock tries to acquire a lock for the given key, it uses the default locker.

View File

@@ -5,7 +5,6 @@ package globallock
import (
"context"
"os"
"sync"
"testing"
@@ -15,50 +14,13 @@ import (
func TestLockAndDo(t *testing.T) {
t.Run("redis", func(t *testing.T) {
url := "redis://127.0.0.1:6379/0"
if os.Getenv("CI") == "" {
// Make it possible to run tests against a local redis instance
url = os.Getenv("TEST_REDIS_URL")
if url == "" {
t.Skip("TEST_REDIS_URL not set and not running in CI")
return
}
}
oldDefaultLocker := defaultLocker
oldInitFunc := initFunc
defer func() {
defaultLocker = oldDefaultLocker
initFunc = oldInitFunc
if defaultLocker == nil {
initOnce = sync.Once{}
}
}()
initOnce = sync.Once{}
initFunc = func() {
defaultLocker = NewRedisLocker(url)
}
locker := newTestRedisLocker(t)
defaultLocker.Store(new(locker))
testLockAndDo(t)
require.NoError(t, defaultLocker.(*redisLocker).Close())
require.NoError(t, locker.(*redisLocker).Close())
})
t.Run("memory", func(t *testing.T) {
oldDefaultLocker := defaultLocker
oldInitFunc := initFunc
defer func() {
defaultLocker = oldDefaultLocker
initFunc = oldInitFunc
if defaultLocker == nil {
initOnce = sync.Once{}
}
}()
initOnce = sync.Once{}
initFunc = func() {
defaultLocker = NewMemoryLocker()
}
defaultLocker.Store(new(NewMemoryLocker()))
testLockAndDo(t)
})
}
@@ -69,13 +31,10 @@ func testLockAndDo(t *testing.T) {
ctx := t.Context()
count := 0
wg := sync.WaitGroup{}
wg.Add(concurrency)
for range concurrency {
go func() {
defer wg.Done()
wg.Go(func() {
err := LockAndDo(ctx, "test", func(ctx context.Context) error {
count++
// It's impossible to acquire the lock inner the function
ok, err := TryLockAndDo(ctx, "test", func(ctx context.Context) error {
assert.Fail(t, "should not acquire the lock")
@@ -83,13 +42,11 @@ func testLockAndDo(t *testing.T) {
})
assert.False(t, ok)
assert.NoError(t, err)
return nil
})
require.NoError(t, err)
}()
assert.NoError(t, err)
})
}
wg.Wait()
assert.Equal(t, concurrency, count)

View File

@@ -10,29 +10,30 @@ import (
"testing"
"time"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/util"
"github.com/go-redsync/redsync/v4"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newTestRedisLocker(t *testing.T) Locker {
t.Helper()
redisURL := util.IfZero(os.Getenv("TEST_REDIS_URL"), "redis://127.0.0.1:6379/0")
rl := NewRedisLocker(redisURL).(*redisLocker)
err := rl.conn.Ping(t.Context()).Err()
if err != nil && test.AllowSkipExternalService() {
t.Skip("no redis server for testing, skipped")
}
require.NoError(t, err, "redis error for testing: %v", err)
return rl
}
func TestLocker(t *testing.T) {
t.Run("redis", func(t *testing.T) {
url := "redis://127.0.0.1:6379/0"
if os.Getenv("CI") == "" {
// Make it possible to run tests against a local redis instance
url = os.Getenv("TEST_REDIS_URL")
if url == "" {
t.Skip("TEST_REDIS_URL not set and not running in CI")
return
}
}
oldExpiry := redisLockExpiry
redisLockExpiry = 5 * time.Second // make it shorter for testing
defer func() {
redisLockExpiry = oldExpiry
}()
locker := NewRedisLocker(url)
defer test.MockVariableValue(&redisLockExpiry, 5*time.Second)() // make it shorter for testing
locker := newTestRedisLocker(t)
testLocker(t, locker)
testRedisLocker(t, locker.(*redisLocker))
require.NoError(t, locker.(*redisLocker).Close())

View File

@@ -14,6 +14,7 @@ import (
"github.com/go-redsync/redsync/v4"
"github.com/go-redsync/redsync/v4/redis/goredis/v9"
"github.com/redis/go-redis/v9"
)
const redisLockKeyPrefix = "gitea:globallock:"
@@ -23,7 +24,8 @@ const redisLockKeyPrefix = "gitea:globallock:"
var redisLockExpiry = 30 * time.Second
type redisLocker struct {
rs *redsync.Redsync
conn redis.UniversalClient
rs *redsync.Redsync
mutexM sync.Map
closed atomic.Bool
@@ -33,17 +35,13 @@ type redisLocker struct {
var _ Locker = &redisLocker{}
func NewRedisLocker(connection string) Locker {
conn := nosql.GetManager().GetRedisClient(connection)
l := &redisLocker{
rs: redsync.New(
goredis.NewPool(
nosql.GetManager().GetRedisClient(connection),
),
),
conn: conn,
rs: redsync.New(goredis.NewPool(conn)),
}
l.extendWg.Add(1)
l.startExtend()
return l
}

View File

@@ -4,24 +4,19 @@
package elasticsearch
import (
"os"
"strings"
"testing"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/require"
)
func newRealIndexer(t *testing.T) *Indexer {
t.Helper()
url := "http://elasticsearch:9200"
if os.Getenv("CI") == "" {
url = os.Getenv("TEST_ELASTICSEARCH_URL")
if url == "" {
t.Skip("TEST_ELASTICSEARCH_URL not set and not running in CI")
}
}
esURL := test.ExternalServiceHTTP(t, "TEST_ELASTICSEARCH_URL", "http://elasticsearch:9200")
indexName := "gitea_test_" + strings.ReplaceAll(strings.ToLower(t.Name()), "/", "_")
ix := NewIndexer(url, indexName, 1, `{"mappings":{"properties":{"x":{"type":"keyword"}}}}`)
ix := NewIndexer(esURL, indexName, 1, `{"mappings":{"properties":{"x":{"type":"keyword"}}}}`)
_, err := ix.Init(t.Context())
require.NoError(t, err)
t.Cleanup(ix.Close)

View File

@@ -7,27 +7,18 @@ import (
"fmt"
"net/http"
"net/url"
"os"
"testing"
"time"
"code.gitea.io/gitea/modules/indexer/issues/internal/tests"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/require"
)
func TestElasticsearchIndexer(t *testing.T) {
// The elasticsearch instance started by pull-db-tests.yml > test-unit > services > elasticsearch
rawURL := "http://elastic:changeme@elasticsearch:9200"
if os.Getenv("CI") == "" {
// Make it possible to run tests against a local elasticsearch instance
rawURL = os.Getenv("TEST_ELASTICSEARCH_URL")
if rawURL == "" {
t.Skip("TEST_ELASTICSEARCH_URL not set and not running in CI")
return
}
}
rawURL := test.ExternalServiceHTTP(t, "TEST_ELASTICSEARCH_URL", "http://elastic:changeme@elasticsearch:9200")
// Go's net/http does not auto-attach URL userinfo as Basic Auth, so extract
// it and set the header explicitly; otherwise auth-enforced clusters answer

View File

@@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/modules/indexer/issues/internal"
"code.gitea.io/gitea/modules/indexer/issues/internal/tests"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/test"
"github.com/meilisearch/meilisearch-go"
"github.com/stretchr/testify/assert"
@@ -21,18 +22,8 @@ import (
func TestMeilisearchIndexer(t *testing.T) {
// The meilisearch instance started by pull-db-tests.yml > test-unit > services > meilisearch
url := "http://meilisearch:7700"
key := "" // auth has been disabled in test environment
if os.Getenv("CI") == "" {
// Make it possible to run tests against a local meilisearch instance
url = os.Getenv("TEST_MEILISEARCH_URL")
if url == "" {
t.Skip("TEST_MEILISEARCH_URL not set and not running in CI")
return
}
key = os.Getenv("TEST_MEILISEARCH_KEY")
}
url := test.ExternalServiceHTTP(t, "TEST_MEILISEARCH_URL", "http://meilisearch:7700")
key := os.Getenv("TEST_MEILISEARCH_KEY")
require.Eventually(t, func() bool {
resp, err := http.Get(url)

View File

@@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/modules/nosql"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -57,10 +58,10 @@ func TestBaseRedis(t *testing.T) {
}()
if !waitRedisReady("redis://127.0.0.1:6379/0", 0) {
redisServer = redisServerCmd(t)
if redisServer == nil && os.Getenv("CI") == "" {
t.Skip("redis-server not found")
return
if redisServer == nil && test.AllowSkipExternalService() {
t.Skip("redis server command not found, skipped")
}
require.NotNil(t, redisServer)
assert.NoError(t, redisServer.Start())
require.True(t, waitRedisReady("redis://127.0.0.1:6379/0", 5*time.Second), "start redis-server")
}

View File

@@ -5,25 +5,22 @@ package storage
import (
"io"
"os"
"strings"
"testing"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert"
)
func TestAzureBlobStorage(t *testing.T) {
if os.Getenv("CI") == "" {
t.Skip("azureBlobStorage not present outside of CI")
return
}
endpoint := test.ExternalServiceHTTP(t, "TEST_AZURESTORAGE_ENDPOINT", "http://devstoreaccount1.azurite.local:10000")
storageType := setting.AzureBlobStorageType
config := &setting.Storage{
AzureBlobConfig: setting.AzureBlobStorageConfig{
// https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#ip-style-url
Endpoint: "http://devstoreaccount1.azurite.local:10000",
Endpoint: endpoint,
// https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#well-known-storage-account-and-key
AccountName: "devstoreaccount1",
AccountKey: "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==",
@@ -77,15 +74,11 @@ func TestAzureBlobStoragePath(t *testing.T) {
}
func Test_azureBlobObject(t *testing.T) {
if os.Getenv("CI") == "" {
t.Skip("azureBlobStorage not present outside of CI")
return
}
endpoint := test.ExternalServiceHTTP(t, "TEST_AZURESTORAGE_ENDPOINT", "http://devstoreaccount1.azurite.local:10000")
s, err := NewStorage(setting.AzureBlobStorageType, &setting.Storage{
AzureBlobConfig: setting.AzureBlobStorageConfig{
// https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#ip-style-url
Endpoint: "http://devstoreaccount1.azurite.local:10000",
Endpoint: endpoint,
// https://learn.microsoft.com/azure/storage/common/storage-use-azurite?tabs=visual-studio-code#well-known-storage-account-and-key
AccountName: "devstoreaccount1",
AccountKey: "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==",

View File

@@ -11,20 +11,18 @@ import (
"testing"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"github.com/minio/minio-go/v7"
"github.com/stretchr/testify/assert"
)
func TestMinioStorage(t *testing.T) {
if os.Getenv("CI") == "" {
t.Skip("minioStorage not present outside of CI")
return
}
endpoint := test.ExternalServiceHTTP(t, "TEST_MINIO_ENDPOINT", "minio:9000")
storageType := setting.MinioStorageType
config := &setting.Storage{
MinioConfig: setting.MinioStorageConfig{
Endpoint: "minio:9000",
Endpoint: endpoint,
AccessKeyID: "123456",
SecretAccessKey: "12345678",
Bucket: "gitea",

View File

@@ -11,7 +11,10 @@ import (
"io"
"net/http"
"net/http/httptest"
"os"
"strconv"
"strings"
"sync"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/util"
@@ -141,3 +144,41 @@ func CompressGzip(content string) *bytes.Buffer {
_ = cw.Close()
return buf
}
var AllowSkipExternalService = sync.OnceValue(func() bool {
isLocalTesting := os.Getenv("CI") == ""
ciSkipExternal, _ := strconv.ParseBool(os.Getenv("GITEA_TEST_CI_SKIP_EXTERNAL"))
return isLocalTesting || ciSkipExternal
})
type TestingT interface {
Helper()
Skipf(format string, args ...any)
Errorf(format string, args ...any)
Fatalf(format string, args ...any)
}
func ExternalServiceHTTP(t TestingT, envVarName, def string) string {
t.Helper()
val := util.IfZero(os.Getenv(envVarName), def)
if val == "" {
if AllowSkipExternalService() {
t.Skipf("skipping test because %s is not set", envVarName)
} else {
t.Fatalf("%s is not set, but skipping is not allowed in CI", envVarName)
}
}
// minio's endpoint is "host:port" pattern
testURL := util.Iif(strings.Contains(val, "://"), val, "http://"+val)
resp, err := http.Get(testURL)
if err != nil {
if AllowSkipExternalService() {
t.Skipf("skipping test because %s is not ready", val)
} else {
t.Fatalf("%s is not ready, but skipping is not allowed in CI", val)
}
} else {
_ = resp.Body.Close()
}
return val
}

View File

@@ -398,7 +398,7 @@ func TestActionsArtifactV4UploadSingleFileWithChunksOutOfOrder(t *testing.T) {
defer test.MockVariableValue(&setting.Actions.ArtifactStorage.AzureBlobConfig.ServeDirect, entry.serveDirect)()
default:
if entry.serveDirect {
t.Skip()
t.Skip("for non-serve-direct only")
}
}
// acquire artifact upload url
@@ -529,7 +529,7 @@ func TestActionsArtifactV4DownloadSingle(t *testing.T) {
defer test.MockVariableValue(&setting.Actions.ArtifactStorage.MinioConfig.ServeDirect, entry.ServeDirect)()
default:
if entry.ServeDirect {
t.Skip()
t.Skip("for non-serve-direct only")
}
}

View File

@@ -17,6 +17,7 @@ import (
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
@@ -335,11 +336,7 @@ func TestAPICron(t *testing.T) {
func TestAPICreateUser_NotAllowedEmailDomain(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.Service.EmailDomainAllowList = []glob.Glob{glob.MustCompile("example.org")}
defer func() {
setting.Service.EmailDomainAllowList = []glob.Glob{}
}()
defer test.MockVariableValue(&setting.Service.EmailDomainAllowList, []glob.Glob{glob.MustCompile("example.org")})()
adminUsername := "user1"
token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin)
@@ -360,11 +357,7 @@ func TestAPICreateUser_NotAllowedEmailDomain(t *testing.T) {
func TestAPIEditUser_NotAllowedEmailDomain(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.Service.EmailDomainAllowList = []glob.Glob{glob.MustCompile("example.org")}
defer func() {
setting.Service.EmailDomainAllowList = []glob.Glob{}
}()
defer test.MockVariableValue(&setting.Service.EmailDomainAllowList, []glob.Glob{glob.MustCompile("example.org")})()
adminUsername := "user1"
token := getUserToken(t, adminUsername, auth_model.AccessTokenScopeWriteAdmin)

View File

@@ -21,8 +21,9 @@ func TestAPIListGitignoresTemplates(t *testing.T) {
req := NewRequest(t, "GET", "/api/v1/gitignore/templates")
resp := MakeRequest(t, req, http.StatusOK)
// This tests if the API returns a list of strings
DecodeJSON(t, resp, []string{})
templateList := DecodeJSON(t, resp, []string{}) // this is a very long list
assert.Contains(t, templateList, "C++")
assert.Contains(t, templateList, "Go")
}
func TestAPIGetGitignoreTemplateInfo(t *testing.T) {

View File

@@ -39,8 +39,7 @@ func TestAPIIssueSubscriptions(t *testing.T) {
req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check", issueRepo.OwnerName, issueRepo.Name, issue.Index)).
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusOK)
wi := new(api.WatchInfo)
DecodeJSON(t, resp, wi)
wi := DecodeJSON(t, resp, &api.WatchInfo{})
assert.Equal(t, isWatching, wi.Subscribed)
assert.Equal(t, !isWatching, wi.Ignored)

View File

@@ -513,15 +513,14 @@ func testAPIIssueProjects(t *testing.T) {
Projects: []int64{1},
}).AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusCreated)
var apiIssue api.Issue
DecodeJSON(t, resp, &apiIssue)
apiIssue := DecodeJSON(t, resp, &api.Issue{})
assert.Len(t, apiIssue.Projects, 1)
assert.EqualValues(t, 1, apiIssue.Projects[0].ID)
// Get issue should include projects
req = NewRequest(t, "GET", fmt.Sprintf("%s/%d", urlStr, apiIssue.Index)).AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &apiIssue)
apiIssue = DecodeJSON(t, resp, &api.Issue{})
assert.Len(t, apiIssue.Projects, 1)
assert.EqualValues(t, 1, apiIssue.Projects[0].ID)
@@ -531,7 +530,7 @@ func testAPIIssueProjects(t *testing.T) {
Projects: &emptyProjects,
}).AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusCreated)
DecodeJSON(t, resp, &apiIssue)
apiIssue = DecodeJSON(t, resp, &api.Issue{})
assert.Empty(t, apiIssue.Projects)
// Edit issue to add project back
@@ -540,7 +539,7 @@ func testAPIIssueProjects(t *testing.T) {
Projects: &projects,
}).AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusCreated)
DecodeJSON(t, resp, &apiIssue)
apiIssue = DecodeJSON(t, resp, &api.Issue{})
assert.Len(t, apiIssue.Projects, 1)
assert.EqualValues(t, 1, apiIssue.Projects[0].ID)

View File

@@ -10,6 +10,7 @@ import (
"code.gitea.io/gitea/modules/options"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/tests"
@@ -22,8 +23,12 @@ func TestAPIListLicenseTemplates(t *testing.T) {
req := NewRequest(t, "GET", "/api/v1/licenses")
resp := MakeRequest(t, req, http.StatusOK)
// This tests if the API returns a list of strings
DecodeJSON(t, resp, []api.LicensesTemplateListEntry{})
licenseList := DecodeJSON(t, resp, []api.LicensesTemplateListEntry{})
assert.Contains(t, licenseList, api.LicensesTemplateListEntry{
Key: "MIT",
Name: "MIT",
URL: setting.AppURL + "api/v1/licenses/MIT",
})
}
func TestAPIGetLicenseTemplateInfo(t *testing.T) {

View File

@@ -556,9 +556,7 @@ func testAPIPullReviewCommentReply(t *testing.T) {
// happy path
req := NewRequestWithJSON(t, http.MethodPost, url, &api.CreatePullReviewCommentReplyOptions{Body: "the reply"}).AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusCreated)
var reply api.PullReviewComment
DecodeJSON(t, resp, &reply)
reply := DecodeJSON(t, resp, &api.PullReviewComment{})
assert.Equal(t, "the reply", reply.Body)
assert.Equal(t, parent.ReviewID, reply.ReviewID)
assert.Equal(t, "README.md", reply.Path)

View File

@@ -155,8 +155,7 @@ func TestAPIViewPullsByBaseHead(t *testing.T) {
AddTokenAuth(ctx.Token)
resp := ctx.Session.MakeRequest(t, req, http.StatusOK)
pull := &api.PullRequest{}
DecodeJSON(t, resp, pull)
pull := DecodeJSON(t, resp, &api.PullRequest{})
assert.EqualValues(t, 3, pull.Index)
assert.EqualValues(t, 2, pull.ID)
@@ -394,10 +393,8 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) {
req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), opts).
AddTokenAuth(token)
res := MakeRequest(t, req, http.StatusCreated)
pull := new(api.PullRequest)
DecodeJSON(t, res, pull)
resp := MakeRequest(t, req, http.StatusCreated)
pull := DecodeJSON(t, resp, &api.PullRequest{})
assert.NotNil(t, pull.Milestone)
assert.Equal(t, opts.Milestone, pull.Milestone.ID)

View File

@@ -15,6 +15,7 @@ import (
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
@@ -22,7 +23,7 @@ import (
func TestAPILFSLocksNotStarted(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.LFS.StartServer = false
defer test.MockVariableValue(&setting.LFS.StartServer, false)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@@ -38,7 +39,7 @@ func TestAPILFSLocksNotStarted(t *testing.T) {
func TestAPILFSLocksNotLogin(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.LFS.StartServer = true
defer test.MockVariableValue(&setting.LFS.StartServer, true)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@@ -51,7 +52,7 @@ func TestAPILFSLocksNotLogin(t *testing.T) {
func TestAPILFSLocksLogged(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.LFS.StartServer = true
defer test.MockVariableValue(&setting.LFS.StartServer, true)()
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // in org 3
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // in org 3

View File

@@ -14,6 +14,7 @@ import (
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/services/migrations"
"code.gitea.io/gitea/tests"
@@ -22,11 +23,8 @@ import (
func TestAPIRepoLFSMigrateLocal(t *testing.T) {
defer tests.PrepareTestEnv(t)()
oldImportLocalPaths := setting.ImportLocalPaths
oldAllowLocalNetworks := setting.Migrations.AllowLocalNetworks
setting.ImportLocalPaths = true
setting.Migrations.AllowLocalNetworks = true
defer test.MockVariableValue(&setting.ImportLocalPaths, true)()
defer test.MockVariableValue(&setting.Migrations.AllowLocalNetworks, true)()
assert.NoError(t, migrations.Init())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
@@ -47,8 +45,4 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) {
assert.True(t, ok)
ok, _ = store.Verify(lfs.Pointer{Oid: "d6f175817f886ec6fbbc1515326465fa96c3bfd54a4ea06cfd6dbbd8340e0152", Size: 6})
assert.True(t, ok)
setting.ImportLocalPaths = oldImportLocalPaths
setting.Migrations.AllowLocalNetworks = oldAllowLocalNetworks
assert.NoError(t, migrations.Init()) // reset old migration settings
}

View File

@@ -28,8 +28,7 @@ import (
func TestAPILFSNotStarted(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.LFS.StartServer = false
defer test.MockVariableValue(&setting.LFS.StartServer, false)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@@ -48,8 +47,7 @@ func TestAPILFSNotStarted(t *testing.T) {
func TestAPILFSMediaType(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.LFS.StartServer = true
defer test.MockVariableValue(&setting.LFS.StartServer, true)()
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@@ -72,8 +70,7 @@ func createLFSTestRepository(t *testing.T, repoName string) *repo_model.Reposito
func TestAPILFSBatch(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.LFS.StartServer = true
defer test.MockVariableValue(&setting.LFS.StartServer, true)()
repo := createLFSTestRepository(t, "lfs-batch-repo")
@@ -326,8 +323,7 @@ func TestAPILFSBatch(t *testing.T) {
func TestAPILFSUpload(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.LFS.StartServer = true
defer test.MockVariableValue(&setting.LFS.StartServer, true)()
repo := createLFSTestRepository(t, "lfs-upload-repo")
oid := storeObjectInRepo(t, repo.ID, "dummy3")
@@ -428,8 +424,7 @@ func TestAPILFSUpload(t *testing.T) {
func TestAPILFSVerify(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.LFS.StartServer = true
defer test.MockVariableValue(&setting.LFS.StartServer, true)()
repo := createLFSTestRepository(t, "lfs-verify-repo")
oid := storeObjectInRepo(t, repo.ID, "dummy3")

View File

@@ -17,10 +17,13 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/services/migrations"
repo_service "code.gitea.io/gitea/services/repository"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestAPIUserReposNotLogin(t *testing.T) {
@@ -60,11 +63,7 @@ func TestAPISearchRepo(t *testing.T) {
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 20})
orgUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 17})
oldAPIDefaultNum := setting.API.DefaultPagingNum
defer func() {
setting.API.DefaultPagingNum = oldAPIDefaultNum
}()
setting.API.DefaultPagingNum = 10
defer test.MockVariableValue(&setting.API.DefaultPagingNum, 10)()
// Map of expected results, where key is user for login
type expectedResults map[*user_model.User]struct {
@@ -367,6 +366,9 @@ func TestAPIRepoMigrate(t *testing.T) {
}
defer tests.PrepareTestEnv(t)()
defer test.MockVariableValue(&setting.Migrations.AllowLocalNetworks, false)()
require.NoError(t, migrations.Init())
for _, testCase := range testCases {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: testCase.ctxUserID})
session := loginUser(t, user.Name)
@@ -536,7 +538,6 @@ func TestAPIRepoTransfer(t *testing.T) {
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
repoName := "moveME"
apiRepo := new(api.Repository)
req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{
Name: repoName,
Description: "repo move around",
@@ -545,7 +546,7 @@ func TestAPIRepoTransfer(t *testing.T) {
AutoInit: true,
}).AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusCreated)
DecodeJSON(t, resp, apiRepo)
apiRepo := DecodeJSON(t, resp, &api.Repository{})
// start testing
for _, testCase := range testCases {
@@ -571,7 +572,6 @@ func transfer(t *testing.T) *repo_model.Repository {
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
repoName := "moveME"
apiRepo := new(api.Repository)
req := NewRequestWithJSON(t, "POST", "/api/v1/user/repos", &api.CreateRepoOption{
Name: repoName,
Description: "repo move around",
@@ -581,7 +581,7 @@ func transfer(t *testing.T) *repo_model.Repository {
}).AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusCreated)
DecodeJSON(t, resp, apiRepo)
apiRepo := DecodeJSON(t, resp, &api.Repository{})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID})
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer", repo.OwnerName, repo.Name), &api.TransferRepoOption{
@@ -616,8 +616,7 @@ func TestAPIAcceptTransfer(t *testing.T) {
req = NewRequest(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer/accept", repo.OwnerName, repo.Name)).
AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusAccepted)
apiRepo := new(api.Repository)
DecodeJSON(t, resp, apiRepo)
apiRepo := DecodeJSON(t, resp, &api.Repository{})
assert.Equal(t, "user4", apiRepo.Owner.UserName)
}
@@ -669,7 +668,6 @@ func TestAPIGenerateRepo(t *testing.T) {
}
// user
repo := new(api.Repository)
req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate", templateRepo.OwnerName, templateRepo.Name), &api.GenerateRepoOption{
Owner: user.Name,
Name: "new-repo",
@@ -678,10 +676,10 @@ func TestAPIGenerateRepo(t *testing.T) {
GitContent: true,
}).AddTokenAuth(token)
resp := MakeRequest(t, req, http.StatusCreated)
DecodeJSON(t, resp, repo)
apiRepo := DecodeJSON(t, resp, &api.Repository{})
assert.Equal(t, "new-repo", repo.Name)
assertGeneratedRepoIsUsable(t, user.Name, repo)
assert.Equal(t, "new-repo", apiRepo.Name)
assertGeneratedRepoIsUsable(t, user.Name, apiRepo)
// org
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/generate", templateRepo.OwnerName, templateRepo.Name), &api.GenerateRepoOption{
@@ -692,10 +690,10 @@ func TestAPIGenerateRepo(t *testing.T) {
GitContent: true,
}).AddTokenAuth(token)
resp = MakeRequest(t, req, http.StatusCreated)
DecodeJSON(t, resp, repo)
apiRepo = DecodeJSON(t, resp, &api.Repository{})
assert.Equal(t, "new-repo", repo.Name)
assertGeneratedRepoIsUsable(t, "org3", repo)
assert.Equal(t, "new-repo", apiRepo.Name)
assertGeneratedRepoIsUsable(t, "org3", apiRepo)
}
func TestAPIRepoGetReviewers(t *testing.T) {

View File

@@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestViewBranches(t *testing.T) {
@@ -57,9 +58,7 @@ func branchAction(t *testing.T, button string) (*HTMLDoc, string) {
htmlDoc := NewHTMLParser(t, resp.Body)
link, exists := htmlDoc.doc.Find(button).Attr("data-url")
if !assert.True(t, exists, "The template has changed") {
t.Skip()
}
require.True(t, exists, "The template has changed")
req = NewRequest(t, "POST", link)
session.MakeRequest(t, req, http.StatusOK)

View File

@@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/routers"
"code.gitea.io/gitea/tests"
@@ -52,16 +53,11 @@ func sessionFileExist(t *testing.T, tmpDir, sessionID string) bool {
func TestSessionFileCreation(t *testing.T) {
defer tests.PrepareTestEnv(t)()
oldSessionConfig := setting.SessionConfig.ProviderConfig
defer func() {
setting.SessionConfig.ProviderConfig = oldSessionConfig
testWebRoutes = routers.NormalRoutes()
}()
defer test.MockVariableValue(&setting.SessionConfig.ProviderConfig)()
defer test.MockVariableValue(&testWebRoutes)()
var config session.Options
err := json.Unmarshal([]byte(oldSessionConfig), &config)
err := json.Unmarshal([]byte(setting.SessionConfig.ProviderConfig), &config)
assert.NoError(t, err)
config.Provider = "file"

View File

@@ -20,6 +20,7 @@ import (
base "code.gitea.io/gitea/modules/migration"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/services/migrations"
"github.com/stretchr/testify/assert"
@@ -28,16 +29,9 @@ import (
func TestDumpRestore(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
AllowLocalNetworks := setting.Migrations.AllowLocalNetworks
setting.Migrations.AllowLocalNetworks = true
AppVer := setting.AppVer
// Gitea SDK (go-sdk) need to parse the AppVer from server response, so we must set it to a valid version string.
setting.AppVer = "1.16.0"
defer func() {
setting.Migrations.AllowLocalNetworks = AllowLocalNetworks
setting.AppVer = AppVer
}()
defer test.MockVariableValue(&setting.AppVer, "1.16.0")()
defer test.MockVariableValue(&setting.Migrations.AllowLocalNetworks, true)()
assert.NoError(t, migrations.Init())
reponame := "repo1"

View File

@@ -15,6 +15,7 @@ import (
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/modules/git/gitcmd"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers/common"
"code.gitea.io/gitea/services/context"
@@ -45,7 +46,7 @@ func TestGitLFSSSH(t *testing.T) {
cfg, err := setting.CfgProvider.PrepareSaving()
require.NoError(t, err)
cfg.Section("server").Key("LFS_ALLOW_PURE_SSH").SetValue("true")
setting.LFS.AllowPureSSH = true
defer test.MockVariableValue(&setting.LFS.AllowPureSSH, true)()
require.NoError(t, cfg.Save())
_, _, cmdErr := gitcmd.NewCommand("config", "lfs.sshtransfer", "always").

View File

@@ -9,6 +9,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"
@@ -36,12 +37,7 @@ func TestGoGet(t *testing.T) {
func TestGoGetForSSH(t *testing.T) {
defer tests.PrepareTestEnv(t)()
old := setting.Repository.GoGetCloneURLProtocol
defer func() {
setting.Repository.GoGetCloneURLProtocol = old
}()
setting.Repository.GoGetCloneURLProtocol = "ssh"
defer test.MockVariableValue(&setting.Repository.GoGetCloneURLProtocol, "ssh")()
req := NewRequest(t, "GET", "/blah/glah/plah?go-get=1")
resp := MakeRequest(t, req, http.StatusOK)

View File

@@ -7,6 +7,7 @@ import (
"bytes"
"context"
"encoding/base64"
"flag"
"fmt"
"hash"
"hash/fnv"
@@ -116,6 +117,11 @@ func testMain(m *testing.M) int {
}
func TestMain(m *testing.M) {
// -test.list must skip InitIntegrationTest, which requires a database.
flag.Parse()
if flag.Lookup("test.list").Value.String() != "" {
os.Exit(m.Run())
}
os.Exit(testMain(m))
}

View File

@@ -129,8 +129,7 @@ func TestLFSLockView(t *testing.T) {
req.Header.Set("Accept", lfs.AcceptHeader)
req.Header.Set("Content-Type", lfs.MediaType)
resp := session.MakeRequest(t, req, http.StatusCreated)
lockResp := &api.LFSLockResponse{}
DecodeJSON(t, resp, lockResp)
lockResp := DecodeJSON(t, resp, &api.LFSLockResponse{})
lockID = lockResp.Lock.ID
}
defer func() {

View File

@@ -27,6 +27,7 @@ import (
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/services/migrations"
"code.gitea.io/gitea/tests"
@@ -36,12 +37,10 @@ import (
func TestMigrateLocalPath(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
defer test.MockVariableValue(&setting.ImportLocalPaths, true)()
adminUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user1"})
old := setting.ImportLocalPaths
setting.ImportLocalPaths = true
basePath := t.TempDir()
lowercasePath := filepath.Join(basePath, "lowercase")
@@ -57,22 +56,13 @@ func TestMigrateLocalPath(t *testing.T) {
err = migrations.IsMigrateURLAllowed(mixedcasePath, adminUser)
assert.NoError(t, err, "case mixedcase path")
setting.ImportLocalPaths = old
}
func TestMigrateGiteaForm(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
AllowLocalNetworks := setting.Migrations.AllowLocalNetworks
setting.Migrations.AllowLocalNetworks = true
AppVer := setting.AppVer
// Gitea SDK (go-sdk) need to parse the AppVer from server response, so we must set it to a valid version string.
setting.AppVer = "1.16.0"
defer func() {
setting.Migrations.AllowLocalNetworks = AllowLocalNetworks
setting.AppVer = AppVer
migrations.Init()
}()
defer test.MockVariableValue(&setting.Migrations.AllowLocalNetworks, true)()
defer test.MockVariableValue(&setting.AppVer, "1.16.0")()
assert.NoError(t, migrations.Init())
ownerName := "user2"
@@ -232,14 +222,8 @@ done
func Test_MigrateFromGiteaToGitea(t *testing.T) {
defer tests.PrepareTestEnv(t)()
AllowLocalNetworks := setting.Migrations.AllowLocalNetworks
setting.Migrations.AllowLocalNetworks = true
defer func() {
setting.Migrations.AllowLocalNetworks = AllowLocalNetworks
migrations.Init()
}()
require.NoError(t, migrations.Init())
defer test.MockVariableValue(&setting.Migrations.AllowLocalNetworks, true)()
assert.NoError(t, migrations.Init())
mockServer := setupGiteaMockServer(t)

View File

@@ -17,6 +17,7 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/gitrepo"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/services/migrations"
mirror_service "code.gitea.io/gitea/services/mirror"
repo_service "code.gitea.io/gitea/services/repository"
@@ -35,7 +36,7 @@ func TestMirrorPushWikiDefaultBranchMismatch(t *testing.T) {
}
func testMirrorPush(t *testing.T, u *url.URL) {
setting.Migrations.AllowLocalNetworks = true
defer test.MockVariableValue(&setting.Migrations.AllowLocalNetworks, true)()
assert.NoError(t, migrations.Init())
_ = db.TruncateBeans(t.Context(), &repo_model.PushMirror{})
@@ -83,7 +84,7 @@ func testMirrorPush(t *testing.T, u *url.URL) {
}
func testMirrorPushWikiDefaultBranchMismatch(t *testing.T, u *url.URL) {
setting.Migrations.AllowLocalNetworks = true
defer test.MockVariableValue(&setting.Migrations.AllowLocalNetworks, true)()
assert.NoError(t, migrations.Init())
_ = db.TruncateBeans(t.Context(), &repo_model.PushMirror{})
@@ -154,7 +155,7 @@ func doUpdatePushMirror(t *testing.T, session *TestSession, owner, repo string,
func TestRepoSettingPushMirrorUpdate(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.Migrations.AllowLocalNetworks = true
defer test.MockVariableValue(&setting.Migrations.AllowLocalNetworks, true)()
assert.NoError(t, migrations.Init())
session := loginUser(t, "user2")

View File

@@ -21,11 +21,6 @@ import (
)
func TestOrgTeamEmailInvite(t *testing.T) {
if setting.MailService == nil {
t.Skip()
return
}
defer tests.PrepareTestEnv(t)()
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
@@ -68,11 +63,6 @@ func TestOrgTeamEmailInvite(t *testing.T) {
// Check that users are redirected to accept the invitation correctly after login
func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) {
if setting.MailService == nil {
t.Skip()
return
}
defer tests.PrepareTestEnv(t)()
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
@@ -139,11 +129,6 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) {
// Check that newly signed up users are redirected to accept the invitation correctly
func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) {
if setting.MailService == nil {
t.Skip()
return
}
defer tests.PrepareTestEnv(t)()
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
@@ -211,11 +196,6 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) {
// Check that users are redirected correctly after confirming their email
func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {
if setting.MailService == nil {
t.Skip()
return
}
// enable email confirmation temporarily
defer test.MockVariableValue(&setting.Service.RegisterEmailConfirm, true)()
defer tests.PrepareTestEnv(t)()
@@ -281,11 +261,6 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {
// For example: an invite may have been created before the user account was created, but they may be
// accepting the invite after having created an account separately
func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) {
if setting.MailService == nil {
t.Skip()
return
}
defer tests.PrepareTestEnv(t)()
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})

View File

@@ -104,13 +104,7 @@ func TestCreateReleaseDraft(t *testing.T) {
func TestCreateReleasePaging(t *testing.T) {
defer tests.PrepareTestEnv(t)()
oldAPIDefaultNum := setting.API.DefaultPagingNum
defer func() {
setting.API.DefaultPagingNum = oldAPIDefaultNum
}()
setting.API.DefaultPagingNum = 10
defer test.MockVariableValue(&setting.API.DefaultPagingNum, 10)()
session := loginUser(t, "user2")
// Create enough releases to have paging
for i := range 12 {

View File

@@ -10,6 +10,7 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
code_indexer "code.gitea.io/gitea/modules/indexer/code"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/PuerkitoBio/goquery"
@@ -35,8 +36,8 @@ func TestSearchRepo(t *testing.T) {
testSearch(t, "/user2/repo1/search?q=Description&page=1", []string{"README.md"})
setting.Indexer.IncludePatterns = setting.IndexerGlobFromString("**.txt")
setting.Indexer.ExcludePatterns = setting.IndexerGlobFromString("**/y/**")
defer test.MockVariableValue(&setting.Indexer.IncludePatterns, setting.IndexerGlobFromString("**.txt"))()
defer test.MockVariableValue(&setting.Indexer.ExcludePatterns, setting.IndexerGlobFromString("**/y/**"))()
repo, err = repo_model.GetRepositoryByOwnerAndName(t.Context(), "user2", "glob")
assert.NoError(t, err)

View File

@@ -133,13 +133,11 @@ func testViewRepoWithCache(t *testing.T) {
// no last commit cache
testView(t)
// enable last commit cache for all repositories
oldCommitsCount := setting.CacheService.LastCommit.CommitsCount
setting.CacheService.LastCommit.CommitsCount = 0
defer test.MockVariableValue(&setting.CacheService.LastCommit.CommitsCount, 0)()
// first view will not hit the cache
testView(t)
// second view will hit the cache
testView(t)
setting.CacheService.LastCommit.CommitsCount = oldCommitsCount
}
func testViewRepoPrivate(t *testing.T) {

View File

@@ -10,12 +10,13 @@ import (
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
)
func TestRepoWatch(t *testing.T) {
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
// Test round-trip auto-watch
setting.Service.AutoWatchOnChanges = true
defer test.MockVariableValue(&setting.Service.AutoWatchOnChanges, true)()
session := loginUser(t, "user2")
unittest.AssertNotExistsBean(t, &repo_model.Watch{UserID: 2, RepoID: 3})
testEditFile(t, session, "org3", "repo3", "master", "README.md", "Hello, World (Edited for watch)\n")

View File

@@ -16,9 +16,7 @@ import (
func TestSettingShowUserEmailExplore(t *testing.T) {
defer tests.PrepareTestEnv(t)()
showUserEmail := setting.UI.ShowUserEmail
setting.UI.ShowUserEmail = true
defer test.MockVariableValue(&setting.UI.ShowUserEmail, true)()
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/explore/users?sort=alphabetically")
@@ -38,8 +36,6 @@ func TestSettingShowUserEmailExplore(t *testing.T) {
htmlDoc.doc.Find(".explore.users").Text(),
"user34@example.com",
)
setting.UI.ShowUserEmail = showUserEmail
}
func TestSettingShowUserEmailProfile(t *testing.T) {

View File

@@ -9,6 +9,7 @@ import (
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
@@ -16,8 +17,7 @@ import (
func TestVersion(t *testing.T) {
defer tests.PrepareTestEnv(t)()
setting.AppVer = "test-version-1"
defer test.MockVariableValue(&setting.AppVer, "test-version-1")()
req := NewRequest(t, "GET", "/api/v1/version")
resp := MakeRequest(t, req, http.StatusOK)