Template
1
0
Fork 0
mirror of https://codeberg.org/forgejo/forgejo synced 2024-11-25 11:16:11 +01:00

Refactor tests (#26464)

1. Give the global variable clear names
2. Use generic parameter for `onGiteaRun`
This commit is contained in:
wxiaoguang 2023-08-13 00:30:16 +08:00 committed by GitHub
parent bcccf4c0d6
commit c28e29fd94
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
12 changed files with 65 additions and 127 deletions

View file

@ -208,8 +208,8 @@ func serveInstalled(ctx *cli.Context) error {
}
// Set up Chi routes
c := routers.NormalRoutes()
err := listen(c, true)
webRoutes := routers.NormalRoutes()
err := listen(webRoutes, true)
<-graceful.GetManager().Done()
log.Info("PID: %d Gitea Web Finished", os.Getpid())
log.GetManager().Close()

View file

@ -28,7 +28,7 @@ import (
"code.gitea.io/gitea/tests"
)
var c *web.Route
var testE2eWebRoutes *web.Route
func TestMain(m *testing.M) {
defer log.GetManager().Close()
@ -38,7 +38,7 @@ func TestMain(m *testing.M) {
defer cancel()
tests.InitTest(false)
c = routers.NormalRoutes()
testE2eWebRoutes = routers.NormalRoutes()
os.Unsetenv("GIT_AUTHOR_NAME")
os.Unsetenv("GIT_AUTHOR_EMAIL")

View file

@ -22,7 +22,7 @@ func onGiteaRunTB(t testing.TB, callback func(testing.TB, *url.URL), prepare ...
defer tests.PrepareTestEnv(t, 1)()
}
s := http.Server{
Handler: c,
Handler: testE2eWebRoutes,
}
u, err := url.Parse(setting.AppURL)

View file

@ -22,10 +22,10 @@ import (
func TestActivityPubPerson(t *testing.T) {
setting.Federation.Enabled = true
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
defer func() {
setting.Federation.Enabled = false
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
}()
onGiteaRun(t, func(*testing.T, *url.URL) {
@ -60,10 +60,10 @@ func TestActivityPubPerson(t *testing.T) {
func TestActivityPubMissingPerson(t *testing.T) {
setting.Federation.Enabled = true
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
defer func() {
setting.Federation.Enabled = false
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
}()
onGiteaRun(t, func(*testing.T, *url.URL) {
@ -75,13 +75,13 @@ func TestActivityPubMissingPerson(t *testing.T) {
func TestActivityPubPersonInbox(t *testing.T) {
setting.Federation.Enabled = true
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
defer func() {
setting.Federation.Enabled = false
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
}()
srv := httptest.NewServer(c)
srv := httptest.NewServer(testWebRoutes)
defer srv.Close()
onGiteaRun(t, func(*testing.T, *url.URL) {

View file

@ -17,10 +17,10 @@ import (
func TestNodeinfo(t *testing.T) {
setting.Federation.Enabled = true
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
defer func() {
setting.Federation.Enabled = false
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
}()
onGiteaRun(t, func(*testing.T, *url.URL) {

View file

@ -110,14 +110,14 @@ func getExpectedFileResponseForCreate(repoFullName, commitID, treePath, latestCo
}
func BenchmarkAPICreateFileSmall(b *testing.B) {
onGiteaRunTB(b, func(t testing.TB, u *url.URL) {
b := t.(*testing.B)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo
onGiteaRun(b, func(b *testing.B, u *url.URL) {
user2 := unittest.AssertExistsAndLoadBean(b, &user_model.User{ID: 2}) // owner of the repo1 & repo16
repo1 := unittest.AssertExistsAndLoadBean(b, &repo_model.Repository{ID: 1}) // public repo
b.ResetTimer()
for n := 0; n < b.N; n++ {
treePath := fmt.Sprintf("update/file%d.txt", n)
createFileInBranch(user2, repo1, treePath, repo1.DefaultBranch, treePath)
_, _ = createFileInBranch(user2, repo1, treePath, repo1.DefaultBranch, treePath)
}
})
}
@ -125,16 +125,15 @@ func BenchmarkAPICreateFileSmall(b *testing.B) {
func BenchmarkAPICreateFileMedium(b *testing.B) {
data := make([]byte, 10*1024*1024)
onGiteaRunTB(b, func(t testing.TB, u *url.URL) {
b := t.(*testing.B)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo1 & repo16
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) // public repo
onGiteaRun(b, func(b *testing.B, u *url.URL) {
user2 := unittest.AssertExistsAndLoadBean(b, &user_model.User{ID: 2}) // owner of the repo1 & repo16
repo1 := unittest.AssertExistsAndLoadBean(b, &repo_model.Repository{ID: 1}) // public repo
b.ResetTimer()
for n := 0; n < b.N; n++ {
treePath := fmt.Sprintf("update/file%d.txt", n)
copy(data, treePath)
createFileInBranch(user2, repo1, treePath, repo1.DefaultBranch, treePath)
_, _ = createFileInBranch(user2, repo1, treePath, repo1.DefaultBranch, treePath)
}
})
}

View file

@ -24,9 +24,7 @@ func StringWithCharset(length int, charset string) string {
}
func BenchmarkRepoBranchCommit(b *testing.B) {
onGiteaRunTB(b, func(t testing.TB, u *url.URL) {
b := t.(*testing.B)
onGiteaRun(b, func(b *testing.B, u *url.URL) {
samples := []int64{1, 2, 3}
b.ResetTimer()

View file

@ -56,7 +56,7 @@ func TestSessionFileCreation(t *testing.T) {
oldSessionConfig := setting.SessionConfig.ProviderConfig
defer func() {
setting.SessionConfig.ProviderConfig = oldSessionConfig
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
}()
var config session.Options
@ -75,7 +75,7 @@ func TestSessionFileCreation(t *testing.T) {
setting.SessionConfig.ProviderConfig = string(newConfigBytes)
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
t.Run("NoSessionOnViewIssue", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()

View file

@ -57,12 +57,10 @@ func createSSHUrl(gitPath string, u *url.URL) *url.URL {
return &u2
}
func onGiteaRunTB(t testing.TB, callback func(testing.TB, *url.URL), prepare ...bool) {
if len(prepare) == 0 || prepare[0] {
func onGiteaRun[T testing.TB](t T, callback func(T, *url.URL)) {
defer tests.PrepareTestEnv(t, 1)()
}
s := http.Server{
Handler: c,
Handler: testWebRoutes,
}
u, err := url.Parse(setting.AppURL)
@ -89,12 +87,6 @@ func onGiteaRunTB(t testing.TB, callback func(testing.TB, *url.URL), prepare ...
callback(t, u)
}
func onGiteaRun(t *testing.T, callback func(*testing.T, *url.URL), prepare ...bool) {
onGiteaRunTB(t, func(t testing.TB, u *url.URL) {
callback(t.(*testing.T), u)
}, prepare...)
}
func doGitClone(dstLocalPath string, u *url.URL) func(*testing.T) {
return func(t *testing.T) {
assert.NoError(t, git.CloneWithArgs(context.Background(), git.AllowLFSFiltersArgs(), u.String(), dstLocalPath, git.CloneRepoOptions{}))

View file

@ -16,6 +16,7 @@ import (
"code.gitea.io/gitea/modules/process"
"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"
@ -24,12 +25,7 @@ import (
)
func TestGPGGit(t *testing.T) {
defer tests.PrepareTestEnv(t)()
username := "user2"
// OK Set a new GPG home
tmpDir := t.TempDir()
tmpDir := t.TempDir() // use a temp dir to avoid messing with the user's GPG keyring
err := os.Chmod(tmpDir, 0o700)
assert.NoError(t, err)
@ -40,31 +36,20 @@ func TestGPGGit(t *testing.T) {
// Need to create a root key
rootKeyPair, err := importTestingKey(tmpDir, "gitea", "gitea@fake.local")
assert.NoError(t, err)
if err != nil {
assert.FailNow(t, "Unable to import rootKeyPair")
if !assert.NoError(t, err, "importTestingKey") {
return
}
rootKeyID := rootKeyPair.PrimaryKey.KeyIdShortString()
defer test.MockVariableValue(&setting.Repository.Signing.SigningKey, rootKeyPair.PrimaryKey.KeyIdShortString())()
defer test.MockVariableValue(&setting.Repository.Signing.SigningName, "gitea")()
defer test.MockVariableValue(&setting.Repository.Signing.SigningEmail, "gitea@fake.local")()
defer test.MockVariableValue(&setting.Repository.Signing.InitialCommit, []string{"never"})()
defer test.MockVariableValue(&setting.Repository.Signing.CRUDActions, []string{"never"})()
oldKeyID := setting.Repository.Signing.SigningKey
oldName := setting.Repository.Signing.SigningName
oldEmail := setting.Repository.Signing.SigningEmail
defer func() {
setting.Repository.Signing.SigningKey = oldKeyID
setting.Repository.Signing.SigningName = oldName
setting.Repository.Signing.SigningEmail = oldEmail
}()
setting.Repository.Signing.SigningKey = rootKeyID
setting.Repository.Signing.SigningName = "gitea"
setting.Repository.Signing.SigningEmail = "gitea@fake.local"
username := "user2"
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: username})
setting.Repository.Signing.InitialCommit = []string{"never"}
setting.Repository.Signing.CRUDActions = []string{"never"}
baseAPITestContext := NewAPITestContext(t, username, "repo1")
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
@ -87,11 +72,8 @@ func TestGPGGit(t *testing.T) {
assert.False(t, response.Verification.Verified)
}))
})
}, false)
setting.Repository.Signing.CRUDActions = []string{"parentsigned"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
setting.Repository.Signing.CRUDActions = []string{"parentsigned"}
t.Run("Unsigned-Initial-CRUD-ParentSigned", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
@ -104,11 +86,8 @@ func TestGPGGit(t *testing.T) {
assert.False(t, response.Verification.Verified)
}))
})
}, false)
setting.Repository.Signing.CRUDActions = []string{"never"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
setting.Repository.Signing.CRUDActions = []string{"never"}
t.Run("Unsigned-Initial-CRUD-Never", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
@ -117,11 +96,8 @@ func TestGPGGit(t *testing.T) {
assert.False(t, response.Verification.Verified)
}))
})
}, false)
setting.Repository.Signing.CRUDActions = []string{"always"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
setting.Repository.Signing.CRUDActions = []string{"always"}
t.Run("Unsigned-Initial-CRUD-Always", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
@ -154,11 +130,8 @@ func TestGPGGit(t *testing.T) {
assert.Equal(t, "gitea@fake.local", response.Verification.Signer.Email)
}))
})
}, false)
setting.Repository.Signing.CRUDActions = []string{"parentsigned"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
setting.Repository.Signing.CRUDActions = []string{"parentsigned"}
t.Run("Unsigned-Initial-CRUD-ParentSigned", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
@ -177,11 +150,8 @@ func TestGPGGit(t *testing.T) {
assert.Equal(t, "gitea@fake.local", response.Verification.Signer.Email)
}))
})
}, false)
setting.Repository.Signing.InitialCommit = []string{"always"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
setting.Repository.Signing.InitialCommit = []string{"always"}
t.Run("AlwaysSign-Initial", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-always", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
@ -205,11 +175,8 @@ func TestGPGGit(t *testing.T) {
assert.Equal(t, "gitea@fake.local", branch.Commit.Verification.Signer.Email)
}))
})
}, false)
setting.Repository.Signing.CRUDActions = []string{"never"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
setting.Repository.Signing.CRUDActions = []string{"never"}
t.Run("AlwaysSign-Initial-CRUD-Never", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-always-never", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
@ -219,10 +186,8 @@ func TestGPGGit(t *testing.T) {
assert.False(t, response.Verification.Verified)
}))
})
}, false)
setting.Repository.Signing.CRUDActions = []string{"parentsigned"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
t.Run("AlwaysSign-Initial-CRUD-ParentSigned-On-Always", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-always-parent", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
@ -237,11 +202,8 @@ func TestGPGGit(t *testing.T) {
assert.Equal(t, "gitea@fake.local", response.Verification.Signer.Email)
}))
})
}, false)
setting.Repository.Signing.CRUDActions = []string{"always"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
setting.Repository.Signing.CRUDActions = []string{"always"}
t.Run("AlwaysSign-Initial-CRUD-Always", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-always-always", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
@ -256,21 +218,16 @@ func TestGPGGit(t *testing.T) {
assert.Equal(t, "gitea@fake.local", response.Verification.Signer.Email)
}))
})
}, false)
var pr api.PullRequest
setting.Repository.Signing.Merges = []string{"commitssigned"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
setting.Repository.Signing.Merges = []string{"commitssigned"}
t.Run("UnsignedMerging", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
var err error
t.Run("CreatePullRequest", func(t *testing.T) {
pr, err = doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "never2")(t)
pr, err := doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "never2")(t)
assert.NoError(t, err)
})
t.Run("MergePR", doAPIMergePullRequest(testCtx, testCtx.Username, testCtx.Reponame, pr.Index))
})
t.Run("CheckMasterBranchUnsigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) {
assert.NotNil(t, branch.Commit)
assert.NotNil(t, branch.Commit.Verification)
@ -278,20 +235,16 @@ func TestGPGGit(t *testing.T) {
assert.Empty(t, branch.Commit.Verification.Signature)
}))
})
}, false)
setting.Repository.Signing.Merges = []string{"basesigned"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
setting.Repository.Signing.Merges = []string{"basesigned"}
t.Run("BaseSignedMerging", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
var err error
t.Run("CreatePullRequest", func(t *testing.T) {
pr, err = doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "parentsigned2")(t)
pr, err := doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "parentsigned2")(t)
assert.NoError(t, err)
})
t.Run("MergePR", doAPIMergePullRequest(testCtx, testCtx.Username, testCtx.Reponame, pr.Index))
})
t.Run("CheckMasterBranchUnsigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) {
assert.NotNil(t, branch.Commit)
assert.NotNil(t, branch.Commit.Verification)
@ -299,27 +252,23 @@ func TestGPGGit(t *testing.T) {
assert.Empty(t, branch.Commit.Verification.Signature)
}))
})
}, false)
setting.Repository.Signing.Merges = []string{"commitssigned"}
onGiteaRun(t, func(t *testing.T, u *url.URL) {
u.Path = baseAPITestContext.GitPath()
setting.Repository.Signing.Merges = []string{"commitssigned"}
t.Run("CommitsSignedMerging", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser)
var err error
t.Run("CreatePullRequest", func(t *testing.T) {
pr, err = doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "always-parentsigned")(t)
pr, err := doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "always-parentsigned")(t)
assert.NoError(t, err)
})
t.Run("MergePR", doAPIMergePullRequest(testCtx, testCtx.Username, testCtx.Reponame, pr.Index))
})
t.Run("CheckMasterBranchUnsigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) {
assert.NotNil(t, branch.Commit)
assert.NotNil(t, branch.Commit.Verification)
assert.True(t, branch.Commit.Verification.Verified)
}))
})
}, false)
})
}
func crudActionCreateFile(t *testing.T, ctx APITestContext, user *user_model.User, from, to, path string, callback ...func(*testing.T, api.FileResponse)) func(*testing.T) {

View file

@ -40,7 +40,7 @@ import (
"github.com/xeipuuv/gojsonschema"
)
var c *web.Route
var testWebRoutes *web.Route
type NilResponseRecorder struct {
httptest.ResponseRecorder
@ -87,7 +87,7 @@ func TestMain(m *testing.M) {
defer cancel()
tests.InitTest(true)
c = routers.NormalRoutes()
testWebRoutes = routers.NormalRoutes()
// integration test settings...
if setting.CfgProvider != nil {
@ -374,7 +374,7 @@ func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.
if req.RemoteAddr == "" {
req.RemoteAddr = "test-mock:12345"
}
c.ServeHTTP(recorder, req)
testWebRoutes.ServeHTTP(recorder, req)
if expectedStatus != NoExpectedStatus {
if !assert.EqualValues(t, expectedStatus, recorder.Code, "Request: %s %s", req.Method, req.URL.String()) {
logUnexpectedResponse(t, recorder)
@ -386,7 +386,7 @@ func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.
func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
t.Helper()
recorder := NewNilResponseRecorder()
c.ServeHTTP(recorder, req)
testWebRoutes.ServeHTTP(recorder, req)
if expectedStatus != NoExpectedStatus {
if !assert.EqualValues(t, expectedStatus, recorder.Code,
"Request: %s %s", req.Method, req.URL.String()) {
@ -399,7 +399,7 @@ func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedSta
func MakeRequestNilResponseHashSumRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseHashSumRecorder {
t.Helper()
recorder := NewNilResponseHashSumRecorder()
c.ServeHTTP(recorder, req)
testWebRoutes.ServeHTTP(recorder, req)
if expectedStatus != NoExpectedStatus {
if !assert.EqualValues(t, expectedStatus, recorder.Code,
"Request: %s %s", req.Method, req.URL.String()) {

View file

@ -181,7 +181,7 @@ func InitTest(requireGitea bool) {
func PrepareTestEnv(t testing.TB, skip ...int) func() {
t.Helper()
ourSkip := 2
ourSkip := 1
if len(skip) > 0 {
ourSkip += skip[0]
}