diff --git a/cmd/docs.go b/cmd/docs.go index 52233c7ac872..073c57497305 100644 --- a/cmd/docs.go +++ b/cmd/docs.go @@ -43,7 +43,11 @@ func runDocs(ctx *cli.Context) error { // Clean up markdown. The following bug was fixed in v2, but is present in v1. // It affects markdown output (even though the issue is referring to man pages) // https://github.com/urfave/cli/issues/1040 - docs = docs[strings.Index(docs, "#"):] + firstHashtagIndex := strings.Index(docs, "#") + + if firstHashtagIndex > 0 { + docs = docs[firstHashtagIndex:] + } } out := os.Stdout diff --git a/cmd/dump_repo.go b/cmd/dump_repo.go index 6274b4d86543..31f4574c2d53 100644 --- a/cmd/dump_repo.go +++ b/cmd/dump_repo.go @@ -11,10 +11,10 @@ import ( "code.gitea.io/gitea/modules/convert" "code.gitea.io/gitea/modules/log" - "code.gitea.io/gitea/modules/migrations" - "code.gitea.io/gitea/modules/migrations/base" + base "code.gitea.io/gitea/modules/migration" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" + "code.gitea.io/gitea/services/migrations" "github.com/urfave/cli" ) diff --git a/contrib/fixtures/fixture_generation.go b/contrib/fixtures/fixture_generation.go index 5e7dd39a78fb..74996a1f3599 100644 --- a/contrib/fixtures/fixture_generation.go +++ b/contrib/fixtures/fixture_generation.go @@ -10,7 +10,7 @@ import ( "path/filepath" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) // To generate derivative fixtures, execute the following from Gitea's repository base dir: @@ -31,13 +31,13 @@ var ( func main() { pathToGiteaRoot := "." fixturesDir = filepath.Join(pathToGiteaRoot, "models", "fixtures") - if err := db.CreateTestEngine(db.FixturesOptions{ + if err := unittest.CreateTestEngine(unittest.FixturesOptions{ Dir: fixturesDir, }); err != nil { fmt.Printf("CreateTestEngine: %+v", err) os.Exit(1) } - if err := db.PrepareTestDatabase(); err != nil { + if err := unittest.PrepareTestDatabase(); err != nil { fmt.Printf("PrepareTestDatabase: %+v\n", err) os.Exit(1) } diff --git a/contrib/pr/checkout.go b/contrib/pr/checkout.go index 89d92c852612..1e2a9714e38a 100644 --- a/contrib/pr/checkout.go +++ b/contrib/pr/checkout.go @@ -26,6 +26,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" gitea_git "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/markup" "code.gitea.io/gitea/modules/markup/external" @@ -99,8 +100,8 @@ func runPR() { }) db.HasEngine = true //x.ShowSQL(true) - err = db.InitFixtures( - db.FixturesOptions{ + err = unittest.InitFixtures( + unittest.FixturesOptions{ Dir: path.Join(curDir, "models/fixtures/"), }, ) @@ -108,7 +109,7 @@ func runPR() { fmt.Printf("Error initializing test database: %v\n", err) os.Exit(1) } - db.LoadFixtures() + unittest.LoadFixtures() util.RemoveAll(setting.RepoRootPath) util.RemoveAll(models.LocalCopyPath()) util.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath) diff --git a/docs/content/doc/developers/guidelines-frontend.md b/docs/content/doc/developers/guidelines-frontend.md index f30b0d1cbd88..c937cfb7b4dd 100644 --- a/docs/content/doc/developers/guidelines-frontend.md +++ b/docs/content/doc/developers/guidelines-frontend.md @@ -39,6 +39,65 @@ We recommend [Google HTML/CSS Style Guide](https://google.github.io/styleguide/h 6. The backend can pass complex data to the frontend by using `ctx.PageData["myModuleData"] = map[]{}` 7. Simple pages and SEO-related pages use Go HTML Template render to generate static Fomantic-UI HTML output. Complex pages can use Vue2 (or Vue3 in future). + +### `async` Functions + +Only mark a function as `async` if and only if there are `await` calls +or `Promise` returns inside the function. + +It's not recommended to use `async` event listeners, which may lead to problems. +The reason is that the code after await is executed outside the event dispatch. +Reference: https://github.com/github/eslint-plugin-github/blob/main/docs/rules/async-preventdefault.md + +If we want to call an `async` function in a non-async context, +it's recommended to use `const _promise = asyncFoo()` to tell readers +that this is done by purpose, we want to call the async function and ignore the Promise. +Some lint rules and IDEs also have warnings if the returned Promise is not handled. + +#### DOM Event Listener + +```js +el.addEventListener('click', (e) => { + (async () => { + await asyncFoo(); // recommended + // then we shound't do e.preventDefault() after await, no effect + })(); + + const _promise = asyncFoo(); // recommended + + e.preventDefault(); // correct +}); + +el.addEventListener('async', async (e) => { // not recommended but acceptable + e.preventDefault(); // acceptable + await asyncFoo(); // skip out event dispath + e.preventDefault(); // WRONG +}); +``` + +#### jQuery Event Listener + +```js +$('#el').on('click', (e) => { + (async () => { + await asyncFoo(); // recommended + // then we shound't do e.preventDefault() after await, no effect + })(); + + const _promise = asyncFoo(); // recommended + + e.preventDefault(); // correct + return false; // correct +}); + +$('#el').on('click', async (e) => { // not recommended but acceptable + e.preventDefault(); // acceptable + return false; // WRONG, jQuery expects the returned value is a boolean, not a Promise + await asyncFoo(); // skip out event dispath + return false; // WRONG +}); +``` + ### Vue2/Vue3 and JSX Gitea is using Vue2 now, we plan to upgrade to Vue3. We decided not to introduce JSX to keep the HTML and the JavaScript code separated. diff --git a/docs/content/doc/installation/with-docker-rootless.en-us.md b/docs/content/doc/installation/with-docker-rootless.en-us.md index 12aad592c823..896ef5aebbbc 100644 --- a/docs/content/doc/installation/with-docker-rootless.en-us.md +++ b/docs/content/doc/installation/with-docker-rootless.en-us.md @@ -168,7 +168,9 @@ named volumes; Docker will deal with that automatically. version: "2" +volumes: -+ gitea: ++ gitea-data: ++ driver: local ++ gitea-config: + driver: local + services: diff --git a/integrations/admin_user_test.go b/integrations/admin_user_test.go index 3acf3490410a..f9e9afac34c0 100644 --- a/integrations/admin_user_test.go +++ b/integrations/admin_user_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) @@ -61,7 +61,7 @@ func makeRequest(t *testing.T, formData models.User, headerCode int) { }) session.MakeRequest(t, req, headerCode) - user := db.AssertExistsAndLoadBean(t, &models.User{ID: formData.ID}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: formData.ID}).(*models.User) assert.Equal(t, formData.Name, user.Name) assert.Equal(t, formData.LoginName, user.LoginName) assert.Equal(t, formData.Email, user.Email) @@ -79,5 +79,5 @@ func TestAdminDeleteUser(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) assertUserDeleted(t, 8) - models.CheckConsistencyFor(t, &models.User{}) + unittest.CheckConsistencyFor(t, &models.User{}) } diff --git a/integrations/api_admin_org_test.go b/integrations/api_admin_org_test.go index 7b149a38d548..a4ef0ed5ef36 100644 --- a/integrations/api_admin_org_test.go +++ b/integrations/api_admin_org_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -43,7 +43,7 @@ func TestAPIAdminOrgCreate(t *testing.T) { assert.Equal(t, org.Location, apiOrg.Location) assert.Equal(t, org.Visibility, apiOrg.Visibility) - db.AssertExistsAndLoadBean(t, &models.User{ + unittest.AssertExistsAndLoadBean(t, &models.User{ Name: org.UserName, LowerName: strings.ToLower(org.UserName), FullName: org.FullName, diff --git a/integrations/api_admin_test.go b/integrations/api_admin_test.go index ae3cc7dcfb01..86a3784b175a 100644 --- a/integrations/api_admin_test.go +++ b/integrations/api_admin_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" @@ -21,7 +21,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { defer prepareTestEnv(t)() // user1 is an admin user session := loginUser(t, "user1") - keyOwner := db.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User) + keyOwner := unittest.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User) token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/admin/users/%s/keys?token=%s", keyOwner.Name, token) @@ -33,7 +33,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { var newPublicKey api.PublicKey DecodeJSON(t, resp, &newPublicKey) - db.AssertExistsAndLoadBean(t, &models.PublicKey{ + unittest.AssertExistsAndLoadBean(t, &models.PublicKey{ ID: newPublicKey.ID, Name: newPublicKey.Title, Content: newPublicKey.Key, @@ -44,7 +44,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) { req = NewRequestf(t, "DELETE", "/api/v1/admin/users/%s/keys/%d?token=%s", keyOwner.Name, newPublicKey.ID, token) session.MakeRequest(t, req, http.StatusNoContent) - db.AssertNotExistsBean(t, &models.PublicKey{ID: newPublicKey.ID}) + unittest.AssertNotExistsBean(t, &models.PublicKey{ID: newPublicKey.ID}) } func TestAPIAdminDeleteMissingSSHKey(t *testing.T) { @@ -53,7 +53,7 @@ func TestAPIAdminDeleteMissingSSHKey(t *testing.T) { session := loginUser(t, "user1") token := getTokenForLoggedInUser(t, session) - req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d?token=%s", db.NonexistentID, token) + req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d?token=%s", unittest.NonexistentID, token) session.MakeRequest(t, req, http.StatusNotFound) } @@ -128,7 +128,7 @@ func TestAPIListUsers(t *testing.T) { } } assert.True(t, found) - numberOfUsers := db.GetCount(t, &models.User{}, "type = 0") + numberOfUsers := unittest.GetCount(t, &models.User{}, "type = 0") assert.Equal(t, numberOfUsers, len(users)) } @@ -194,7 +194,7 @@ func TestAPIEditUser(t *testing.T) { json.Unmarshal(resp.Body.Bytes(), &errMap) assert.EqualValues(t, "email is not allowed to be empty string", errMap["message"].(string)) - user2 := db.AssertExistsAndLoadBean(t, &models.User{LoginName: "user2"}).(*models.User) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{LoginName: "user2"}).(*models.User) assert.False(t, user2.IsRestricted) bTrue := true req = NewRequestWithJSON(t, "PATCH", urlStr, api.EditUserOption{ @@ -205,6 +205,6 @@ func TestAPIEditUser(t *testing.T) { Restricted: &bTrue, }) session.MakeRequest(t, req, http.StatusOK) - user2 = db.AssertExistsAndLoadBean(t, &models.User{LoginName: "user2"}).(*models.User) + user2 = unittest.AssertExistsAndLoadBean(t, &models.User{LoginName: "user2"}).(*models.User) assert.True(t, user2.IsRestricted) } diff --git a/integrations/api_comment_test.go b/integrations/api_comment_test.go index a5513af6e300..6f8c5a85bda0 100644 --- a/integrations/api_comment_test.go +++ b/integrations/api_comment_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/convert" api "code.gitea.io/gitea/modules/structs" @@ -21,11 +21,11 @@ import ( func TestAPIListRepoComments(t *testing.T) { defer prepareTestEnv(t)() - comment := db.AssertExistsAndLoadBean(t, &models.Comment{}, - db.Cond("type = ?", models.CommentTypeComment)).(*models.Comment) - issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) - repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{}, + unittest.Cond("type = ?", models.CommentTypeComment)).(*models.Comment) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) + repoOwner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments", repoOwner.Name, repo.Name)) @@ -37,9 +37,9 @@ func TestAPIListRepoComments(t *testing.T) { assert.Len(t, apiComments, 2) for _, apiComment := range apiComments { c := &models.Comment{ID: apiComment.ID} - db.AssertExistsAndLoadBean(t, c, - db.Cond("type = ?", models.CommentTypeComment)) - db.AssertExistsAndLoadBean(t, &models.Issue{ID: c.IssueID, RepoID: repo.ID}) + unittest.AssertExistsAndLoadBean(t, c, + unittest.Cond("type = ?", models.CommentTypeComment)) + unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: c.IssueID, RepoID: repo.ID}) } //test before and since filters @@ -67,11 +67,11 @@ func TestAPIListRepoComments(t *testing.T) { func TestAPIListIssueComments(t *testing.T) { defer prepareTestEnv(t)() - comment := db.AssertExistsAndLoadBean(t, &models.Comment{}, - db.Cond("type = ?", models.CommentTypeComment)).(*models.Comment) - issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) - repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{}, + unittest.Cond("type = ?", models.CommentTypeComment)).(*models.Comment) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) + repoOwner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments", @@ -80,8 +80,8 @@ func TestAPIListIssueComments(t *testing.T) { var comments []*api.Comment DecodeJSON(t, resp, &comments) - expectedCount := db.GetCount(t, &models.Comment{IssueID: issue.ID}, - db.Cond("type = ?", models.CommentTypeComment)) + expectedCount := unittest.GetCount(t, &models.Comment{IssueID: issue.ID}, + unittest.Cond("type = ?", models.CommentTypeComment)) assert.EqualValues(t, expectedCount, len(comments)) } @@ -89,9 +89,9 @@ func TestAPICreateComment(t *testing.T) { defer prepareTestEnv(t)() const commentBody = "Comment body" - issue := db.AssertExistsAndLoadBean(t, &models.Issue{}).(*models.Issue) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) - repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{}).(*models.Issue) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) + repoOwner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session) @@ -105,16 +105,16 @@ func TestAPICreateComment(t *testing.T) { var updatedComment api.Comment DecodeJSON(t, resp, &updatedComment) assert.EqualValues(t, commentBody, updatedComment.Body) - db.AssertExistsAndLoadBean(t, &models.Comment{ID: updatedComment.ID, IssueID: issue.ID, Content: commentBody}) + unittest.AssertExistsAndLoadBean(t, &models.Comment{ID: updatedComment.ID, IssueID: issue.ID, Content: commentBody}) } func TestAPIGetComment(t *testing.T) { defer prepareTestEnv(t)() - comment := db.AssertExistsAndLoadBean(t, &models.Comment{ID: 2}).(*models.Comment) + comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{ID: 2}).(*models.Comment) assert.NoError(t, comment.LoadIssue()) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: comment.Issue.RepoID}).(*models.Repository) - repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: comment.Issue.RepoID}).(*models.Repository) + repoOwner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session) @@ -139,11 +139,11 @@ func TestAPIEditComment(t *testing.T) { defer prepareTestEnv(t)() const newCommentBody = "This is the new comment body" - comment := db.AssertExistsAndLoadBean(t, &models.Comment{}, - db.Cond("type = ?", models.CommentTypeComment)).(*models.Comment) - issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) - repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{}, + unittest.Cond("type = ?", models.CommentTypeComment)).(*models.Comment) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) + repoOwner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session) @@ -158,17 +158,17 @@ func TestAPIEditComment(t *testing.T) { DecodeJSON(t, resp, &updatedComment) assert.EqualValues(t, comment.ID, updatedComment.ID) assert.EqualValues(t, newCommentBody, updatedComment.Body) - db.AssertExistsAndLoadBean(t, &models.Comment{ID: comment.ID, IssueID: issue.ID, Content: newCommentBody}) + unittest.AssertExistsAndLoadBean(t, &models.Comment{ID: comment.ID, IssueID: issue.ID, Content: newCommentBody}) } func TestAPIDeleteComment(t *testing.T) { defer prepareTestEnv(t)() - comment := db.AssertExistsAndLoadBean(t, &models.Comment{}, - db.Cond("type = ?", models.CommentTypeComment)).(*models.Comment) - issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) - repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{}, + unittest.Cond("type = ?", models.CommentTypeComment)).(*models.Comment) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) + repoOwner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session) @@ -176,5 +176,5 @@ func TestAPIDeleteComment(t *testing.T) { repoOwner.Name, repo.Name, comment.ID, token) session.MakeRequest(t, req, http.StatusNoContent) - db.AssertNotExistsBean(t, &models.Comment{ID: comment.ID}) + unittest.AssertNotExistsBean(t, &models.Comment{ID: comment.ID}) } diff --git a/integrations/api_issue_label_test.go b/integrations/api_issue_label_test.go index 4508069e1764..7cb5df812b72 100644 --- a/integrations/api_issue_label_test.go +++ b/integrations/api_issue_label_test.go @@ -10,18 +10,19 @@ import ( "strings" "testing" + "code.gitea.io/gitea/models/unittest" + "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" ) func TestAPIModifyLabels(t *testing.T) { - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/labels?token=%s", owner.Name, repo.Name, token) @@ -35,7 +36,7 @@ func TestAPIModifyLabels(t *testing.T) { resp := session.MakeRequest(t, req, http.StatusCreated) apiLabel := new(api.Label) DecodeJSON(t, resp, &apiLabel) - dbLabel := db.AssertExistsAndLoadBean(t, &models.Label{ID: apiLabel.ID, RepoID: repo.ID}).(*models.Label) + dbLabel := unittest.AssertExistsAndLoadBean(t, &models.Label{ID: apiLabel.ID, RepoID: repo.ID}).(*models.Label) assert.EqualValues(t, dbLabel.Name, apiLabel.Name) assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color) @@ -88,12 +89,12 @@ func TestAPIModifyLabels(t *testing.T) { } func TestAPIAddIssueLabels(t *testing.T) { - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - issue := db.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repo.ID}).(*models.Issue) - _ = db.AssertExistsAndLoadBean(t, &models.Label{RepoID: repo.ID, ID: 2}).(*models.Label) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repo.ID}).(*models.Issue) + _ = unittest.AssertExistsAndLoadBean(t, &models.Label{RepoID: repo.ID, ID: 2}).(*models.Label) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) @@ -105,18 +106,18 @@ func TestAPIAddIssueLabels(t *testing.T) { resp := session.MakeRequest(t, req, http.StatusOK) var apiLabels []*api.Label DecodeJSON(t, resp, &apiLabels) - assert.Len(t, apiLabels, db.GetCount(t, &models.IssueLabel{IssueID: issue.ID})) + assert.Len(t, apiLabels, unittest.GetCount(t, &models.IssueLabel{IssueID: issue.ID})) - db.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: issue.ID, LabelID: 2}) + unittest.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: issue.ID, LabelID: 2}) } func TestAPIReplaceIssueLabels(t *testing.T) { - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - issue := db.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repo.ID}).(*models.Issue) - label := db.AssertExistsAndLoadBean(t, &models.Label{RepoID: repo.ID}).(*models.Label) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repo.ID}).(*models.Issue) + label := unittest.AssertExistsAndLoadBean(t, &models.Label{RepoID: repo.ID}).(*models.Label) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) @@ -132,15 +133,15 @@ func TestAPIReplaceIssueLabels(t *testing.T) { assert.EqualValues(t, label.ID, apiLabels[0].ID) } - db.AssertCount(t, &models.IssueLabel{IssueID: issue.ID}, 1) - db.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: issue.ID, LabelID: label.ID}) + unittest.AssertCount(t, &models.IssueLabel{IssueID: issue.ID}, 1) + unittest.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: issue.ID, LabelID: label.ID}) } func TestAPIModifyOrgLabels(t *testing.T) { - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) user := "user1" session := loginUser(t, user) token := getTokenForLoggedInUser(t, session) @@ -155,7 +156,7 @@ func TestAPIModifyOrgLabels(t *testing.T) { resp := session.MakeRequest(t, req, http.StatusCreated) apiLabel := new(api.Label) DecodeJSON(t, resp, &apiLabel) - dbLabel := db.AssertExistsAndLoadBean(t, &models.Label{ID: apiLabel.ID, OrgID: owner.ID}).(*models.Label) + dbLabel := unittest.AssertExistsAndLoadBean(t, &models.Label{ID: apiLabel.ID, OrgID: owner.ID}).(*models.Label) assert.EqualValues(t, dbLabel.Name, apiLabel.Name) assert.EqualValues(t, strings.TrimLeft(dbLabel.Color, "#"), apiLabel.Color) diff --git a/integrations/api_issue_milestone_test.go b/integrations/api_issue_milestone_test.go index ba4ada12136f..233d8ef33c71 100644 --- a/integrations/api_issue_milestone_test.go +++ b/integrations/api_issue_milestone_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -19,9 +19,9 @@ import ( func TestAPIIssuesMilestone(t *testing.T) { defer prepareTestEnv(t)() - milestone := db.AssertExistsAndLoadBean(t, &models.Milestone{ID: 1}).(*models.Milestone) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: milestone.RepoID}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + milestone := unittest.AssertExistsAndLoadBean(t, &models.Milestone{ID: 1}).(*models.Milestone) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: milestone.RepoID}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) assert.Equal(t, int64(1), int64(milestone.NumIssues)) assert.Equal(t, structs.StateOpen, milestone.State()) diff --git a/integrations/api_issue_reaction_test.go b/integrations/api_issue_reaction_test.go index d064f488545b..4591f8fa8c57 100644 --- a/integrations/api_issue_reaction_test.go +++ b/integrations/api_issue_reaction_test.go @@ -11,7 +11,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/convert" api "code.gitea.io/gitea/modules/structs" @@ -21,14 +21,14 @@ import ( func TestAPIIssuesReactions(t *testing.T) { defer prepareTestEnv(t)() - issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue) _ = issue.LoadRepo() - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/reactions?token=%s", owner.Name, issue.Repo.Name, issue.Index, token) @@ -78,17 +78,17 @@ func TestAPIIssuesReactions(t *testing.T) { func TestAPICommentReactions(t *testing.T) { defer prepareTestEnv(t)() - comment := db.AssertExistsAndLoadBean(t, &models.Comment{ID: 2}).(*models.Comment) + comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{ID: 2}).(*models.Comment) _ = comment.LoadIssue() issue := comment.Issue _ = issue.LoadRepo() - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) - user1 := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user1 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/reactions?token=%s", owner.Name, issue.Repo.Name, comment.ID, token) diff --git a/integrations/api_issue_stopwatch_test.go b/integrations/api_issue_stopwatch_test.go index 8ccd79f691e0..92822ed8117b 100644 --- a/integrations/api_issue_stopwatch_test.go +++ b/integrations/api_issue_stopwatch_test.go @@ -9,7 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -18,8 +18,8 @@ import ( func TestAPIListStopWatches(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) @@ -27,8 +27,8 @@ func TestAPIListStopWatches(t *testing.T) { resp := session.MakeRequest(t, req, http.StatusOK) var apiWatches []*api.StopWatch DecodeJSON(t, resp, &apiWatches) - stopwatch := db.AssertExistsAndLoadBean(t, &models.Stopwatch{UserID: owner.ID}).(*models.Stopwatch) - issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: stopwatch.IssueID}).(*models.Issue) + stopwatch := unittest.AssertExistsAndLoadBean(t, &models.Stopwatch{UserID: owner.ID}).(*models.Stopwatch) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: stopwatch.IssueID}).(*models.Issue) if assert.Len(t, apiWatches, 1) { assert.EqualValues(t, stopwatch.CreatedUnix.AsTime().Unix(), apiWatches[0].Created.Unix()) assert.EqualValues(t, issue.Index, apiWatches[0].IssueIndex) @@ -42,10 +42,10 @@ func TestAPIListStopWatches(t *testing.T) { func TestAPIStopStopWatches(t *testing.T) { defer prepareTestEnv(t)() - issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) _ = issue.LoadRepo() - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User) - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -58,10 +58,10 @@ func TestAPIStopStopWatches(t *testing.T) { func TestAPICancelStopWatches(t *testing.T) { defer prepareTestEnv(t)() - issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue) _ = issue.LoadRepo() - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User) - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -74,10 +74,10 @@ func TestAPICancelStopWatches(t *testing.T) { func TestAPIStartStopWatches(t *testing.T) { defer prepareTestEnv(t)() - issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue) _ = issue.LoadRepo() - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User) - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_issue_subscription_test.go b/integrations/api_issue_subscription_test.go index 30c307661140..dd8e4311496c 100644 --- a/integrations/api_issue_subscription_test.go +++ b/integrations/api_issue_subscription_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -19,20 +19,20 @@ import ( func TestAPIIssueSubscriptions(t *testing.T) { defer prepareTestEnv(t)() - issue1 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue) - issue2 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) - issue3 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue) - issue4 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 4}).(*models.Issue) - issue5 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 8}).(*models.Issue) + issue1 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue) + issue2 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) + issue3 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue) + issue4 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 4}).(*models.Issue) + issue5 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 8}).(*models.Issue) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue1.PosterID}).(*models.User) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: issue1.PosterID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) testSubscription := func(issue *models.Issue, isWatching bool) { - issueRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) + issueRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/check?token=%s", issueRepo.OwnerName, issueRepo.Name, issue.Index, token) req := NewRequest(t, "GET", urlStr) @@ -53,7 +53,7 @@ func TestAPIIssueSubscriptions(t *testing.T) { testSubscription(issue4, false) testSubscription(issue5, false) - issue1Repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issue1.RepoID}).(*models.Repository) + issue1Repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue1.RepoID}).(*models.Repository) urlStr := fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s?token=%s", issue1Repo.OwnerName, issue1Repo.Name, issue1.Index, owner.Name, token) req := NewRequest(t, "DELETE", urlStr) session.MakeRequest(t, req, http.StatusCreated) @@ -63,7 +63,7 @@ func TestAPIIssueSubscriptions(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) testSubscription(issue1, false) - issue5Repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issue5.RepoID}).(*models.Repository) + issue5Repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issue5.RepoID}).(*models.Repository) urlStr = fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/subscriptions/%s?token=%s", issue5Repo.OwnerName, issue5Repo.Name, issue5.Index, owner.Name, token) req = NewRequest(t, "PUT", urlStr) session.MakeRequest(t, req, http.StatusCreated) diff --git a/integrations/api_issue_test.go b/integrations/api_issue_test.go index df258a983104..a46cba599097 100644 --- a/integrations/api_issue_test.go +++ b/integrations/api_issue_test.go @@ -12,7 +12,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -21,8 +21,8 @@ import ( func TestAPIListIssues(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) @@ -32,9 +32,9 @@ func TestAPIListIssues(t *testing.T) { resp := session.MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) var apiIssues []*api.Issue DecodeJSON(t, resp, &apiIssues) - assert.Len(t, apiIssues, db.GetCount(t, &models.Issue{RepoID: repo.ID})) + assert.Len(t, apiIssues, unittest.GetCount(t, &models.Issue{RepoID: repo.ID})) for _, apiIssue := range apiIssues { - db.AssertExistsAndLoadBean(t, &models.Issue{ID: apiIssue.ID, RepoID: repo.ID}) + unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: apiIssue.ID, RepoID: repo.ID}) } // test milestone filter @@ -72,8 +72,8 @@ func TestAPICreateIssue(t *testing.T) { defer prepareTestEnv(t)() const body, title = "apiTestBody", "apiTestTitle" - repoBefore := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User) + repoBefore := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) @@ -89,14 +89,14 @@ func TestAPICreateIssue(t *testing.T) { assert.Equal(t, body, apiIssue.Body) assert.Equal(t, title, apiIssue.Title) - db.AssertExistsAndLoadBean(t, &models.Issue{ + unittest.AssertExistsAndLoadBean(t, &models.Issue{ RepoID: repoBefore.ID, AssigneeID: owner.ID, Content: body, Title: title, }) - repoAfter := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repoAfter := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) assert.Equal(t, repoBefore.NumIssues+1, repoAfter.NumIssues) assert.Equal(t, repoBefore.NumClosedIssues, repoAfter.NumClosedIssues) } @@ -104,9 +104,9 @@ func TestAPICreateIssue(t *testing.T) { func TestAPIEditIssue(t *testing.T) { defer prepareTestEnv(t)() - issueBefore := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 10}).(*models.Issue) - repoBefore := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issueBefore.RepoID}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User) + issueBefore := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 10}).(*models.Issue) + repoBefore := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issueBefore.RepoID}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User) assert.NoError(t, issueBefore.LoadAttributes()) assert.Equal(t, int64(1019307200), int64(issueBefore.DeadlineUnix)) assert.Equal(t, api.StateOpen, issueBefore.State()) @@ -135,8 +135,8 @@ func TestAPIEditIssue(t *testing.T) { var apiIssue api.Issue DecodeJSON(t, resp, &apiIssue) - issueAfter := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 10}).(*models.Issue) - repoAfter := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issueBefore.RepoID}).(*models.Repository) + issueAfter := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 10}).(*models.Issue) + repoAfter := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: issueBefore.RepoID}).(*models.Repository) // check deleted user assert.Equal(t, int64(500), issueAfter.PosterID) diff --git a/integrations/api_issue_tracked_time_test.go b/integrations/api_issue_tracked_time_test.go index fcf18e45df95..bcaa0213c8ee 100644 --- a/integrations/api_issue_tracked_time_test.go +++ b/integrations/api_issue_tracked_time_test.go @@ -11,7 +11,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -20,8 +20,8 @@ import ( func TestAPIGetTrackedTimes(t *testing.T) { defer prepareTestEnv(t)() - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - issue2 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + issue2 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) assert.NoError(t, issue2.LoadRepo()) session := loginUser(t, user2.Name) @@ -62,10 +62,10 @@ func TestAPIGetTrackedTimes(t *testing.T) { func TestAPIDeleteTrackedTime(t *testing.T) { defer prepareTestEnv(t)() - time6 := db.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 6}).(*models.TrackedTime) - issue2 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) + time6 := unittest.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 6}).(*models.TrackedTime) + issue2 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) assert.NoError(t, issue2.LoadRepo()) - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session) @@ -74,7 +74,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { req := NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time6.ID, token) session.MakeRequest(t, req, http.StatusForbidden) - time3 := db.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 3}).(*models.TrackedTime) + time3 := unittest.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 3}).(*models.TrackedTime) req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times/%d?token=%s", user2.Name, issue2.Repo.Name, issue2.Index, time3.ID, token) session.MakeRequest(t, req, http.StatusNoContent) //Delete non existing time @@ -97,10 +97,10 @@ func TestAPIDeleteTrackedTime(t *testing.T) { func TestAPIAddTrackedTimes(t *testing.T) { defer prepareTestEnv(t)() - issue2 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) + issue2 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) assert.NoError(t, issue2.LoadRepo()) - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - admin := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + admin := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) session := loginUser(t, admin.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_keys_test.go b/integrations/api_keys_test.go index 161b05e8ce96..244ece56cc5d 100644 --- a/integrations/api_keys_test.go +++ b/integrations/api_keys_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -46,8 +46,8 @@ func TestDeleteDeployKeyNoLogin(t *testing.T) { func TestCreateReadOnlyDeployKey(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository) - repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository) + repoOwner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session) @@ -62,7 +62,7 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { var newDeployKey api.DeployKey DecodeJSON(t, resp, &newDeployKey) - db.AssertExistsAndLoadBean(t, &models.DeployKey{ + unittest.AssertExistsAndLoadBean(t, &models.DeployKey{ ID: newDeployKey.ID, Name: rawKeyBody.Title, Content: rawKeyBody.Key, @@ -72,8 +72,8 @@ func TestCreateReadOnlyDeployKey(t *testing.T) { func TestCreateReadWriteDeployKey(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository) - repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository) + repoOwner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, repoOwner.Name) token := getTokenForLoggedInUser(t, session) @@ -87,7 +87,7 @@ func TestCreateReadWriteDeployKey(t *testing.T) { var newDeployKey api.DeployKey DecodeJSON(t, resp, &newDeployKey) - db.AssertExistsAndLoadBean(t, &models.DeployKey{ + unittest.AssertExistsAndLoadBean(t, &models.DeployKey{ ID: newDeployKey.ID, Name: rawKeyBody.Title, Content: rawKeyBody.Key, @@ -97,7 +97,7 @@ func TestCreateReadWriteDeployKey(t *testing.T) { func TestCreateUserKey(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User) session := loginUser(t, "user1") token := url.QueryEscape(getTokenForLoggedInUser(t, session)) @@ -113,7 +113,7 @@ func TestCreateUserKey(t *testing.T) { var newPublicKey api.PublicKey DecodeJSON(t, resp, &newPublicKey) - db.AssertExistsAndLoadBean(t, &models.PublicKey{ + unittest.AssertExistsAndLoadBean(t, &models.PublicKey{ ID: newPublicKey.ID, OwnerID: user.ID, Name: rawKeyBody.Title, diff --git a/integrations/api_notification_test.go b/integrations/api_notification_test.go index 3049f1b99546..1c62ee5abf5d 100644 --- a/integrations/api_notification_test.go +++ b/integrations/api_notification_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -19,9 +19,9 @@ import ( func TestAPINotification(t *testing.T) { defer prepareTestEnv(t)() - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - thread5 := db.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + thread5 := unittest.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session) @@ -112,7 +112,7 @@ func TestAPINotification(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusResetContent) assert.Equal(t, models.NotificationStatusUnread, thread5.Status) - thread5 = db.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification) + thread5 = unittest.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification) assert.Equal(t, models.NotificationStatusRead, thread5.Status) // -- check notifications -- diff --git a/integrations/api_oauth2_apps_test.go b/integrations/api_oauth2_apps_test.go index 6f0a46249f51..d84477ace5c2 100644 --- a/integrations/api_oauth2_apps_test.go +++ b/integrations/api_oauth2_apps_test.go @@ -10,8 +10,8 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -27,7 +27,7 @@ func TestOAuth2Application(t *testing.T) { } func testAPICreateOAuth2Application(t *testing.T) { - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) appBody := api.CreateOAuth2ApplicationOptions{ Name: "test-app-1", RedirectURIs: []string{ @@ -47,15 +47,15 @@ func testAPICreateOAuth2Application(t *testing.T) { assert.Len(t, createdApp.ClientID, 36) assert.NotEmpty(t, createdApp.Created) assert.EqualValues(t, appBody.RedirectURIs[0], createdApp.RedirectURIs[0]) - db.AssertExistsAndLoadBean(t, &login.OAuth2Application{UID: user.ID, Name: createdApp.Name}) + unittest.AssertExistsAndLoadBean(t, &login.OAuth2Application{UID: user.ID, Name: createdApp.Name}) } func testAPIListOAuth2Applications(t *testing.T) { - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) - existApp := db.AssertExistsAndLoadBean(t, &login.OAuth2Application{ + existApp := unittest.AssertExistsAndLoadBean(t, &login.OAuth2Application{ UID: user.ID, Name: "test-app-1", RedirectURIs: []string{ @@ -76,15 +76,15 @@ func testAPIListOAuth2Applications(t *testing.T) { assert.Len(t, expectedApp.ClientID, 36) assert.Empty(t, expectedApp.ClientSecret) assert.EqualValues(t, existApp.RedirectURIs[0], expectedApp.RedirectURIs[0]) - db.AssertExistsAndLoadBean(t, &login.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) + unittest.AssertExistsAndLoadBean(t, &login.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) } func testAPIDeleteOAuth2Application(t *testing.T) { - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) - oldApp := db.AssertExistsAndLoadBean(t, &login.OAuth2Application{ + oldApp := unittest.AssertExistsAndLoadBean(t, &login.OAuth2Application{ UID: user.ID, Name: "test-app-1", }).(*login.OAuth2Application) @@ -93,7 +93,7 @@ func testAPIDeleteOAuth2Application(t *testing.T) { req := NewRequest(t, "DELETE", urlStr) session.MakeRequest(t, req, http.StatusNoContent) - db.AssertNotExistsBean(t, &login.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name}) + unittest.AssertNotExistsBean(t, &login.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name}) // Delete again will return not found req = NewRequest(t, "DELETE", urlStr) @@ -101,11 +101,11 @@ func testAPIDeleteOAuth2Application(t *testing.T) { } func testAPIGetOAuth2Application(t *testing.T) { - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) - existApp := db.AssertExistsAndLoadBean(t, &login.OAuth2Application{ + existApp := unittest.AssertExistsAndLoadBean(t, &login.OAuth2Application{ UID: user.ID, Name: "test-app-1", RedirectURIs: []string{ @@ -127,13 +127,13 @@ func testAPIGetOAuth2Application(t *testing.T) { assert.Empty(t, expectedApp.ClientSecret) assert.Len(t, expectedApp.RedirectURIs, 1) assert.EqualValues(t, existApp.RedirectURIs[0], expectedApp.RedirectURIs[0]) - db.AssertExistsAndLoadBean(t, &login.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) + unittest.AssertExistsAndLoadBean(t, &login.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) } func testAPIUpdateOAuth2Application(t *testing.T) { - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - existApp := db.AssertExistsAndLoadBean(t, &login.OAuth2Application{ + existApp := unittest.AssertExistsAndLoadBean(t, &login.OAuth2Application{ UID: user.ID, Name: "test-app-1", RedirectURIs: []string{ @@ -161,5 +161,5 @@ func testAPIUpdateOAuth2Application(t *testing.T) { assert.Len(t, expectedApp.RedirectURIs, 2) assert.EqualValues(t, expectedApp.RedirectURIs[0], appBody.RedirectURIs[0]) assert.EqualValues(t, expectedApp.RedirectURIs[1], appBody.RedirectURIs[1]) - db.AssertExistsAndLoadBean(t, &login.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) + unittest.AssertExistsAndLoadBean(t, &login.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) } diff --git a/integrations/api_org_test.go b/integrations/api_org_test.go index 6268fa4a10ef..ced78d7ee95b 100644 --- a/integrations/api_org_test.go +++ b/integrations/api_org_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" @@ -44,7 +44,7 @@ func TestAPIOrgCreate(t *testing.T) { assert.Equal(t, org.Location, apiOrg.Location) assert.Equal(t, org.Visibility, apiOrg.Visibility) - db.AssertExistsAndLoadBean(t, &models.User{ + unittest.AssertExistsAndLoadBean(t, &models.User{ Name: org.UserName, LowerName: strings.ToLower(org.UserName), FullName: org.FullName, diff --git a/integrations/api_pull_commits_test.go b/integrations/api_pull_commits_test.go index 615589fd12f1..c537f002085c 100644 --- a/integrations/api_pull_commits_test.go +++ b/integrations/api_pull_commits_test.go @@ -9,16 +9,16 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" ) func TestAPIPullCommits(t *testing.T) { defer prepareTestEnv(t)() - pullIssue := db.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest) + pullIssue := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest) assert.NoError(t, pullIssue.LoadIssue()) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.HeadRepoID}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.HeadRepoID}).(*models.Repository) session := loginUser(t, "user2") req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/commits", repo.OwnerName, repo.Name, pullIssue.Index) diff --git a/integrations/api_pull_review_test.go b/integrations/api_pull_review_test.go index 123ba0a2b5c4..ace2c89e8026 100644 --- a/integrations/api_pull_review_test.go +++ b/integrations/api_pull_review_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" @@ -19,9 +19,9 @@ import ( func TestAPIPullReview(t *testing.T) { defer prepareTestEnv(t)() - pullIssue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue) + pullIssue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue) assert.NoError(t, pullIssue.LoadAttributes()) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.RepoID}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.RepoID}).(*models.Repository) // test ListPullReviews session := loginUser(t, "user2") @@ -63,7 +63,7 @@ func TestAPIPullReview(t *testing.T) { assert.EqualValues(t, *reviews[5], review) // test GetPullReviewComments - comment := db.AssertExistsAndLoadBean(t, &models.Comment{ID: 7}).(*models.Comment) + comment := unittest.AssertExistsAndLoadBean(t, &models.Comment{ID: 7}).(*models.Comment) req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews/%d/comments?token=%s", repo.OwnerName, repo.Name, pullIssue.Index, 10, token) resp = session.MakeRequest(t, req, http.StatusOK) var reviewComments []*api.PullReviewComment @@ -196,9 +196,9 @@ func TestAPIPullReview(t *testing.T) { // test get review requests // to make it simple, use same api with get review - pullIssue12 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 12}).(*models.Issue) + pullIssue12 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 12}).(*models.Issue) assert.NoError(t, pullIssue12.LoadAttributes()) - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue12.RepoID}).(*models.Repository) + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue12.RepoID}).(*models.Repository) req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token) resp = session.MakeRequest(t, req, http.StatusOK) @@ -220,9 +220,9 @@ func TestAPIPullReview(t *testing.T) { func TestAPIPullReviewRequest(t *testing.T) { defer prepareTestEnv(t)() - pullIssue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue) + pullIssue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue) assert.NoError(t, pullIssue.LoadAttributes()) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.RepoID}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.RepoID}).(*models.Repository) // Test add Review Request session := loginUser(t, "user2") @@ -265,9 +265,9 @@ func TestAPIPullReviewRequest(t *testing.T) { session.MakeRequest(t, req, http.StatusNoContent) // Test team review request - pullIssue12 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 12}).(*models.Issue) + pullIssue12 := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 12}).(*models.Issue) assert.NoError(t, pullIssue12.LoadAttributes()) - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue12.RepoID}).(*models.Repository) + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue12.RepoID}).(*models.Repository) // Test add Team Review Request req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers?token=%s", repo3.OwnerName, repo3.Name, pullIssue12.Index, token), &api.PullReviewRequestOptions{ diff --git a/integrations/api_pull_test.go b/integrations/api_pull_test.go index 069650993dfa..060eb16d89c8 100644 --- a/integrations/api_pull_test.go +++ b/integrations/api_pull_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/services/forms" @@ -21,8 +21,8 @@ import ( func TestAPIViewPulls(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session) @@ -31,16 +31,16 @@ func TestAPIViewPulls(t *testing.T) { var pulls []*api.PullRequest DecodeJSON(t, resp, &pulls) - expectedLen := db.GetCount(t, &models.Issue{RepoID: repo.ID}, db.Cond("is_pull = ?", true)) + expectedLen := unittest.GetCount(t, &models.Issue{RepoID: repo.ID}, unittest.Cond("is_pull = ?", true)) assert.Len(t, pulls, expectedLen) } // TestAPIMergePullWIP ensures that we can't merge a WIP pull request func TestAPIMergePullWIP(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) - pr := db.AssertExistsAndLoadBean(t, &models.PullRequest{Status: models.PullRequestStatusMergeable}, db.Cond("has_merged = ?", false)).(*models.PullRequest) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{Status: models.PullRequestStatusMergeable}, unittest.Cond("has_merged = ?", false)).(*models.PullRequest) pr.LoadIssue() issue_service.ChangeTitle(pr.Issue, owner, setting.Repository.PullRequest.WorkInProgressPrefixes[0]+" "+pr.Issue.Title) @@ -61,12 +61,12 @@ func TestAPIMergePullWIP(t *testing.T) { func TestAPICreatePullSuccess(t *testing.T) { defer prepareTestEnv(t)() - repo10 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository) + repo10 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository) // repo10 have code, pulls units. - repo11 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository) + repo11 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository) // repo11 only have code unit but should still create pulls - owner10 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User) - owner11 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User) + owner10 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User) + owner11 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User) session := loginUser(t, owner11.Name) token := getTokenForLoggedInUser(t, session) @@ -82,11 +82,11 @@ func TestAPICreatePullSuccess(t *testing.T) { func TestAPICreatePullWithFieldsSuccess(t *testing.T) { defer prepareTestEnv(t)() // repo10 have code, pulls units. - repo10 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository) - owner10 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User) + repo10 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository) + owner10 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User) // repo11 only have code unit but should still create pulls - repo11 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository) - owner11 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User) + repo11 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository) + owner11 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User) session := loginUser(t, owner11.Name) token := getTokenForLoggedInUser(t, session) @@ -119,11 +119,11 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) { func TestAPICreatePullWithFieldsFailure(t *testing.T) { defer prepareTestEnv(t)() // repo10 have code, pulls units. - repo10 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository) - owner10 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User) + repo10 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository) + owner10 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User) // repo11 only have code unit but should still create pulls - repo11 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository) - owner11 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User) + repo11 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository) + owner11 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User) session := loginUser(t, owner11.Name) token := getTokenForLoggedInUser(t, session) @@ -152,8 +152,8 @@ func TestAPICreatePullWithFieldsFailure(t *testing.T) { func TestAPIEditPull(t *testing.T) { defer prepareTestEnv(t)() - repo10 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository) - owner10 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User) + repo10 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository) + owner10 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User) session := loginUser(t, owner10.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_releases_test.go b/integrations/api_releases_test.go index cb04c2a8d3f2..ac2beb7bdf3b 100644 --- a/integrations/api_releases_test.go +++ b/integrations/api_releases_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" @@ -21,8 +21,8 @@ import ( func TestAPIListReleases(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) session := loginUser(t, user2.LowerName) token := getTokenForLoggedInUser(t, session) @@ -85,7 +85,7 @@ func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string, var newRelease api.Release DecodeJSON(t, resp, &newRelease) - db.AssertExistsAndLoadBean(t, &models.Release{ + unittest.AssertExistsAndLoadBean(t, &models.Release{ ID: newRelease.ID, TagName: newRelease.TagName, Title: newRelease.Title, @@ -98,8 +98,8 @@ func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string, func TestAPICreateAndUpdateRelease(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.LowerName) token := getTokenForLoggedInUser(t, session) @@ -138,7 +138,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &newRelease) - db.AssertExistsAndLoadBean(t, &models.Release{ + unittest.AssertExistsAndLoadBean(t, &models.Release{ ID: newRelease.ID, TagName: newRelease.TagName, Title: newRelease.Title, @@ -149,8 +149,8 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { func TestAPICreateReleaseToDefaultBranch(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.LowerName) token := getTokenForLoggedInUser(t, session) @@ -160,8 +160,8 @@ func TestAPICreateReleaseToDefaultBranch(t *testing.T) { func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.LowerName) token := getTokenForLoggedInUser(t, session) @@ -178,8 +178,8 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) { func TestAPIGetReleaseByTag(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.LowerName) tag := "v1.1" @@ -211,8 +211,8 @@ func TestAPIGetReleaseByTag(t *testing.T) { func TestAPIDeleteReleaseByTagName(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.LowerName) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_repo_edit_test.go b/integrations/api_repo_edit_test.go index f8e21a495b63..404e8e912f70 100644 --- a/integrations/api_repo_edit_test.go +++ b/integrations/api_repo_edit_test.go @@ -11,8 +11,8 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" unit_model "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -134,13 +134,13 @@ func TestAPIRepoEdit(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { bFalse, bTrue := false, true - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo - repo15 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 15}).(*models.Repository) // empty repo - repo16 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo + repo15 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 15}).(*models.Repository) // empty repo + repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo // Get user2's token session := loginUser(t, user2.Name) @@ -166,7 +166,7 @@ func TestAPIRepoEdit(t *testing.T) { assert.Equal(t, *repoEditOption.Website, repo.Website) assert.Equal(t, *repoEditOption.Archived, repo.Archived) // check repo1 from database - repo1edited := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo1edited := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) repo1editedOption := getRepoEditOptionFromRepo(repo1edited) assert.Equal(t, *repoEditOption.Name, *repo1editedOption.Name) assert.Equal(t, *repoEditOption.Description, *repo1editedOption.Description) @@ -191,7 +191,7 @@ func TestAPIRepoEdit(t *testing.T) { DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) // check repo1 was written to database - repo1edited = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo1edited = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) repo1editedOption = getRepoEditOptionFromRepo(repo1edited) assert.Equal(t, *repo1editedOption.HasIssues, true) assert.Nil(t, repo1editedOption.ExternalTracker) @@ -213,7 +213,7 @@ func TestAPIRepoEdit(t *testing.T) { DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) // check repo1 was written to database - repo1edited = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo1edited = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) repo1editedOption = getRepoEditOptionFromRepo(repo1edited) assert.Equal(t, *repo1editedOption.HasIssues, true) assert.Equal(t, *repo1editedOption.ExternalTracker, *repoEditOption.ExternalTracker) @@ -244,7 +244,7 @@ func TestAPIRepoEdit(t *testing.T) { DecodeJSON(t, resp, &repo) assert.NotNil(t, repo) // check repo1 was written to database - repo1edited = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo1edited = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) repo1editedOption = getRepoEditOptionFromRepo(repo1edited) assert.Equal(t, *repo1editedOption.Description, *repoEditOption.Description) assert.Equal(t, *repo1editedOption.HasIssues, true) @@ -289,7 +289,7 @@ func TestAPIRepoEdit(t *testing.T) { _ = session.MakeRequest(t, req, http.StatusOK) // Test making a repo public that is private - repo16 = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) + repo16 = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) assert.True(t, repo16.IsPrivate) repoEditOption = &api.EditRepoOption{ Private: &bFalse, @@ -297,7 +297,7 @@ func TestAPIRepoEdit(t *testing.T) { url = fmt.Sprintf("/api/v1/repos/%s/%s?token=%s", user2.Name, repo16.Name, token2) req = NewRequestWithJSON(t, "PATCH", url, &repoEditOption) _ = session.MakeRequest(t, req, http.StatusOK) - repo16 = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) + repo16 = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) assert.False(t, repo16.IsPrivate) // Make it private again repoEditOption.Private = &bTrue @@ -311,7 +311,7 @@ func TestAPIRepoEdit(t *testing.T) { Archived: &bTrue, }) _ = session.MakeRequest(t, req, http.StatusOK) - repo15 = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 15}).(*models.Repository) + repo15 = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 15}).(*models.Repository) assert.True(t, repo15.IsArchived) req = NewRequestWithJSON(t, "PATCH", url, &api.EditRepoOption{ Archived: &bFalse, diff --git a/integrations/api_repo_file_create_test.go b/integrations/api_repo_file_create_test.go index 5b0e3927f905..dd703a99bb6f 100644 --- a/integrations/api_repo_file_create_test.go +++ b/integrations/api_repo_file_create_test.go @@ -14,7 +14,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/setting" @@ -109,8 +109,8 @@ func getExpectedFileResponseForCreate(commitID, treePath string) *api.FileRespon func BenchmarkAPICreateFileSmall(b *testing.B) { onGiteaRunTB(b, func(t testing.TB, u *url.URL) { b := t.(*testing.B) - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo for n := 0; n < b.N; n++ { treePath := fmt.Sprintf("update/file%d.txt", n) @@ -124,8 +124,8 @@ func BenchmarkAPICreateFileMedium(b *testing.B) { onGiteaRunTB(b, func(t testing.TB, u *url.URL) { b := t.(*testing.B) - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo b.ResetTimer() for n := 0; n < b.N; n++ { @@ -138,12 +138,12 @@ func BenchmarkAPICreateFileMedium(b *testing.B) { func TestAPICreateFile(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo - repo16 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo + repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo fileID := 0 // Get user2's token diff --git a/integrations/api_repo_file_delete_test.go b/integrations/api_repo_file_delete_test.go index 69e24d29c3b9..e9877d08c26e 100644 --- a/integrations/api_repo_file_delete_test.go +++ b/integrations/api_repo_file_delete_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -38,12 +38,12 @@ func getDeleteFileOptions() *api.DeleteFileOptions { func TestAPIDeleteFile(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo - repo16 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo + repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo fileID := 0 // Get user2's token diff --git a/integrations/api_repo_file_update_test.go b/integrations/api_repo_file_update_test.go index b6d9be24f5fe..ba1f309f14e4 100644 --- a/integrations/api_repo_file_update_test.go +++ b/integrations/api_repo_file_update_test.go @@ -13,7 +13,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/setting" @@ -104,12 +104,12 @@ func getExpectedFileResponseForUpdate(commitID, treePath string) *api.FileRespon func TestAPIUpdateFile(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo - repo16 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo + repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo fileID := 0 // Get user2's token diff --git a/integrations/api_repo_get_contents_list_test.go b/integrations/api_repo_get_contents_list_test.go index 625231a8b227..c35a345e81bb 100644 --- a/integrations/api_repo_get_contents_list_test.go +++ b/integrations/api_repo_get_contents_list_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" repo_module "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" @@ -53,13 +53,13 @@ func TestAPIGetContentsList(t *testing.T) { func testAPIGetContentsList(t *testing.T, u *url.URL) { /*** SETUP ***/ - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo - repo16 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo - treePath := "" // root dir + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo + repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo + treePath := "" // root dir // Get user2's token session := loginUser(t, user2.Name) diff --git a/integrations/api_repo_get_contents_test.go b/integrations/api_repo_get_contents_test.go index e096a718bdb6..243ee229dc4d 100644 --- a/integrations/api_repo_get_contents_test.go +++ b/integrations/api_repo_get_contents_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" repo_module "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" @@ -54,12 +54,12 @@ func TestAPIGetContents(t *testing.T) { func testAPIGetContents(t *testing.T, u *url.URL) { /*** SETUP ***/ - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo - repo16 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo + repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo treePath := "README.md" // Get user2's token diff --git a/integrations/api_repo_git_blobs_test.go b/integrations/api_repo_git_blobs_test.go index 5bbf13ac46b1..53c266e9f970 100644 --- a/integrations/api_repo_git_blobs_test.go +++ b/integrations/api_repo_git_blobs_test.go @@ -9,7 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -17,12 +17,12 @@ import ( func TestAPIReposGitBlobs(t *testing.T) { defer prepareTestEnv(t)() - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3 - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo - repo16 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3 + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo + repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo repo1ReadmeSHA := "65f1bf27bc3bf70f64657658635e66094edbcb4d" repo3ReadmeSHA := "d56a3073c1dbb7b15963110a049d50cdb5db99fc" repo16ReadmeSHA := "f90451c72ef61a7645293d17b47be7a8e983da57" diff --git a/integrations/api_repo_git_commits_test.go b/integrations/api_repo_git_commits_test.go index 314416d2646e..627f563dafe6 100644 --- a/integrations/api_repo_git_commits_test.go +++ b/integrations/api_repo_git_commits_test.go @@ -9,7 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -25,7 +25,7 @@ func compareCommitFiles(t *testing.T, expect []string, files []*api.CommitAffect func TestAPIReposGitCommits(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Login as User2. session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -53,7 +53,7 @@ func TestAPIReposGitCommits(t *testing.T) { func TestAPIReposGitCommitList(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Login as User2. session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -76,7 +76,7 @@ func TestAPIReposGitCommitList(t *testing.T) { func TestAPIReposGitCommitListPage2Empty(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Login as User2. session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -93,7 +93,7 @@ func TestAPIReposGitCommitListPage2Empty(t *testing.T) { func TestAPIReposGitCommitListDifferentBranch(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Login as User2. session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -112,7 +112,7 @@ func TestAPIReposGitCommitListDifferentBranch(t *testing.T) { func TestDownloadCommitDiffOrPatch(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Login as User2. session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_repo_git_hook_test.go b/integrations/api_repo_git_hook_test.go index 490251b30b0b..f9cfdf44934c 100644 --- a/integrations/api_repo_git_hook_test.go +++ b/integrations/api_repo_git_hook_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -24,8 +24,8 @@ echo Hello, World! func TestAPIListGitHooks(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) // user1 is an admin user session := loginUser(t, "user1") @@ -50,8 +50,8 @@ func TestAPIListGitHooks(t *testing.T) { func TestAPIListGitHooksNoHooks(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) // user1 is an admin user session := loginUser(t, "user1") @@ -71,8 +71,8 @@ func TestAPIListGitHooksNoHooks(t *testing.T) { func TestAPIListGitHooksNoAccess(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) @@ -84,8 +84,8 @@ func TestAPIListGitHooksNoAccess(t *testing.T) { func TestAPIGetGitHook(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) // user1 is an admin user session := loginUser(t, "user1") @@ -102,8 +102,8 @@ func TestAPIGetGitHook(t *testing.T) { func TestAPIGetGitHookNoAccess(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) @@ -115,8 +115,8 @@ func TestAPIGetGitHookNoAccess(t *testing.T) { func TestAPIEditGitHook(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) // user1 is an admin user session := loginUser(t, "user1") @@ -145,8 +145,8 @@ func TestAPIEditGitHook(t *testing.T) { func TestAPIEditGitHookNoAccess(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) @@ -161,8 +161,8 @@ func TestAPIEditGitHookNoAccess(t *testing.T) { func TestAPIDeleteGitHook(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) // user1 is an admin user session := loginUser(t, "user1") @@ -184,8 +184,8 @@ func TestAPIDeleteGitHook(t *testing.T) { func TestAPIDeleteGitHookNoAccess(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_repo_git_notes_test.go b/integrations/api_repo_git_notes_test.go index 02235f9d910c..21b8a931b07d 100644 --- a/integrations/api_repo_git_notes_test.go +++ b/integrations/api_repo_git_notes_test.go @@ -10,14 +10,14 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" ) func TestAPIReposGitNotes(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Login as User2. session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_repo_git_ref_test.go b/integrations/api_repo_git_ref_test.go index fcf5edc75848..9137f03adf28 100644 --- a/integrations/api_repo_git_ref_test.go +++ b/integrations/api_repo_git_ref_test.go @@ -9,12 +9,12 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestAPIReposGitRefs(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Login as User2. session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_repo_git_tags_test.go b/integrations/api_repo_git_tags_test.go index 01e0450c6bd0..f091286e2c29 100644 --- a/integrations/api_repo_git_tags_test.go +++ b/integrations/api_repo_git_tags_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" @@ -20,8 +20,8 @@ import ( func TestAPIGitTags(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // Login as User2. session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -65,8 +65,8 @@ func TestAPIGitTags(t *testing.T) { func TestAPIDeleteTagByName(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.LowerName) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_repo_git_trees_test.go b/integrations/api_repo_git_trees_test.go index bf605d4d8601..27088156bac6 100644 --- a/integrations/api_repo_git_trees_test.go +++ b/integrations/api_repo_git_trees_test.go @@ -9,17 +9,17 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestAPIReposGitTrees(t *testing.T) { defer prepareTestEnv(t)() - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3 - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo - repo16 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16 + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3 + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo + repo16 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo repo1TreeSHA := "65f1bf27bc3bf70f64657658635e66094edbcb4d" repo3TreeSHA := "2a47ca4b614a9f5a43abbd5ad851a54a616ffee6" repo16TreeSHA := "69554a64c1e6030f051e5c3f94bfbd773cd6a324" diff --git a/integrations/api_repo_lfs_locks_test.go b/integrations/api_repo_lfs_locks_test.go index b2d8f0e63179..6a69145589a4 100644 --- a/integrations/api_repo_lfs_locks_test.go +++ b/integrations/api_repo_lfs_locks_test.go @@ -11,7 +11,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" @@ -22,8 +22,8 @@ import ( func TestAPILFSLocksNotStarted(t *testing.T) { defer prepareTestEnv(t)() setting.LFS.StartServer = false - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) req := NewRequestf(t, "GET", "/%s/%s.git/info/lfs/locks", user.Name, repo.Name) MakeRequest(t, req, http.StatusNotFound) @@ -38,8 +38,8 @@ func TestAPILFSLocksNotStarted(t *testing.T) { func TestAPILFSLocksNotLogin(t *testing.T) { defer prepareTestEnv(t)() setting.LFS.StartServer = true - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) req := NewRequestf(t, "GET", "/%s/%s.git/info/lfs/locks", user.Name, repo.Name) req.Header.Set("Accept", lfs.MediaType) @@ -52,11 +52,11 @@ func TestAPILFSLocksNotLogin(t *testing.T) { func TestAPILFSLocksLogged(t *testing.T) { defer prepareTestEnv(t)() setting.LFS.StartServer = true - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) //in org 3 - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) //in org 3 + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) //in org 3 + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) //in org 3 - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // own by org 3 + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // own by org 3 tests := []struct { user *models.User diff --git a/integrations/api_repo_lfs_migrate_test.go b/integrations/api_repo_lfs_migrate_test.go index 9acc96e4f473..47fcb489508b 100644 --- a/integrations/api_repo_lfs_migrate_test.go +++ b/integrations/api_repo_lfs_migrate_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" @@ -26,7 +26,7 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) { setting.ImportLocalPaths = true setting.Migrations.AllowLocalNetworks = true - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_repo_lfs_test.go b/integrations/api_repo_lfs_test.go index 22c324f973fa..4addb422c39c 100644 --- a/integrations/api_repo_lfs_test.go +++ b/integrations/api_repo_lfs_test.go @@ -13,7 +13,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/setting" @@ -26,8 +26,8 @@ func TestAPILFSNotStarted(t *testing.T) { setting.LFS.StartServer = false - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) req := NewRequestf(t, "POST", "/%s/%s.git/info/lfs/objects/batch", user.Name, repo.Name) MakeRequest(t, req, http.StatusNotFound) @@ -46,8 +46,8 @@ func TestAPILFSMediaType(t *testing.T) { setting.LFS.StartServer = true - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) req := NewRequestf(t, "POST", "/%s/%s.git/info/lfs/objects/batch", user.Name, repo.Name) MakeRequest(t, req, http.StatusUnsupportedMediaType) diff --git a/integrations/api_repo_raw_test.go b/integrations/api_repo_raw_test.go index 77b33473c82d..e7eb60ac56c1 100644 --- a/integrations/api_repo_raw_test.go +++ b/integrations/api_repo_raw_test.go @@ -9,12 +9,12 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestAPIReposRaw(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Login as User2. session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_repo_tags_test.go b/integrations/api_repo_tags_test.go index 8897bc44bc54..59eaedcbdf31 100644 --- a/integrations/api_repo_tags_test.go +++ b/integrations/api_repo_tags_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" @@ -19,7 +19,7 @@ import ( func TestAPIRepoTags(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Login as User2. session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/api_repo_teams_test.go b/integrations/api_repo_teams_test.go index e718d79cbe17..56836fcee318 100644 --- a/integrations/api_repo_teams_test.go +++ b/integrations/api_repo_teams_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -20,9 +20,9 @@ func TestAPIRepoTeams(t *testing.T) { defer prepareTestEnv(t)() // publicOrgRepo = user3/repo21 - publicOrgRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 32}).(*models.Repository) + publicOrgRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 32}).(*models.Repository) // user4 - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -62,7 +62,7 @@ func TestAPIRepoTeams(t *testing.T) { res = session.MakeRequest(t, req, http.StatusForbidden) // AddTeam with user2 - user = db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user = unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) session = loginUser(t, user.Name) token = getTokenForLoggedInUser(t, session) url = fmt.Sprintf("/api/v1/repos/%s/teams/%s?token=%s", publicOrgRepo.FullName(), "team1", token) diff --git a/integrations/api_repo_test.go b/integrations/api_repo_test.go index b93319be338c..ec9f3d9ba1e5 100644 --- a/integrations/api_repo_test.go +++ b/integrations/api_repo_test.go @@ -12,7 +12,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" @@ -22,15 +22,15 @@ import ( func TestAPIUserReposNotLogin(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) req := NewRequestf(t, "GET", "/api/v1/users/%s/repos", user.Name) resp := MakeRequest(t, req, http.StatusOK) var apiRepos []api.Repository DecodeJSON(t, resp, &apiRepos) - expectedLen := db.GetCount(t, models.Repository{OwnerID: user.ID}, - db.Cond("is_private = ?", false)) + expectedLen := unittest.GetCount(t, models.Repository{OwnerID: user.ID}, + unittest.Cond("is_private = ?", false)) assert.Len(t, apiRepos, expectedLen) for _, repo := range apiRepos { assert.EqualValues(t, user.ID, repo.Owner.ID) @@ -53,11 +53,11 @@ func TestAPISearchRepo(t *testing.T) { assert.False(t, repo.Private) } - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 15}).(*models.User) - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 16}).(*models.User) - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 18}).(*models.User) - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 20}).(*models.User) - orgUser := db.AssertExistsAndLoadBean(t, &models.User{ID: 17}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 15}).(*models.User) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 16}).(*models.User) + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 18}).(*models.User) + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 20}).(*models.User) + orgUser := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 17}).(*models.User) oldAPIDefaultNum := setting.API.DefaultPagingNum defer func() { @@ -209,7 +209,7 @@ var repoCache = make(map[int64]*models.Repository) func getRepo(t *testing.T, repoID int64) *models.Repository { if _, ok := repoCache[repoID]; !ok { - repoCache[repoID] = db.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.Repository) + repoCache[repoID] = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.Repository) } return repoCache[repoID] } @@ -246,11 +246,11 @@ func TestAPIViewRepo(t *testing.T) { func TestAPIOrgRepos(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User) // User3 is an Org. Check their repos. - sourceOrg := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) + sourceOrg := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) expectedResults := map[*models.User]struct { count int @@ -292,7 +292,7 @@ func TestAPIOrgRepos(t *testing.T) { func TestAPIGetRepoByIDUnauthorized(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) req := NewRequestf(t, "GET", "/api/v1/repositories/2?token="+token) @@ -316,7 +316,7 @@ func TestAPIRepoMigrate(t *testing.T) { defer prepareTestEnv(t)() for _, testCase := range testCases { - user := db.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, "POST", "/api/v1/repos/migrate?token="+token, &api.MigrateRepoOptions{ @@ -395,7 +395,7 @@ func TestAPIOrgRepoCreate(t *testing.T) { defer prepareTestEnv(t)() for _, testCase := range testCases { - user := db.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/org/%s/repos?token="+token, testCase.orgName), &api.CreateRepoOption{ @@ -463,7 +463,7 @@ func TestAPIRepoTransfer(t *testing.T) { defer prepareTestEnv(t)() //create repo to move - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) repoName := "moveME" @@ -480,8 +480,8 @@ func TestAPIRepoTransfer(t *testing.T) { //start testing for _, testCase := range testCases { - user = db.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: apiRepo.ID}).(*models.Repository) + user = unittest.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: apiRepo.ID}).(*models.Repository) session = loginUser(t, user.Name) token = getTokenForLoggedInUser(t, session) req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/transfer?token=%s", repo.OwnerName, repo.Name, token), &api.TransferRepoOption{ @@ -492,18 +492,18 @@ func TestAPIRepoTransfer(t *testing.T) { } //cleanup - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: apiRepo.ID}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: apiRepo.ID}).(*models.Repository) _ = models.DeleteRepository(user, repo.OwnerID, repo.ID) } func TestAPIGenerateRepo(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) - templateRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 44}).(*models.Repository) + templateRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 44}).(*models.Repository) // user repo := new(api.Repository) @@ -535,10 +535,10 @@ func TestAPIGenerateRepo(t *testing.T) { func TestAPIRepoGetReviewers(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/reviewers?token=%s", user.Name, repo.Name, token) resp := session.MakeRequest(t, req, http.StatusOK) @@ -549,10 +549,10 @@ func TestAPIRepoGetReviewers(t *testing.T) { func TestAPIRepoGetAssignees(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/assignees?token=%s", user.Name, repo.Name, token) resp := session.MakeRequest(t, req, http.StatusOK) diff --git a/integrations/api_repo_topic_test.go b/integrations/api_repo_topic_test.go index cc76f188589b..6035dd3d52ef 100644 --- a/integrations/api_repo_topic_test.go +++ b/integrations/api_repo_topic_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -51,11 +51,11 @@ func TestAPITopicSearch(t *testing.T) { func TestAPIRepoTopic(t *testing.T) { defer prepareTestEnv(t)() - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of repo2 - user3 := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of repo3 - user4 := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // write access to repo 3 - repo2 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) - repo3 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of repo2 + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of repo3 + user4 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // write access to repo 3 + repo2 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) + repo3 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // Get user2's token session := loginUser(t, user2.Name) diff --git a/integrations/api_team_test.go b/integrations/api_team_test.go index 086450033525..141c887e1372 100644 --- a/integrations/api_team_test.go +++ b/integrations/api_team_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/convert" api "code.gitea.io/gitea/modules/structs" @@ -21,9 +21,9 @@ import ( func TestAPITeam(t *testing.T) { defer prepareTestEnv(t)() - teamUser := db.AssertExistsAndLoadBean(t, &models.TeamUser{}).(*models.TeamUser) - team := db.AssertExistsAndLoadBean(t, &models.Team{ID: teamUser.TeamID}).(*models.Team) - user := db.AssertExistsAndLoadBean(t, &models.User{ID: teamUser.UID}).(*models.User) + teamUser := unittest.AssertExistsAndLoadBean(t, &models.TeamUser{}).(*models.TeamUser) + team := unittest.AssertExistsAndLoadBean(t, &models.Team{ID: teamUser.TeamID}).(*models.Team) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: teamUser.UID}).(*models.User) session := loginUser(t, user.Name) token := getTokenForLoggedInUser(t, session) @@ -36,8 +36,8 @@ func TestAPITeam(t *testing.T) { assert.Equal(t, team.Name, apiTeam.Name) // non team member user will not access the teams details - teamUser2 := db.AssertExistsAndLoadBean(t, &models.TeamUser{ID: 3}).(*models.TeamUser) - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: teamUser2.UID}).(*models.User) + teamUser2 := unittest.AssertExistsAndLoadBean(t, &models.TeamUser{ID: 3}).(*models.TeamUser) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: teamUser2.UID}).(*models.User) session = loginUser(t, user2.Name) token = getTokenForLoggedInUser(t, session) @@ -48,11 +48,11 @@ func TestAPITeam(t *testing.T) { _ = session.MakeRequest(t, req, http.StatusUnauthorized) // Get an admin user able to create, update and delete teams. - user = db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + user = unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) session = loginUser(t, user.Name) token = getTokenForLoggedInUser(t, session) - org := db.AssertExistsAndLoadBean(t, &models.User{ID: 6}).(*models.User) + org := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 6}).(*models.User) // Create team. teamToCreate := &api.CreateTeamOption{ @@ -102,7 +102,7 @@ func TestAPITeam(t *testing.T) { teamToEdit.Permission, teamToEdit.Units) // Read team. - teamRead := db.AssertExistsAndLoadBean(t, &models.Team{ID: teamID}).(*models.Team) + teamRead := unittest.AssertExistsAndLoadBean(t, &models.Team{ID: teamID}).(*models.Team) req = NewRequestf(t, "GET", "/api/v1/teams/%d?token="+token, teamID) resp = session.MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &apiTeam) @@ -112,7 +112,7 @@ func TestAPITeam(t *testing.T) { // Delete team. req = NewRequestf(t, "DELETE", "/api/v1/teams/%d?token="+token, teamID) session.MakeRequest(t, req, http.StatusNoContent) - db.AssertNotExistsBean(t, &models.Team{ID: teamID}) + unittest.AssertNotExistsBean(t, &models.Team{ID: teamID}) } func checkTeamResponse(t *testing.T, apiTeam *api.Team, name, description string, includesAllRepositories bool, permission string, units []string) { @@ -126,7 +126,7 @@ func checkTeamResponse(t *testing.T, apiTeam *api.Team, name, description string } func checkTeamBean(t *testing.T, id int64, name, description string, includesAllRepositories bool, permission string, units []string) { - team := db.AssertExistsAndLoadBean(t, &models.Team{ID: id}).(*models.Team) + team := unittest.AssertExistsAndLoadBean(t, &models.Team{ID: id}).(*models.Team) assert.NoError(t, team.GetUnits(), "GetUnits") checkTeamResponse(t, convert.ToTeam(team), name, description, includesAllRepositories, permission, units) } @@ -139,8 +139,8 @@ type TeamSearchResults struct { func TestAPITeamSearch(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - org := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + org := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) var results TeamSearchResults @@ -155,7 +155,7 @@ func TestAPITeamSearch(t *testing.T) { assert.Equal(t, "test_team", results.Data[0].Name) // no access if not organization member - user5 := db.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User) + user5 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User) session = loginUser(t, user5.Name) csrf = GetCSRF(t, session, "/"+org.Name) req = NewRequestf(t, "GET", "/api/v1/orgs/%s/teams/search?q=%s", org.Name, "team") diff --git a/integrations/api_team_user_test.go b/integrations/api_team_user_test.go index 747227269ccc..7e5bb0802e39 100644 --- a/integrations/api_team_user_test.go +++ b/integrations/api_team_user_test.go @@ -10,7 +10,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/convert" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -30,7 +30,7 @@ func TestAPITeamUser(t *testing.T) { var user2 *api.User DecodeJSON(t, resp, &user2) user2.Created = user2.Created.In(time.Local) - user := db.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User) expectedUser := convert.ToUser(user, user) diff --git a/integrations/api_token_test.go b/integrations/api_token_test.go index 1a6d53547bfc..8314d5b636ff 100644 --- a/integrations/api_token_test.go +++ b/integrations/api_token_test.go @@ -9,14 +9,14 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" ) // TestAPICreateAndDeleteToken tests that token that was just created can be deleted func TestAPICreateAndDeleteToken(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) req := NewRequestWithJSON(t, "POST", "/api/v1/users/user1/tokens", map[string]string{ "name": "test-key-1", @@ -26,7 +26,7 @@ func TestAPICreateAndDeleteToken(t *testing.T) { var newAccessToken api.AccessToken DecodeJSON(t, resp, &newAccessToken) - db.AssertExistsAndLoadBean(t, &models.AccessToken{ + unittest.AssertExistsAndLoadBean(t, &models.AccessToken{ ID: newAccessToken.ID, Name: newAccessToken.Name, Token: newAccessToken.Token, @@ -37,7 +37,7 @@ func TestAPICreateAndDeleteToken(t *testing.T) { req = AddBasicAuthHeader(req, user.Name) MakeRequest(t, req, http.StatusNoContent) - db.AssertNotExistsBean(t, &models.AccessToken{ID: newAccessToken.ID}) + unittest.AssertNotExistsBean(t, &models.AccessToken{ID: newAccessToken.ID}) req = NewRequestWithJSON(t, "POST", "/api/v1/users/user1/tokens", map[string]string{ "name": "test-key-2", @@ -50,15 +50,15 @@ func TestAPICreateAndDeleteToken(t *testing.T) { req = AddBasicAuthHeader(req, user.Name) MakeRequest(t, req, http.StatusNoContent) - db.AssertNotExistsBean(t, &models.AccessToken{ID: newAccessToken.ID}) + unittest.AssertNotExistsBean(t, &models.AccessToken{ID: newAccessToken.ID}) } // TestAPIDeleteMissingToken ensures that error is thrown when token not found func TestAPIDeleteMissingToken(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) - req := NewRequestf(t, "DELETE", "/api/v1/users/user1/tokens/%d", db.NonexistentID) + req := NewRequestf(t, "DELETE", "/api/v1/users/user1/tokens/%d", unittest.NonexistentID) req = AddBasicAuthHeader(req, user.Name) MakeRequest(t, req, http.StatusNotFound) } diff --git a/integrations/api_user_orgs_test.go b/integrations/api_user_orgs_test.go index 36b11335c054..d52ac980b92c 100644 --- a/integrations/api_user_orgs_test.go +++ b/integrations/api_user_orgs_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -25,7 +25,7 @@ func TestUserOrgs(t *testing.T) { orgs := getUserOrgs(t, adminUsername, normalUsername) - user3 := db.AssertExistsAndLoadBean(t, &models.User{Name: "user3"}).(*models.User) + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{Name: "user3"}).(*models.User) assert.Equal(t, []*api.Organization{ { @@ -81,7 +81,7 @@ func TestMyOrgs(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusOK) var orgs []*api.Organization DecodeJSON(t, resp, &orgs) - user3 := db.AssertExistsAndLoadBean(t, &models.User{Name: "user3"}).(*models.User) + user3 := unittest.AssertExistsAndLoadBean(t, &models.User{Name: "user3"}).(*models.User) assert.Equal(t, []*api.Organization{ { diff --git a/integrations/api_user_search_test.go b/integrations/api_user_search_test.go index d6144d9e87cb..67dc2f1cac40 100644 --- a/integrations/api_user_search_test.go +++ b/integrations/api_user_search_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" @@ -52,7 +52,7 @@ func TestAPIUserSearchNotLoggedIn(t *testing.T) { var modelUser *models.User for _, user := range results.Data { assert.Contains(t, user.UserName, query) - modelUser = db.AssertExistsAndLoadBean(t, &models.User{ID: user.ID}).(*models.User) + modelUser = unittest.AssertExistsAndLoadBean(t, &models.User{ID: user.ID}).(*models.User) if modelUser.KeepEmailPrivate { assert.EqualValues(t, fmt.Sprintf("%s@%s", modelUser.LowerName, setting.Service.NoReplyAddress), user.Email) } else { diff --git a/integrations/benchmarks_test.go b/integrations/benchmarks_test.go index 5df0d7b74954..627825083c01 100644 --- a/integrations/benchmarks_test.go +++ b/integrations/benchmarks_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" ) @@ -33,7 +33,7 @@ func BenchmarkRepoBranchCommit(b *testing.B) { for _, repoID := range samples { b.StopTimer() - repo := db.AssertExistsAndLoadBean(b, &models.Repository{ID: repoID}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(b, &models.Repository{ID: repoID}).(*models.Repository) b.StartTimer() b.Run(repo.Name, func(b *testing.B) { session := loginUser(b, "user2") diff --git a/integrations/change_default_branch_test.go b/integrations/change_default_branch_test.go index d6a666435037..d691e48e00a4 100644 --- a/integrations/change_default_branch_test.go +++ b/integrations/change_default_branch_test.go @@ -10,13 +10,13 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestChangeDefaultBranch(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) session := loginUser(t, owner.Name) branchesURL := fmt.Sprintf("/%s/%s/settings/branches", owner.Name, repo.Name) diff --git a/integrations/delete_user_test.go b/integrations/delete_user_test.go index f529734e1983..86896c8ae120 100644 --- a/integrations/delete_user_test.go +++ b/integrations/delete_user_test.go @@ -10,19 +10,19 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func assertUserDeleted(t *testing.T, userID int64) { - db.AssertNotExistsBean(t, &models.User{ID: userID}) - db.AssertNotExistsBean(t, &models.Follow{UserID: userID}) - db.AssertNotExistsBean(t, &models.Follow{FollowID: userID}) - db.AssertNotExistsBean(t, &models.Repository{OwnerID: userID}) - db.AssertNotExistsBean(t, &models.Access{UserID: userID}) - db.AssertNotExistsBean(t, &models.OrgUser{UID: userID}) - db.AssertNotExistsBean(t, &models.IssueUser{UID: userID}) - db.AssertNotExistsBean(t, &models.TeamUser{UID: userID}) - db.AssertNotExistsBean(t, &models.Star{UID: userID}) + unittest.AssertNotExistsBean(t, &models.User{ID: userID}) + unittest.AssertNotExistsBean(t, &models.Follow{UserID: userID}) + unittest.AssertNotExistsBean(t, &models.Follow{FollowID: userID}) + unittest.AssertNotExistsBean(t, &models.Repository{OwnerID: userID}) + unittest.AssertNotExistsBean(t, &models.Access{UserID: userID}) + unittest.AssertNotExistsBean(t, &models.OrgUser{UID: userID}) + unittest.AssertNotExistsBean(t, &models.IssueUser{UID: userID}) + unittest.AssertNotExistsBean(t, &models.TeamUser{UID: userID}) + unittest.AssertNotExistsBean(t, &models.Star{UID: userID}) } func TestUserDeleteAccount(t *testing.T) { @@ -37,7 +37,7 @@ func TestUserDeleteAccount(t *testing.T) { session.MakeRequest(t, req, http.StatusFound) assertUserDeleted(t, 8) - models.CheckConsistencyFor(t, &models.User{}) + unittest.CheckConsistencyFor(t, &models.User{}) } func TestUserDeleteAccountStillOwnRepos(t *testing.T) { @@ -52,5 +52,5 @@ func TestUserDeleteAccountStillOwnRepos(t *testing.T) { session.MakeRequest(t, req, http.StatusFound) // user should not have been deleted, because the user still owns repos - db.AssertExistsAndLoadBean(t, &models.User{ID: 2}) + unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}) } diff --git a/integrations/empty_repo_test.go b/integrations/empty_repo_test.go index 7346c34b27eb..cbab67ba1e20 100644 --- a/integrations/empty_repo_test.go +++ b/integrations/empty_repo_test.go @@ -9,7 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestEmptyRepo(t *testing.T) { @@ -20,8 +20,8 @@ func TestEmptyRepo(t *testing.T) { "commit/1ae57b34ccf7e18373", "graph", } - emptyRepo := db.AssertExistsAndLoadBean(t, &models.Repository{}, db.Cond("is_empty = ?", true)).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: emptyRepo.OwnerID}).(*models.User) + emptyRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{}, unittest.Cond("is_empty = ?", true)).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: emptyRepo.OwnerID}).(*models.User) for _, subpath := range subpaths { req := NewRequestf(t, "GET", "/%s/%s/%s", owner.Name, emptyRepo.Name, subpath) MakeRequest(t, req, http.StatusNotFound) diff --git a/integrations/eventsource_test.go b/integrations/eventsource_test.go index 17c5ff8ab439..ead01da8ca8f 100644 --- a/integrations/eventsource_test.go +++ b/integrations/eventsource_test.go @@ -11,7 +11,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/eventsource" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -50,9 +50,9 @@ func TestEventSourceManagerRun(t *testing.T) { } } - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - thread5 := db.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + thread5 := unittest.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification) assert.NoError(t, thread5.LoadAttributes()) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/git_test.go b/integrations/git_test.go index 9a264c9448e0..cf84800eed86 100644 --- a/integrations/git_test.go +++ b/integrations/git_test.go @@ -18,7 +18,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/setting" @@ -631,7 +631,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB return } - pullNum := db.GetCount(t, &models.PullRequest{}) + pullNum := unittest.GetCount(t, &models.PullRequest{}) t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch)) @@ -667,8 +667,8 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB if !assert.NoError(t, err) { return } - db.AssertCount(t, &models.PullRequest{}, pullNum+1) - pr1 = db.AssertExistsAndLoadBean(t, &models.PullRequest{ + unittest.AssertCount(t, &models.PullRequest{}, pullNum+1) + pr1 = unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ HeadRepoID: repo.ID, Flow: models.PullRequestFlowAGit, }).(*models.PullRequest) @@ -688,8 +688,8 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB if !assert.NoError(t, err) { return } - db.AssertCount(t, &models.PullRequest{}, pullNum+2) - pr2 = db.AssertExistsAndLoadBean(t, &models.PullRequest{ + unittest.AssertCount(t, &models.PullRequest{}, pullNum+2) + pr2 = unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ HeadRepoID: repo.ID, Index: pr1.Index + 1, Flow: models.PullRequestFlowAGit, @@ -741,7 +741,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB if !assert.NoError(t, err) { return } - db.AssertCount(t, &models.PullRequest{}, pullNum+2) + unittest.AssertCount(t, &models.PullRequest{}, pullNum+2) prMsg, err := doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr1.Index)(t) if !assert.NoError(t, err) { return @@ -753,7 +753,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB if !assert.NoError(t, err) { return } - db.AssertCount(t, &models.PullRequest{}, pullNum+2) + unittest.AssertCount(t, &models.PullRequest{}, pullNum+2) prMsg, err = doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr2.Index)(t) if !assert.NoError(t, err) { return diff --git a/integrations/gpg_git_test.go b/integrations/gpg_git_test.go index 2cfb883fd933..ecc253978407 100644 --- a/integrations/gpg_git_test.go +++ b/integrations/gpg_git_test.go @@ -12,7 +12,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/process" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" @@ -60,7 +60,7 @@ func TestGPGGit(t *testing.T) { setting.Repository.Signing.SigningKey = rootKeyID setting.Repository.Signing.SigningName = "gitea" setting.Repository.Signing.SigningEmail = "gitea@fake.local" - user := db.AssertExistsAndLoadBean(t, &models.User{Name: username}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{Name: username}).(*models.User) setting.Repository.Signing.InitialCommit = []string{"never"} setting.Repository.Signing.CRUDActions = []string{"never"} diff --git a/integrations/integration_test.go b/integrations/integration_test.go index 1429893270b0..710e2b3b30a5 100644 --- a/integrations/integration_test.go +++ b/integrations/integration_test.go @@ -25,7 +25,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/graceful" @@ -112,8 +112,8 @@ func TestMain(m *testing.M) { } } - err := db.InitFixtures( - db.FixturesOptions{ + err := unittest.InitFixtures( + unittest.FixturesOptions{ Dir: filepath.Join(filepath.Dir(setting.AppPath), "models/fixtures/"), }, ) @@ -250,7 +250,7 @@ func prepareTestEnv(t testing.TB, skip ...int) func() { ourSkip += skip[0] } deferFn := PrintCurrentTest(t, ourSkip) - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath)) @@ -527,7 +527,7 @@ func GetCSRF(t testing.TB, session *TestSession, urlStr string) string { // within a single test this is required func resetFixtures(t *testing.T) { assert.NoError(t, queue.GetManager().FlushAll(context.Background(), -1)) - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath)) } diff --git a/integrations/issue_test.go b/integrations/issue_test.go index 1d7dbdabd77b..56cddcb0639c 100644 --- a/integrations/issue_test.go +++ b/integrations/issue_test.go @@ -14,7 +14,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/indexer/issues" "code.gitea.io/gitea/modules/references" "code.gitea.io/gitea/modules/setting" @@ -36,7 +36,7 @@ func getIssue(t *testing.T, repoID int64, issueSelection *goquery.Selection) *mo indexStr := href[strings.LastIndexByte(href, '/')+1:] index, err := strconv.Atoi(indexStr) assert.NoError(t, err, "Invalid issue href: %s", href) - return db.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repoID, Index: int64(index)}).(*models.Issue) + return unittest.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repoID, Index: int64(index)}).(*models.Issue) } func assertMatch(t testing.TB, issue *models.Issue, keyword string) { @@ -61,8 +61,8 @@ func TestNoLoginViewIssues(t *testing.T) { func TestViewIssuesSortByType(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) session := loginUser(t, user.Name) req := NewRequest(t, "GET", repo.Link()+"/issues?type=created_by") @@ -70,10 +70,10 @@ func TestViewIssuesSortByType(t *testing.T) { htmlDoc := NewHTMLParser(t, resp.Body) issuesSelection := getIssuesSelection(t, htmlDoc) - expectedNumIssues := db.GetCount(t, + expectedNumIssues := unittest.GetCount(t, &models.Issue{RepoID: repo.ID, PosterID: user.ID}, - db.Cond("is_closed=?", false), - db.Cond("is_pull=?", false), + unittest.Cond("is_closed=?", false), + unittest.Cond("is_pull=?", false), ) if expectedNumIssues > setting.UI.IssuePagingNum { expectedNumIssues = setting.UI.IssuePagingNum @@ -89,8 +89,8 @@ func TestViewIssuesSortByType(t *testing.T) { func TestViewIssuesKeyword(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - issue := db.AssertExistsAndLoadBean(t, &models.Issue{ + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ RepoID: repo.ID, Index: 1, }).(*models.Issue) @@ -236,7 +236,7 @@ func TestIssueCrossReference(t *testing.T) { // Ref from issue title issueRefURL, issueRef := testIssueWithBean(t, "user2", 1, fmt.Sprintf("Title ref #%d", issueBase.Index), "Description") - db.AssertExistsAndLoadBean(t, &models.Comment{ + unittest.AssertExistsAndLoadBean(t, &models.Comment{ IssueID: issueBase.ID, RefRepoID: 1, RefIssueID: issueRef.ID, @@ -246,7 +246,7 @@ func TestIssueCrossReference(t *testing.T) { // Edit title, neuter ref testIssueChangeInfo(t, "user2", issueRefURL, "title", "Title no ref") - db.AssertExistsAndLoadBean(t, &models.Comment{ + unittest.AssertExistsAndLoadBean(t, &models.Comment{ IssueID: issueBase.ID, RefRepoID: 1, RefIssueID: issueRef.ID, @@ -256,7 +256,7 @@ func TestIssueCrossReference(t *testing.T) { // Ref from issue content issueRefURL, issueRef = testIssueWithBean(t, "user2", 1, "TitleXRef", fmt.Sprintf("Description ref #%d", issueBase.Index)) - db.AssertExistsAndLoadBean(t, &models.Comment{ + unittest.AssertExistsAndLoadBean(t, &models.Comment{ IssueID: issueBase.ID, RefRepoID: 1, RefIssueID: issueRef.ID, @@ -266,7 +266,7 @@ func TestIssueCrossReference(t *testing.T) { // Edit content, neuter ref testIssueChangeInfo(t, "user2", issueRefURL, "content", "Description no ref") - db.AssertExistsAndLoadBean(t, &models.Comment{ + unittest.AssertExistsAndLoadBean(t, &models.Comment{ IssueID: issueBase.ID, RefRepoID: 1, RefIssueID: issueRef.ID, @@ -284,11 +284,11 @@ func TestIssueCrossReference(t *testing.T) { RefCommentID: commentID, RefIsPull: false, RefAction: references.XRefActionNone} - db.AssertExistsAndLoadBean(t, comment) + unittest.AssertExistsAndLoadBean(t, comment) // Ref from a different repository issueRefURL, issueRef = testIssueWithBean(t, "user12", 10, "TitleXRef", fmt.Sprintf("Description ref user2/repo1#%d", issueBase.Index)) - db.AssertExistsAndLoadBean(t, &models.Comment{ + unittest.AssertExistsAndLoadBean(t, &models.Comment{ IssueID: issueBase.ID, RefRepoID: 10, RefIssueID: issueRef.ID, @@ -304,7 +304,7 @@ func testIssueWithBean(t *testing.T, user string, repoID int64, title, content s index, err := strconv.Atoi(indexStr) assert.NoError(t, err, "Invalid issue href: %s", issueURL) issue := &models.Issue{RepoID: repoID, Index: int64(index)} - db.AssertExistsAndLoadBean(t, issue) + unittest.AssertExistsAndLoadBean(t, issue) return issueURL, issue } diff --git a/integrations/migrate_test.go b/integrations/migrate_test.go index c0d5d4fc75a9..e22da7db907e 100644 --- a/integrations/migrate_test.go +++ b/integrations/migrate_test.go @@ -9,17 +9,17 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" - "code.gitea.io/gitea/modules/migrations" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/services/migrations" "github.com/stretchr/testify/assert" ) func TestMigrateLocalPath(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - adminUser := db.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User) + adminUser := unittest.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User) old := setting.ImportLocalPaths setting.ImportLocalPaths = true diff --git a/integrations/mirror_pull_test.go b/integrations/mirror_pull_test.go index f396aac4b445..277118a595bc 100644 --- a/integrations/mirror_pull_test.go +++ b/integrations/mirror_pull_test.go @@ -9,9 +9,9 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" - migration "code.gitea.io/gitea/modules/migrations/base" + "code.gitea.io/gitea/modules/migration" "code.gitea.io/gitea/modules/repository" mirror_service "code.gitea.io/gitea/services/mirror" release_service "code.gitea.io/gitea/services/release" @@ -22,8 +22,8 @@ import ( func TestMirrorPull(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) repoPath := models.RepoPath(user.Name, repo.Name) opts := migration.MigrateOptions{ diff --git a/integrations/mirror_push_test.go b/integrations/mirror_push_test.go index 3d2966cfdcd4..d681b3c40894 100644 --- a/integrations/mirror_push_test.go +++ b/integrations/mirror_push_test.go @@ -12,7 +12,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" @@ -30,8 +30,8 @@ func testMirrorPush(t *testing.T, u *url.URL) { setting.Migrations.AllowLocalNetworks = true - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - srcRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + srcRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) mirrorRepo, err := repository.CreateRepository(user, user, models.CreateRepoOptions{ Name: "test-push-mirror", diff --git a/integrations/org_count_test.go b/integrations/org_count_test.go index bd64139b2fc2..c473ecd68aac 100644 --- a/integrations/org_count_test.go +++ b/integrations/org_count_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" ) @@ -111,7 +111,7 @@ func doCheckOrgCounts(username string, orgCounts map[string]int, strict bool, ca } return func(t *testing.T) { - user := db.AssertExistsAndLoadBean(t, &models.User{ + user := unittest.AssertExistsAndLoadBean(t, &models.User{ Name: username, }).(*models.User) diff --git a/integrations/privateactivity_test.go b/integrations/privateactivity_test.go index e7b618abd6ac..e45274ad43d5 100644 --- a/integrations/privateactivity_test.go +++ b/integrations/privateactivity_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -25,8 +25,8 @@ const privateActivityTestOtherUser = "user4" // activity helpers func testPrivateActivityDoSomethingForActionEntries(t *testing.T) { - repoBefore := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User) + repoBefore := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User) session := loginUser(t, privateActivityTestUser) token := getTokenForLoggedInUser(t, session) diff --git a/integrations/pull_merge_test.go b/integrations/pull_merge_test.go index 9ccc4043a061..4d5699fa53cd 100644 --- a/integrations/pull_merge_test.go +++ b/integrations/pull_merge_test.go @@ -17,7 +17,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" @@ -221,15 +221,15 @@ func TestCantMergeConflict(t *testing.T) { session.MakeRequest(t, req, 201) // Now this PR will be marked conflict - or at least a race will do - so drop down to pure code at this point... - user1 := db.AssertExistsAndLoadBean(t, &models.User{ + user1 := unittest.AssertExistsAndLoadBean(t, &models.User{ Name: "user1", }).(*models.User) - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ OwnerID: user1.ID, Name: "repo1", }).(*models.Repository) - pr := db.AssertExistsAndLoadBean(t, &models.PullRequest{ + pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ HeadRepoID: repo1.ID, BaseRepoID: repo1.ID, HeadBranch: "conflict", @@ -258,10 +258,10 @@ func TestCantMergeUnrelated(t *testing.T) { // Now we want to create a commit on a branch that is totally unrelated to our current head // Drop down to pure code at this point - user1 := db.AssertExistsAndLoadBean(t, &models.User{ + user1 := unittest.AssertExistsAndLoadBean(t, &models.User{ Name: "user1", }).(*models.User) - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ OwnerID: user1.ID, Name: "repo1", }).(*models.Repository) @@ -320,7 +320,7 @@ func TestCantMergeUnrelated(t *testing.T) { // Now this PR could be marked conflict - or at least a race may occur - so drop down to pure code at this point... gitRepo, err := git.OpenRepository(path) assert.NoError(t, err) - pr := db.AssertExistsAndLoadBean(t, &models.PullRequest{ + pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ HeadRepoID: repo1.ID, BaseRepoID: repo1.ID, HeadBranch: "unrelated", diff --git a/integrations/pull_update_test.go b/integrations/pull_update_test.go index ea3a4794a621..43cfe7debfa2 100644 --- a/integrations/pull_update_test.go +++ b/integrations/pull_update_test.go @@ -11,9 +11,8 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/repofiles" - repo_module "code.gitea.io/gitea/modules/repository" pull_service "code.gitea.io/gitea/services/pull" repo_service "code.gitea.io/gitea/services/repository" @@ -23,8 +22,8 @@ import ( func TestAPIPullUpdate(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { //Create PR to test - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - org26 := db.AssertExistsAndLoadBean(t, &models.User{ID: 26}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + org26 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 26}).(*models.User) pr := createOutdatedPR(t, user, org26) //Test GetDiverging @@ -51,8 +50,8 @@ func TestAPIPullUpdate(t *testing.T) { func TestAPIPullUpdateByRebase(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { //Create PR to test - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) - org26 := db.AssertExistsAndLoadBean(t, &models.User{ID: 26}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + org26 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 26}).(*models.User) pr := createOutdatedPR(t, user, org26) //Test GetDiverging @@ -89,7 +88,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *models.User) *models.PullReq assert.NoError(t, err) assert.NotEmpty(t, baseRepo) - headRepo, err := repo_module.ForkRepository(actor, forkOrg, models.ForkRepoOptions{ + headRepo, err := repo_service.ForkRepository(actor, forkOrg, models.ForkRepoOptions{ BaseRepo: baseRepo, Name: "repo-pr-update", Description: "desc", @@ -163,7 +162,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *models.User) *models.PullReq err = pull_service.NewPullRequest(baseRepo, pullIssue, nil, nil, pullRequest, nil) assert.NoError(t, err) - issue := db.AssertExistsAndLoadBean(t, &models.Issue{Title: "Test Pull -to-update-"}).(*models.Issue) + issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{Title: "Test Pull -to-update-"}).(*models.Issue) pr, err := models.GetPullRequestByIssueID(issue.ID) assert.NoError(t, err) diff --git a/integrations/release_test.go b/integrations/release_test.go index 2e9de316997d..1f15aba09a12 100644 --- a/integrations/release_test.go +++ b/integrations/release_test.go @@ -11,7 +11,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/test" @@ -134,7 +134,7 @@ func TestCreateReleasePaging(t *testing.T) { func TestViewReleaseListNoLogin(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) link := repo.Link() + "/releases" @@ -160,7 +160,7 @@ func TestViewReleaseListNoLogin(t *testing.T) { func TestViewReleaseListLogin(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) link := repo.Link() + "/releases" @@ -191,7 +191,7 @@ func TestViewReleaseListLogin(t *testing.T) { func TestViewTagsList(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) link := repo.Link() + "/tags" diff --git a/integrations/rename_branch_test.go b/integrations/rename_branch_test.go index 90c1f4d15f1b..a8138ff0c58e 100644 --- a/integrations/rename_branch_test.go +++ b/integrations/rename_branch_test.go @@ -9,7 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) @@ -39,6 +39,6 @@ func TestRenameBranch(t *testing.T) { assert.Equal(t, "/user2/repo1/src/branch/main/README.md", location) // check db - repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) assert.Equal(t, "main", repo1.DefaultBranch) } diff --git a/integrations/repo_fork_test.go b/integrations/repo_fork_test.go index f9a994fd8ef9..22b2169e2fe0 100644 --- a/integrations/repo_fork_test.go +++ b/integrations/repo_fork_test.go @@ -11,13 +11,13 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func testRepoFork(t *testing.T, session *TestSession, ownerName, repoName, forkOwnerName, forkRepoName string) *httptest.ResponseRecorder { - forkOwner := db.AssertExistsAndLoadBean(t, &models.User{Name: forkOwnerName}).(*models.User) + forkOwner := unittest.AssertExistsAndLoadBean(t, &models.User{Name: forkOwnerName}).(*models.User) // Step0: check the existence of the to-fork repo req := NewRequestf(t, "GET", "/%s/%s", forkOwnerName, forkRepoName) diff --git a/integrations/repo_generate_test.go b/integrations/repo_generate_test.go index 7afce7474a76..d1e28c2f081b 100644 --- a/integrations/repo_generate_test.go +++ b/integrations/repo_generate_test.go @@ -11,13 +11,13 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func testRepoGenerate(t *testing.T, session *TestSession, templateOwnerName, templateRepoName, generateOwnerName, generateRepoName string) *httptest.ResponseRecorder { - generateOwner := db.AssertExistsAndLoadBean(t, &models.User{Name: generateOwnerName}).(*models.User) + generateOwner := unittest.AssertExistsAndLoadBean(t, &models.User{Name: generateOwnerName}).(*models.User) // Step0: check the existence of the generated repo req := NewRequestf(t, "GET", "/%s/%s", generateOwnerName, generateRepoName) diff --git a/integrations/repo_tag_test.go b/integrations/repo_tag_test.go index abbc2c02fcb8..7bba055e2a57 100644 --- a/integrations/repo_tag_test.go +++ b/integrations/repo_tag_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/services/release" @@ -21,8 +21,8 @@ import ( func TestCreateNewTagProtected(t *testing.T) { defer prepareTestEnv(t)() - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + owner := unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) t.Run("API", func(t *testing.T) { defer PrintCurrentTest(t)() diff --git a/integrations/repo_watch_test.go b/integrations/repo_watch_test.go index 7ae9f1fe7fa9..6ff189975b98 100644 --- a/integrations/repo_watch_test.go +++ b/integrations/repo_watch_test.go @@ -9,7 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" ) @@ -18,8 +18,8 @@ func TestRepoWatch(t *testing.T) { // Test round-trip auto-watch setting.Service.AutoWatchOnChanges = true session := loginUser(t, "user2") - db.AssertNotExistsBean(t, &models.Watch{UserID: 2, RepoID: 3}) + unittest.AssertNotExistsBean(t, &models.Watch{UserID: 2, RepoID: 3}) testEditFile(t, session, "user3", "repo3", "master", "README.md", "Hello, World (Edited for watch)\n") - db.AssertExistsAndLoadBean(t, &models.Watch{UserID: 2, RepoID: 3, Mode: models.RepoWatchModeAuto}) + unittest.AssertExistsAndLoadBean(t, &models.Watch{UserID: 2, RepoID: 3, Mode: models.RepoWatchModeAuto}) }) } diff --git a/integrations/repofiles_delete_test.go b/integrations/repofiles_delete_test.go index 22fef4b03ef6..8150673e2b32 100644 --- a/integrations/repofiles_delete_test.go +++ b/integrations/repofiles_delete_test.go @@ -8,8 +8,9 @@ import ( "net/url" "testing" + "code.gitea.io/gitea/models/unittest" + "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/repofiles" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/test" @@ -67,7 +68,7 @@ func TestDeleteRepoFile(t *testing.T) { func testDeleteRepoFile(t *testing.T, u *url.URL) { // setup - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -106,7 +107,7 @@ func TestDeleteRepoFileWithoutBranchNames(t *testing.T) { func testDeleteRepoFileWithoutBranchNames(t *testing.T, u *url.URL) { // setup - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -136,7 +137,7 @@ func testDeleteRepoFileWithoutBranchNames(t *testing.T, u *url.URL) { func TestDeleteRepoFileErrors(t *testing.T) { // setup - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) diff --git a/integrations/signin_test.go b/integrations/signin_test.go index 081f87f0bd51..a920ed45dd3d 100644 --- a/integrations/signin_test.go +++ b/integrations/signin_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" "github.com/unknwon/i18n" @@ -34,13 +34,13 @@ func testLoginFailed(t *testing.T, username, password, message string) { func TestSignin(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // add new user with user2's email user.Name = "testuser" user.LowerName = strings.ToLower(user.Name) user.ID = 0 - db.AssertSuccessfulInsert(t, user) + unittest.AssertSuccessfulInsert(t, user) samples := []struct { username string diff --git a/integrations/signup_test.go b/integrations/signup_test.go index dccb1f6767b7..33e5809b289b 100644 --- a/integrations/signup_test.go +++ b/integrations/signup_test.go @@ -11,7 +11,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" "github.com/unknwon/i18n" @@ -53,7 +53,7 @@ func TestSignupAsRestricted(t *testing.T) { req = NewRequest(t, "GET", "/restrictedUser") MakeRequest(t, req, http.StatusOK) - user2 := db.AssertExistsAndLoadBean(t, &models.User{Name: "restrictedUser"}).(*models.User) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{Name: "restrictedUser"}).(*models.User) assert.True(t, user2.IsRestricted) } diff --git a/integrations/user_avatar_test.go b/integrations/user_avatar_test.go index f07b7c7fcfbf..e53f0e34fe34 100644 --- a/integrations/user_avatar_test.go +++ b/integrations/user_avatar_test.go @@ -14,14 +14,14 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/avatar" "github.com/stretchr/testify/assert" ) func TestUserAvatar(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo3, is an org + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo3, is an org seed := user2.Email if len(seed) == 0 { @@ -71,7 +71,7 @@ func TestUserAvatar(t *testing.T) { session.MakeRequest(t, req, http.StatusFound) - user2 = db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo3, is an org + user2 = unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo3, is an org req = NewRequest(t, "GET", user2.AvatarLinkWithSize(0)) _ = session.MakeRequest(t, req, http.StatusOK) diff --git a/integrations/user_test.go b/integrations/user_test.go index f9e507afbea1..b70bf212b09f 100644 --- a/integrations/user_test.go +++ b/integrations/user_test.go @@ -9,7 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" @@ -35,8 +35,8 @@ func TestRenameUsername(t *testing.T) { }) session.MakeRequest(t, req, http.StatusFound) - db.AssertExistsAndLoadBean(t, &models.User{Name: "newUsername"}) - db.AssertNotExistsBean(t, &models.User{Name: "user2"}) + unittest.AssertExistsAndLoadBean(t, &models.User{Name: "newUsername"}) + unittest.AssertNotExistsBean(t, &models.User{Name: "user2"}) } func TestRenameInvalidUsername(t *testing.T) { @@ -67,7 +67,7 @@ func TestRenameInvalidUsername(t *testing.T) { i18n.Tr("en", "form.alpha_dash_dot_error"), ) - db.AssertNotExistsBean(t, &models.User{Name: invalidUsername}) + unittest.AssertNotExistsBean(t, &models.User{Name: invalidUsername}) } } @@ -113,7 +113,7 @@ func TestRenameReservedUsername(t *testing.T) { i18n.Tr("en", "user.form.name_reserved", reservedUsername), ) - db.AssertNotExistsBean(t, &models.User{Name: reservedUsername}) + unittest.AssertNotExistsBean(t, &models.User{Name: reservedUsername}) } } diff --git a/integrations/xss_test.go b/integrations/xss_test.go index 427c97de265b..8128a54aa374 100644 --- a/integrations/xss_test.go +++ b/integrations/xss_test.go @@ -9,14 +9,14 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestXSSUserFullName(t *testing.T) { defer prepareTestEnv(t)() - user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) + user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) const fullName = `name & ` session := loginUser(t, user.Name) diff --git a/jest.config.js b/jest.config.js index c94113d6f423..690f58d17719 100644 --- a/jest.config.js +++ b/jest.config.js @@ -4,7 +4,9 @@ export default { testEnvironment: 'jsdom', testMatch: ['/**/*.test.js'], testTimeout: 20000, - transform: {}, + transform: { + '\\.svg$': 'jest-raw-loader', + }, verbose: false, }; diff --git a/models/access_test.go b/models/access_test.go index 2f641bb9b573..96aa34edb648 100644 --- a/models/access_test.go +++ b/models/access_test.go @@ -8,27 +8,28 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestAccessLevel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - user5 := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) - user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) + user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user5 := unittest.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) + user29 := unittest.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) // A public repository owned by User 2 - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.False(t, repo1.IsPrivate) // A private repository owned by Org 3 - repo3 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) + repo3 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) assert.True(t, repo3.IsPrivate) // Another public repository - repo4 := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) + repo4 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) assert.False(t, repo4.IsPrivate) // org. owned private repo - repo24 := db.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository) + repo24 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository) level, err := AccessLevel(user2, repo1) assert.NoError(t, err) @@ -63,15 +64,15 @@ func TestAccessLevel(t *testing.T) { } func TestHasAccess(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user1 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - user2 := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) + user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) // A public repository owned by User 2 - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.False(t, repo1.IsPrivate) // A private repository owned by Org 3 - repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) + repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) assert.True(t, repo2.IsPrivate) has, err := HasAccess(user1.ID, repo1) @@ -89,33 +90,33 @@ func TestHasAccess(t *testing.T) { } func TestUser_GetRepositoryAccesses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) accesses, err := user1.GetRepositoryAccesses() assert.NoError(t, err) assert.Len(t, accesses, 0) - user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) + user29 := unittest.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) accesses, err = user29.GetRepositoryAccesses() assert.NoError(t, err) assert.Len(t, accesses, 2) } func TestUser_GetAccessibleRepositories(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) repos, err := user1.GetAccessibleRepositories(0) assert.NoError(t, err) assert.Len(t, repos, 0) - user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) repos, err = user2.GetAccessibleRepositories(0) assert.NoError(t, err) assert.Len(t, repos, 4) - user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) + user29 := unittest.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) repos, err = user29.GetAccessibleRepositories(0) assert.NoError(t, err) assert.Len(t, repos, 2) @@ -123,8 +124,8 @@ func TestUser_GetAccessibleRepositories(t *testing.T) { func TestRepository_RecalculateAccesses(t *testing.T) { // test with organization repo - assert.NoError(t, db.PrepareTestDatabase()) - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) assert.NoError(t, repo1.GetOwner()) _, err := db.GetEngine(db.DefaultContext).Delete(&Collaboration{UserID: 2, RepoID: 3}) @@ -140,8 +141,8 @@ func TestRepository_RecalculateAccesses(t *testing.T) { func TestRepository_RecalculateAccesses2(t *testing.T) { // test with non-organization repo - assert.NoError(t, db.PrepareTestDatabase()) - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) assert.NoError(t, repo1.GetOwner()) _, err := db.GetEngine(db.DefaultContext).Delete(&Collaboration{UserID: 4, RepoID: 4}) @@ -154,9 +155,9 @@ func TestRepository_RecalculateAccesses2(t *testing.T) { } func TestRepository_RecalculateAccesses3(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - team5 := db.AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team) - user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + team5 := unittest.AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team) + user29 := unittest.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) has, err := db.GetEngine(db.DefaultContext).Get(&Access{UserID: 29, RepoID: 23}) assert.NoError(t, err) diff --git a/models/action_test.go b/models/action_test.go index 78090e3aadbb..87bbcf3fb775 100644 --- a/models/action_test.go +++ b/models/action_test.go @@ -8,24 +8,24 @@ import ( "path" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestAction_GetRepoPath(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{}).(*Repository) - owner := db.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{}).(*Repository) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) action := &Action{RepoID: repo.ID} assert.Equal(t, path.Join(owner.Name, repo.Name), action.GetRepoPath()) } func TestAction_GetRepoLink(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{}).(*Repository) - owner := db.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{}).(*Repository) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) action := &Action{RepoID: repo.ID} setting.AppSubURL = "/suburl" expected := path.Join(setting.AppSubURL, owner.Name, repo.Name) @@ -34,8 +34,8 @@ func TestAction_GetRepoLink(t *testing.T) { func TestGetFeeds(t *testing.T) { // test with an individual user - assert.NoError(t, db.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) actions, err := GetFeeds(GetFeedsOptions{ RequestedUser: user, @@ -62,9 +62,9 @@ func TestGetFeeds(t *testing.T) { func TestGetFeeds2(t *testing.T) { // test with an organization user - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) actions, err := GetFeeds(GetFeedsOptions{ RequestedUser: org, diff --git a/models/admin_test.go b/models/admin_test.go index 316ed5cb683d..95415731b240 100644 --- a/models/admin_test.go +++ b/models/admin_test.go @@ -7,7 +7,7 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) @@ -20,38 +20,38 @@ func TestNotice_TrStr(t *testing.T) { } func TestCreateNotice(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) noticeBean := &Notice{ Type: NoticeRepository, Description: "test description", } - db.AssertNotExistsBean(t, noticeBean) + unittest.AssertNotExistsBean(t, noticeBean) assert.NoError(t, CreateNotice(noticeBean.Type, noticeBean.Description)) - db.AssertExistsAndLoadBean(t, noticeBean) + unittest.AssertExistsAndLoadBean(t, noticeBean) } func TestCreateRepositoryNotice(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) noticeBean := &Notice{ Type: NoticeRepository, Description: "test description", } - db.AssertNotExistsBean(t, noticeBean) + unittest.AssertNotExistsBean(t, noticeBean) assert.NoError(t, CreateRepositoryNotice(noticeBean.Description)) - db.AssertExistsAndLoadBean(t, noticeBean) + unittest.AssertExistsAndLoadBean(t, noticeBean) } // TODO TestRemoveAllWithNotice func TestCountNotices(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.Equal(t, int64(3), CountNotices()) } func TestNotices(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) notices, err := Notices(1, 2) assert.NoError(t, err) @@ -68,47 +68,47 @@ func TestNotices(t *testing.T) { } func TestDeleteNotice(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - db.AssertExistsAndLoadBean(t, &Notice{ID: 3}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 3}) assert.NoError(t, DeleteNotice(3)) - db.AssertNotExistsBean(t, &Notice{ID: 3}) + unittest.AssertNotExistsBean(t, &Notice{ID: 3}) } func TestDeleteNotices(t *testing.T) { // delete a non-empty range - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - db.AssertExistsAndLoadBean(t, &Notice{ID: 1}) - db.AssertExistsAndLoadBean(t, &Notice{ID: 2}) - db.AssertExistsAndLoadBean(t, &Notice{ID: 3}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 1}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 2}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 3}) assert.NoError(t, DeleteNotices(1, 2)) - db.AssertNotExistsBean(t, &Notice{ID: 1}) - db.AssertNotExistsBean(t, &Notice{ID: 2}) - db.AssertExistsAndLoadBean(t, &Notice{ID: 3}) + unittest.AssertNotExistsBean(t, &Notice{ID: 1}) + unittest.AssertNotExistsBean(t, &Notice{ID: 2}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 3}) } func TestDeleteNotices2(t *testing.T) { // delete an empty range - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - db.AssertExistsAndLoadBean(t, &Notice{ID: 1}) - db.AssertExistsAndLoadBean(t, &Notice{ID: 2}) - db.AssertExistsAndLoadBean(t, &Notice{ID: 3}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 1}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 2}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 3}) assert.NoError(t, DeleteNotices(3, 2)) - db.AssertExistsAndLoadBean(t, &Notice{ID: 1}) - db.AssertExistsAndLoadBean(t, &Notice{ID: 2}) - db.AssertExistsAndLoadBean(t, &Notice{ID: 3}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 1}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 2}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 3}) } func TestDeleteNoticesByIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - db.AssertExistsAndLoadBean(t, &Notice{ID: 1}) - db.AssertExistsAndLoadBean(t, &Notice{ID: 2}) - db.AssertExistsAndLoadBean(t, &Notice{ID: 3}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 1}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 2}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 3}) assert.NoError(t, DeleteNoticesByIDs([]int64{1, 3})) - db.AssertNotExistsBean(t, &Notice{ID: 1}) - db.AssertExistsAndLoadBean(t, &Notice{ID: 2}) - db.AssertNotExistsBean(t, &Notice{ID: 3}) + unittest.AssertNotExistsBean(t, &Notice{ID: 1}) + unittest.AssertExistsAndLoadBean(t, &Notice{ID: 2}) + unittest.AssertNotExistsBean(t, &Notice{ID: 3}) } diff --git a/models/attachment_test.go b/models/attachment_test.go index c7f456341cdc..c3949905363b 100644 --- a/models/attachment_test.go +++ b/models/attachment_test.go @@ -9,11 +9,12 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestIncreaseDownloadCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) attachment, err := GetAttachmentByUUID("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11") assert.NoError(t, err) @@ -29,7 +30,7 @@ func TestIncreaseDownloadCount(t *testing.T) { } func TestGetByCommentOrIssueID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // count of attachments from issue ID attachments, err := GetAttachmentsByIssueID(1) @@ -42,7 +43,7 @@ func TestGetByCommentOrIssueID(t *testing.T) { } func TestDeleteAttachments(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) count, err := DeleteAttachmentsByIssue(4, false) assert.NoError(t, err) @@ -62,7 +63,7 @@ func TestDeleteAttachments(t *testing.T) { } func TestGetAttachmentByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) attach, err := GetAttachmentByID(1) assert.NoError(t, err) @@ -78,7 +79,7 @@ func TestAttachment_DownloadURL(t *testing.T) { } func TestUpdateAttachment(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) attach, err := GetAttachmentByID(1) assert.NoError(t, err) @@ -87,11 +88,11 @@ func TestUpdateAttachment(t *testing.T) { attach.Name = "new_name" assert.NoError(t, UpdateAttachment(attach)) - db.AssertExistsAndLoadBean(t, &Attachment{Name: "new_name"}) + unittest.AssertExistsAndLoadBean(t, &Attachment{Name: "new_name"}) } func TestGetAttachmentsByUUIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) attachList, err := GetAttachmentsByUUIDs(db.DefaultContext, []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"}) assert.NoError(t, err) @@ -103,7 +104,7 @@ func TestGetAttachmentsByUUIDs(t *testing.T) { } func TestLinkedRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testCases := []struct { name string attachID int64 diff --git a/models/branches_test.go b/models/branches_test.go index e9a32666f9da..787dd7fe8365 100644 --- a/models/branches_test.go +++ b/models/branches_test.go @@ -7,22 +7,22 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestAddDeletedBranch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + firstBranch := unittest.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) assert.Error(t, repo.AddDeletedBranch(firstBranch.Name, firstBranch.Commit, firstBranch.DeletedByID)) assert.NoError(t, repo.AddDeletedBranch("test", "5655464564554545466464656", int64(1))) } func TestGetDeletedBranches(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) branches, err := repo.GetDeletedBranches() assert.NoError(t, err) @@ -30,17 +30,17 @@ func TestGetDeletedBranches(t *testing.T) { } func TestGetDeletedBranch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) + assert.NoError(t, unittest.PrepareTestDatabase()) + firstBranch := unittest.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) assert.NotNil(t, getDeletedBranch(t, firstBranch)) } func TestDeletedBranchLoadUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) - secondBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 2}).(*DeletedBranch) + firstBranch := unittest.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) + secondBranch := unittest.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 2}).(*DeletedBranch) branch := getDeletedBranch(t, firstBranch) assert.Nil(t, branch.DeletedBy) @@ -56,19 +56,19 @@ func TestDeletedBranchLoadUser(t *testing.T) { } func TestRemoveDeletedBranch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) + firstBranch := unittest.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) err := repo.RemoveDeletedBranch(1) assert.NoError(t, err) - db.AssertNotExistsBean(t, firstBranch) - db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 2}) + unittest.AssertNotExistsBean(t, firstBranch) + unittest.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 2}) } func getDeletedBranch(t *testing.T, branch *DeletedBranch) *DeletedBranch { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) deletedBranch, err := repo.GetDeletedBranchByID(branch.ID) assert.NoError(t, err) @@ -81,7 +81,7 @@ func getDeletedBranch(t *testing.T, branch *DeletedBranch) *DeletedBranch { } func TestFindRenamedBranch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) branch, exist, err := FindRenamedBranch(1, "dev") assert.NoError(t, err) assert.Equal(t, true, exist) @@ -93,8 +93,8 @@ func TestFindRenamedBranch(t *testing.T) { } func TestRenameBranch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) _isDefault := false err := UpdateProtectBranch(repo1, &ProtectedBranch{ @@ -109,33 +109,33 @@ func TestRenameBranch(t *testing.T) { })) assert.Equal(t, true, _isDefault) - repo1 = db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo1 = unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.Equal(t, "main", repo1.DefaultBranch) - pull := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) // merged + pull := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) // merged assert.Equal(t, "master", pull.BaseBranch) - pull = db.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) // open + pull = unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) // open assert.Equal(t, "main", pull.BaseBranch) - renamedBranch := db.AssertExistsAndLoadBean(t, &RenamedBranch{ID: 2}).(*RenamedBranch) + renamedBranch := unittest.AssertExistsAndLoadBean(t, &RenamedBranch{ID: 2}).(*RenamedBranch) assert.Equal(t, "master", renamedBranch.From) assert.Equal(t, "main", renamedBranch.To) assert.Equal(t, int64(1), renamedBranch.RepoID) - db.AssertExistsAndLoadBean(t, &ProtectedBranch{ + unittest.AssertExistsAndLoadBean(t, &ProtectedBranch{ RepoID: repo1.ID, BranchName: "main", }) } func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Get deletedBranch with ID of 1 on repo with ID 2. // This should return a nil branch as this deleted branch // is actually on repo with ID 1. - repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) + repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) deletedBranch, err := repo2.GetDeletedBranchByID(1) @@ -145,7 +145,7 @@ func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) { // Now get the deletedBranch with ID of 1 on repo with ID 1. // This should return the deletedBranch. - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) deletedBranch, err = repo1.GetDeletedBranchByID(1) diff --git a/models/commit_status_test.go b/models/commit_status_test.go index 7f4709144ceb..32d6a433ce05 100644 --- a/models/commit_status_test.go +++ b/models/commit_status_test.go @@ -8,14 +8,15 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" ) func TestGetCommitStatuses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) sha1 := "1234123412341234123412341234123412341234" diff --git a/models/consistency.go b/models/consistency.go index ab814569160d..d7bf8ade5758 100644 --- a/models/consistency.go +++ b/models/consistency.go @@ -5,190 +5,11 @@ package models import ( - "reflect" - "strings" - "testing" - "code.gitea.io/gitea/models/db" - "github.com/stretchr/testify/assert" "xorm.io/builder" ) -// CheckConsistencyForAll test that the entire database is consistent -func CheckConsistencyForAll(t *testing.T) { - CheckConsistencyFor(t, - &User{}, - &Repository{}, - &Issue{}, - &PullRequest{}, - &Milestone{}, - &Label{}, - &Team{}, - &Action{}) -} - -// CheckConsistencyFor test that all matching database entries are consistent -func CheckConsistencyFor(t *testing.T, beansToCheck ...interface{}) { - for _, bean := range beansToCheck { - sliceType := reflect.SliceOf(reflect.TypeOf(bean)) - sliceValue := reflect.MakeSlice(sliceType, 0, 10) - - ptrToSliceValue := reflect.New(sliceType) - ptrToSliceValue.Elem().Set(sliceValue) - - assert.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface())) - sliceValue = ptrToSliceValue.Elem() - - for i := 0; i < sliceValue.Len(); i++ { - entity := sliceValue.Index(i).Interface() - checkForConsistency(entity, t) - } - } -} - -func checkForConsistency(bean interface{}, t *testing.T) { - switch b := bean.(type) { - case *User: - checkForUserConsistency(b, t) - case *Repository: - checkForRepoConsistency(b, t) - case *Issue: - checkForIssueConsistency(b, t) - case *PullRequest: - checkForPullRequestConsistency(b, t) - case *Milestone: - checkForMilestoneConsistency(b, t) - case *Label: - checkForLabelConsistency(b, t) - case *Team: - checkForTeamConsistency(b, t) - case *Action: - checkForActionConsistency(b, t) - default: - t.Errorf("unknown bean type: %#v", bean) - } -} - -// getCount get the count of database entries matching bean -func getCount(t *testing.T, e db.Engine, bean interface{}) int64 { - count, err := e.Count(bean) - assert.NoError(t, err) - return count -} - -// assertCount test the count of database entries matching bean -func assertCount(t *testing.T, bean interface{}, expected int) { - assert.EqualValues(t, expected, getCount(t, db.GetEngine(db.DefaultContext), bean), - "Failed consistency test, the counted bean (of type %T) was %+v", bean, bean) -} - -func checkForUserConsistency(user *User, t *testing.T) { - assertCount(t, &Repository{OwnerID: user.ID}, user.NumRepos) - assertCount(t, &Star{UID: user.ID}, user.NumStars) - assertCount(t, &OrgUser{OrgID: user.ID}, user.NumMembers) - assertCount(t, &Team{OrgID: user.ID}, user.NumTeams) - assertCount(t, &Follow{UserID: user.ID}, user.NumFollowing) - assertCount(t, &Follow{FollowID: user.ID}, user.NumFollowers) - if user.Type != UserTypeOrganization { - assert.EqualValues(t, 0, user.NumMembers) - assert.EqualValues(t, 0, user.NumTeams) - } -} - -func checkForRepoConsistency(repo *Repository, t *testing.T) { - assert.Equal(t, repo.LowerName, strings.ToLower(repo.Name), "repo: %+v", repo) - assertCount(t, &Star{RepoID: repo.ID}, repo.NumStars) - assertCount(t, &Milestone{RepoID: repo.ID}, repo.NumMilestones) - assertCount(t, &Repository{ForkID: repo.ID}, repo.NumForks) - if repo.IsFork { - db.AssertExistsAndLoadBean(t, &Repository{ID: repo.ForkID}) - } - - actual := getCount(t, db.GetEngine(db.DefaultContext).Where("Mode<>?", RepoWatchModeDont), &Watch{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumWatches, actual, - "Unexpected number of watches for repo %+v", repo) - - actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=?", false), &Issue{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumIssues, actual, - "Unexpected number of issues for repo %+v", repo) - - actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=? AND is_closed=?", false, true), &Issue{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumClosedIssues, actual, - "Unexpected number of closed issues for repo %+v", repo) - - actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=?", true), &Issue{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumPulls, actual, - "Unexpected number of pulls for repo %+v", repo) - - actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=? AND is_closed=?", true, true), &Issue{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumClosedPulls, actual, - "Unexpected number of closed pulls for repo %+v", repo) - - actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_closed=?", true), &Milestone{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumClosedMilestones, actual, - "Unexpected number of closed milestones for repo %+v", repo) -} - -func checkForIssueConsistency(issue *Issue, t *testing.T) { - actual := getCount(t, db.GetEngine(db.DefaultContext).Where("type=?", CommentTypeComment), &Comment{IssueID: issue.ID}) - assert.EqualValues(t, issue.NumComments, actual, - "Unexpected number of comments for issue %+v", issue) - if issue.IsPull { - pr := db.AssertExistsAndLoadBean(t, &PullRequest{IssueID: issue.ID}).(*PullRequest) - assert.EqualValues(t, pr.Index, issue.Index) - } -} - -func checkForPullRequestConsistency(pr *PullRequest, t *testing.T) { - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: pr.IssueID}).(*Issue) - assert.True(t, issue.IsPull) - assert.EqualValues(t, issue.Index, pr.Index) -} - -func checkForMilestoneConsistency(milestone *Milestone, t *testing.T) { - assertCount(t, &Issue{MilestoneID: milestone.ID}, milestone.NumIssues) - - actual := getCount(t, db.GetEngine(db.DefaultContext).Where("is_closed=?", true), &Issue{MilestoneID: milestone.ID}) - assert.EqualValues(t, milestone.NumClosedIssues, actual, - "Unexpected number of closed issues for milestone %+v", milestone) - - completeness := 0 - if milestone.NumIssues > 0 { - completeness = milestone.NumClosedIssues * 100 / milestone.NumIssues - } - assert.Equal(t, completeness, milestone.Completeness) -} - -func checkForLabelConsistency(label *Label, t *testing.T) { - issueLabels := make([]*IssueLabel, 0, 10) - assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&issueLabels, &IssueLabel{LabelID: label.ID})) - assert.EqualValues(t, label.NumIssues, len(issueLabels), - "Unexpected number of issue for label %+v", label) - - issueIDs := make([]int64, len(issueLabels)) - for i, issueLabel := range issueLabels { - issueIDs[i] = issueLabel.IssueID - } - - expected := int64(0) - if len(issueIDs) > 0 { - expected = getCount(t, db.GetEngine(db.DefaultContext).In("id", issueIDs).Where("is_closed=?", true), &Issue{}) - } - assert.EqualValues(t, expected, label.NumClosedIssues, - "Unexpected number of closed issues for label %+v", label) -} - -func checkForTeamConsistency(team *Team, t *testing.T) { - assertCount(t, &TeamUser{TeamID: team.ID}, team.NumMembers) - assertCount(t, &TeamRepo{TeamID: team.ID}, team.NumRepos) -} - -func checkForActionConsistency(action *Action, t *testing.T) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: action.RepoID}).(*Repository) - assert.Equal(t, repo.IsPrivate, action.IsPrivate, "action: %+v", action) -} - // CountOrphanedLabels return count of labels witch are broken and not accessible via ui anymore func CountOrphanedLabels() (int64, error) { noref, err := db.GetEngine(db.DefaultContext).Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count("label.id") diff --git a/models/consistency_test.go b/models/consistency_test.go index 8332b5d76191..6995f47c87e2 100644 --- a/models/consistency_test.go +++ b/models/consistency_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestDeleteOrphanedObjects(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) countBefore, err := db.GetEngine(db.DefaultContext).Count(&PullRequest{}) assert.NoError(t, err) diff --git a/models/db/engine.go b/models/db/engine.go index d5f2470a7af6..e392008020b2 100755 --- a/models/db/engine.go +++ b/models/db/engine.go @@ -124,7 +124,8 @@ func NewEngine() (*xorm.Engine, error) { return engine, nil } -func syncTables() error { +//SyncAllTables sync the schemas of all tables, is required by unit test code +func SyncAllTables() error { return x.StoreEngine("InnoDB").Sync2(tables...) } @@ -152,6 +153,15 @@ func InitEngine(ctx context.Context) (err error) { return nil } +// SetEngine is used by unit test code +func SetEngine(eng *xorm.Engine) { + x = eng + DefaultContext = &Context{ + Context: context.Background(), + e: x, + } +} + // InitEngineWithMigration initializes a new xorm.Engine // This function must never call .Sync2() if the provided migration function fails. // When called from the "doctor" command, the migration function is a version check @@ -176,7 +186,7 @@ func InitEngineWithMigration(ctx context.Context, migrateFunc func(*xorm.Engine) return fmt.Errorf("migrate: %v", err) } - if err = syncTables(); err != nil { + if err = SyncAllTables(); err != nil { return fmt.Errorf("sync database struct error: %v", err) } diff --git a/models/db/main_test.go b/models/db/paginator/main_test.go similarity index 67% rename from models/db/main_test.go rename to models/db/paginator/main_test.go index f34ff65813c1..601ed89710a3 100644 --- a/models/db/main_test.go +++ b/models/db/paginator/main_test.go @@ -2,13 +2,15 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package db +package paginator import ( "path/filepath" "testing" + + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } diff --git a/models/db/paginator/paginator.go b/models/db/paginator/paginator.go new file mode 100644 index 000000000000..747539f30ea6 --- /dev/null +++ b/models/db/paginator/paginator.go @@ -0,0 +1,8 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package paginator + +// dummy only. in the future, the models/db/list_options.go should be moved here to decouple from db package +// otherwise the unit test will cause cycle import diff --git a/models/db/list_options_test.go b/models/db/paginator/paginator_test.go similarity index 79% rename from models/db/list_options_test.go rename to models/db/paginator/paginator_test.go index 2c860afdfbdd..fdb8eee4417a 100644 --- a/models/db/list_options_test.go +++ b/models/db/paginator/paginator_test.go @@ -2,11 +2,12 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package db +package paginator import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" @@ -14,35 +15,35 @@ import ( func TestPaginator(t *testing.T) { cases := []struct { - Paginator + db.Paginator Skip int Take int Start int End int }{ { - Paginator: &ListOptions{Page: -1, PageSize: -1}, + Paginator: &db.ListOptions{Page: -1, PageSize: -1}, Skip: 0, Take: setting.API.DefaultPagingNum, Start: 0, End: setting.API.DefaultPagingNum, }, { - Paginator: &ListOptions{Page: 2, PageSize: 10}, + Paginator: &db.ListOptions{Page: 2, PageSize: 10}, Skip: 10, Take: 10, Start: 10, End: 20, }, { - Paginator: NewAbsoluteListOptions(-1, -1), + Paginator: db.NewAbsoluteListOptions(-1, -1), Skip: 0, Take: setting.API.DefaultPagingNum, Start: 0, End: setting.API.DefaultPagingNum, }, { - Paginator: NewAbsoluteListOptions(2, 10), + Paginator: db.NewAbsoluteListOptions(2, 10), Skip: 2, Take: 10, Start: 2, diff --git a/models/engine_test.go b/models/engine_test.go index d97fc3cc197a..75c854b185f2 100644 --- a/models/engine_test.go +++ b/models/engine_test.go @@ -10,13 +10,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestDumpDatabase(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) dir, err := os.MkdirTemp(os.TempDir(), "dump") assert.NoError(t, err) diff --git a/models/fixture_test.go b/models/fixture_test.go index 3c6ebc06850d..0857341e4447 100644 --- a/models/fixture_test.go +++ b/models/fixture_test.go @@ -9,21 +9,21 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" ) func TestFixtureGeneration(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(gen func() (string, error), name string) { expected, err := gen() if !assert.NoError(t, err) { return } - bytes, err := os.ReadFile(filepath.Join(db.FixturesDir(), name+".yml")) + bytes, err := os.ReadFile(filepath.Join(unittest.FixturesDir(), name+".yml")) if !assert.NoError(t, err) { return } diff --git a/models/gpg_key_test.go b/models/gpg_key_test.go index 7a3cbfd67fea..e5f4960b7666 100644 --- a/models/gpg_key_test.go +++ b/models/gpg_key_test.go @@ -8,7 +8,7 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" @@ -193,9 +193,9 @@ Unknown GPG key with good email } func TestCheckGPGUserEmail(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - _ = db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + _ = unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) testEmailWithUpperCaseLetters := `-----BEGIN PGP PUBLIC KEY BLOCK----- Version: GnuPG v1 diff --git a/models/issue_assignees_test.go b/models/issue_assignees_test.go index 5052df3dfb10..8e2256072a59 100644 --- a/models/issue_assignees_test.go +++ b/models/issue_assignees_test.go @@ -7,12 +7,12 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestUpdateAssignee(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Fake issue with assignees issue, err := GetIssueWithAttrsByID(1) @@ -62,10 +62,10 @@ func TestUpdateAssignee(t *testing.T) { } func TestMakeIDsFromAPIAssigneesToAdd(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - _ = db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) - _ = db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + _ = unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + _ = unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) IDs, err := MakeIDsFromAPIAssigneesToAdd("", []string{""}) assert.NoError(t, err) diff --git a/models/issue_comment_test.go b/models/issue_comment_test.go index 78199881c602..27c50a3ae4c6 100644 --- a/models/issue_comment_test.go +++ b/models/issue_comment_test.go @@ -8,16 +8,16 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestCreateComment(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{}).(*Issue) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository) - doer := db.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{}).(*Issue) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository) + doer := unittest.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) now := time.Now().Unix() comment, err := CreateComment(&CreateCommentOptions{ @@ -34,18 +34,18 @@ func TestCreateComment(t *testing.T) { assert.EqualValues(t, "Hello", comment.Content) assert.EqualValues(t, issue.ID, comment.IssueID) assert.EqualValues(t, doer.ID, comment.PosterID) - db.AssertInt64InRange(t, now, then, int64(comment.CreatedUnix)) - db.AssertExistsAndLoadBean(t, comment) // assert actually added to DB + unittest.AssertInt64InRange(t, now, then, int64(comment.CreatedUnix)) + unittest.AssertExistsAndLoadBean(t, comment) // assert actually added to DB - updatedIssue := db.AssertExistsAndLoadBean(t, &Issue{ID: issue.ID}).(*Issue) - db.AssertInt64InRange(t, now, then, int64(updatedIssue.UpdatedUnix)) + updatedIssue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: issue.ID}).(*Issue) + unittest.AssertInt64InRange(t, now, then, int64(updatedIssue.UpdatedUnix)) } func TestFetchCodeComments(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) - user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) res, err := FetchCodeComments(issue, user) assert.NoError(t, err) assert.Contains(t, res, "README.md") @@ -53,7 +53,7 @@ func TestFetchCodeComments(t *testing.T) { assert.Len(t, res["README.md"][4], 1) assert.Equal(t, int64(4), res["README.md"][4][0].ID) - user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) res, err = FetchCodeComments(issue, user2) assert.NoError(t, err) assert.Len(t, res, 1) diff --git a/models/issue_dependency_test.go b/models/issue_dependency_test.go index 10872645b081..c357d35c501f 100644 --- a/models/issue_dependency_test.go +++ b/models/issue_dependency_test.go @@ -7,13 +7,13 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestCreateIssueDependency(t *testing.T) { // Prepare - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1, err := GetUserByID(1) assert.NoError(t, err) @@ -38,7 +38,7 @@ func TestCreateIssueDependency(t *testing.T) { assert.Error(t, err) assert.True(t, IsErrCircularDependency(err)) - _ = db.AssertExistsAndLoadBean(t, &Comment{Type: CommentTypeAddDependency, PosterID: user1.ID, IssueID: issue1.ID}) + _ = unittest.AssertExistsAndLoadBean(t, &Comment{Type: CommentTypeAddDependency, PosterID: user1.ID, IssueID: issue1.ID}) // Check if dependencies left is correct left, err := IssueNoDependenciesLeft(issue1) diff --git a/models/issue_label_test.go b/models/issue_label_test.go index 93807a326f80..658c459ba527 100644 --- a/models/issue_label_test.go +++ b/models/issue_label_test.go @@ -9,29 +9,30 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) // TODO TestGetLabelTemplateFile func TestLabel_CalOpenIssues(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - label := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) + assert.NoError(t, unittest.PrepareTestDatabase()) + label := unittest.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) label.CalOpenIssues() assert.EqualValues(t, 2, label.NumOpenIssues) } func TestLabel_ForegroundColor(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - label := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) + assert.NoError(t, unittest.PrepareTestDatabase()) + label := unittest.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) assert.Equal(t, template.CSS("#000"), label.ForegroundColor()) - label = db.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) + label = unittest.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) assert.Equal(t, template.CSS("#fff"), label.ForegroundColor()) } func TestNewLabels(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) labels := []*Label{ {RepoID: 2, Name: "labelName2", Color: "#123456"}, {RepoID: 3, Name: "labelName3", Color: "#23456F"}, @@ -40,27 +41,27 @@ func TestNewLabels(t *testing.T) { assert.Error(t, NewLabel(&Label{RepoID: 3, Name: "invalid Color", Color: "123456"})) assert.Error(t, NewLabel(&Label{RepoID: 3, Name: "invalid Color", Color: "#12345G"})) for _, label := range labels { - db.AssertNotExistsBean(t, label) + unittest.AssertNotExistsBean(t, label) } assert.NoError(t, NewLabels(labels...)) for _, label := range labels { - db.AssertExistsAndLoadBean(t, label, db.Cond("id = ?", label.ID)) + unittest.AssertExistsAndLoadBean(t, label, unittest.Cond("id = ?", label.ID)) } - CheckConsistencyFor(t, &Label{}, &Repository{}) + unittest.CheckConsistencyFor(t, &Label{}, &Repository{}) } func TestGetLabelByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label, err := GetLabelByID(1) assert.NoError(t, err) assert.EqualValues(t, 1, label.ID) - _, err = GetLabelByID(db.NonexistentID) + _, err = GetLabelByID(unittest.NonexistentID) assert.True(t, IsErrLabelNotExist(err)) } func TestGetLabelInRepoByName(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label, err := GetLabelInRepoByName(1, "label1") assert.NoError(t, err) assert.EqualValues(t, 1, label.ID) @@ -69,12 +70,12 @@ func TestGetLabelInRepoByName(t *testing.T) { _, err = GetLabelInRepoByName(1, "") assert.True(t, IsErrRepoLabelNotExist(err)) - _, err = GetLabelInRepoByName(db.NonexistentID, "nonexistent") + _, err = GetLabelInRepoByName(unittest.NonexistentID, "nonexistent") assert.True(t, IsErrRepoLabelNotExist(err)) } func TestGetLabelInRepoByNames(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) labelIDs, err := GetLabelIDsInRepoByNames(1, []string{"label1", "label2"}) assert.NoError(t, err) @@ -85,7 +86,7 @@ func TestGetLabelInRepoByNames(t *testing.T) { } func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // label3 doesn't exists.. See labels.yml labelIDs, err := GetLabelIDsInRepoByNames(1, []string{"label1", "label2", "label3"}) assert.NoError(t, err) @@ -98,7 +99,7 @@ func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) { } func TestGetLabelInRepoByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label, err := GetLabelInRepoByID(1, 1) assert.NoError(t, err) assert.EqualValues(t, 1, label.ID) @@ -106,13 +107,13 @@ func TestGetLabelInRepoByID(t *testing.T) { _, err = GetLabelInRepoByID(1, -1) assert.True(t, IsErrRepoLabelNotExist(err)) - _, err = GetLabelInRepoByID(db.NonexistentID, db.NonexistentID) + _, err = GetLabelInRepoByID(unittest.NonexistentID, unittest.NonexistentID) assert.True(t, IsErrRepoLabelNotExist(err)) } func TestGetLabelsInRepoByIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - labels, err := GetLabelsInRepoByIDs(1, []int64{1, 2, db.NonexistentID}) + assert.NoError(t, unittest.PrepareTestDatabase()) + labels, err := GetLabelsInRepoByIDs(1, []int64{1, 2, unittest.NonexistentID}) assert.NoError(t, err) if assert.Len(t, labels, 2) { assert.EqualValues(t, 1, labels[0].ID) @@ -121,7 +122,7 @@ func TestGetLabelsInRepoByIDs(t *testing.T) { } func TestGetLabelsByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) { labels, err := GetLabelsByRepoID(repoID, sortType, db.ListOptions{}) assert.NoError(t, err) @@ -139,7 +140,7 @@ func TestGetLabelsByRepoID(t *testing.T) { // Org versions func TestGetLabelInOrgByName(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label, err := GetLabelInOrgByName(3, "orglabel3") assert.NoError(t, err) assert.EqualValues(t, 3, label.ID) @@ -154,12 +155,12 @@ func TestGetLabelInOrgByName(t *testing.T) { _, err = GetLabelInOrgByName(-1, "orglabel3") assert.True(t, IsErrOrgLabelNotExist(err)) - _, err = GetLabelInOrgByName(db.NonexistentID, "nonexistent") + _, err = GetLabelInOrgByName(unittest.NonexistentID, "nonexistent") assert.True(t, IsErrOrgLabelNotExist(err)) } func TestGetLabelInOrgByNames(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) labelIDs, err := GetLabelIDsInOrgByNames(3, []string{"orglabel3", "orglabel4"}) assert.NoError(t, err) @@ -170,7 +171,7 @@ func TestGetLabelInOrgByNames(t *testing.T) { } func TestGetLabelInOrgByNamesDiscardsNonExistentLabels(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // orglabel99 doesn't exists.. See labels.yml labelIDs, err := GetLabelIDsInOrgByNames(3, []string{"orglabel3", "orglabel4", "orglabel99"}) assert.NoError(t, err) @@ -183,7 +184,7 @@ func TestGetLabelInOrgByNamesDiscardsNonExistentLabels(t *testing.T) { } func TestGetLabelInOrgByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label, err := GetLabelInOrgByID(3, 3) assert.NoError(t, err) assert.EqualValues(t, 3, label.ID) @@ -197,13 +198,13 @@ func TestGetLabelInOrgByID(t *testing.T) { _, err = GetLabelInOrgByID(-1, 3) assert.True(t, IsErrOrgLabelNotExist(err)) - _, err = GetLabelInOrgByID(db.NonexistentID, db.NonexistentID) + _, err = GetLabelInOrgByID(unittest.NonexistentID, unittest.NonexistentID) assert.True(t, IsErrOrgLabelNotExist(err)) } func TestGetLabelsInOrgByIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - labels, err := GetLabelsInOrgByIDs(3, []int64{3, 4, db.NonexistentID}) + assert.NoError(t, unittest.PrepareTestDatabase()) + labels, err := GetLabelsInOrgByIDs(3, []int64{3, 4, unittest.NonexistentID}) assert.NoError(t, err) if assert.Len(t, labels, 2) { assert.EqualValues(t, 3, labels[0].ID) @@ -212,7 +213,7 @@ func TestGetLabelsInOrgByIDs(t *testing.T) { } func TestGetLabelsByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) { labels, err := GetLabelsByOrgID(orgID, sortType, db.ListOptions{}) assert.NoError(t, err) @@ -237,21 +238,21 @@ func TestGetLabelsByOrgID(t *testing.T) { // func TestGetLabelsByIssueID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) labels, err := GetLabelsByIssueID(1) assert.NoError(t, err) if assert.Len(t, labels, 1) { assert.EqualValues(t, 1, labels[0].ID) } - labels, err = GetLabelsByIssueID(db.NonexistentID) + labels, err = GetLabelsByIssueID(unittest.NonexistentID) assert.NoError(t, err) assert.Len(t, labels, 0) } func TestUpdateLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - label := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) + assert.NoError(t, unittest.PrepareTestDatabase()) + label := unittest.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) // make sure update wont overwrite it update := &Label{ ID: label.ID, @@ -262,99 +263,99 @@ func TestUpdateLabel(t *testing.T) { label.Color = update.Color label.Name = update.Name assert.NoError(t, UpdateLabel(update)) - newLabel := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) + newLabel := unittest.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) assert.EqualValues(t, label.ID, newLabel.ID) assert.EqualValues(t, label.Color, newLabel.Color) assert.EqualValues(t, label.Name, newLabel.Name) assert.EqualValues(t, label.Description, newLabel.Description) - CheckConsistencyFor(t, &Label{}, &Repository{}) + unittest.CheckConsistencyFor(t, &Label{}, &Repository{}) } func TestDeleteLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - label := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) + assert.NoError(t, unittest.PrepareTestDatabase()) + label := unittest.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) assert.NoError(t, DeleteLabel(label.RepoID, label.ID)) - db.AssertNotExistsBean(t, &Label{ID: label.ID, RepoID: label.RepoID}) + unittest.AssertNotExistsBean(t, &Label{ID: label.ID, RepoID: label.RepoID}) assert.NoError(t, DeleteLabel(label.RepoID, label.ID)) - db.AssertNotExistsBean(t, &Label{ID: label.ID}) + unittest.AssertNotExistsBean(t, &Label{ID: label.ID}) - assert.NoError(t, DeleteLabel(db.NonexistentID, db.NonexistentID)) - CheckConsistencyFor(t, &Label{}, &Repository{}) + assert.NoError(t, DeleteLabel(unittest.NonexistentID, unittest.NonexistentID)) + unittest.CheckConsistencyFor(t, &Label{}, &Repository{}) } func TestHasIssueLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, HasIssueLabel(1, 1)) assert.False(t, HasIssueLabel(1, 2)) - assert.False(t, HasIssueLabel(db.NonexistentID, db.NonexistentID)) + assert.False(t, HasIssueLabel(unittest.NonexistentID, unittest.NonexistentID)) } func TestNewIssueLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - label := db.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) - doer := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + label := unittest.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + doer := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) // add new IssueLabel prevNumIssues := label.NumIssues assert.NoError(t, NewIssueLabel(issue, label, doer)) - db.AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label.ID}) - db.AssertExistsAndLoadBean(t, &Comment{ + unittest.AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label.ID}) + unittest.AssertExistsAndLoadBean(t, &Comment{ Type: CommentTypeLabel, PosterID: doer.ID, IssueID: issue.ID, LabelID: label.ID, Content: "1", }) - label = db.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) + label = unittest.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) assert.EqualValues(t, prevNumIssues+1, label.NumIssues) // re-add existing IssueLabel assert.NoError(t, NewIssueLabel(issue, label, doer)) - CheckConsistencyFor(t, &Issue{}, &Label{}) + unittest.CheckConsistencyFor(t, &Issue{}, &Label{}) } func TestNewIssueLabels(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - label1 := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) - label2 := db.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 5}).(*Issue) - doer := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + label1 := unittest.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) + label2 := unittest.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 5}).(*Issue) + doer := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) assert.NoError(t, NewIssueLabels(issue, []*Label{label1, label2}, doer)) - db.AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label1.ID}) - db.AssertExistsAndLoadBean(t, &Comment{ + unittest.AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label1.ID}) + unittest.AssertExistsAndLoadBean(t, &Comment{ Type: CommentTypeLabel, PosterID: doer.ID, IssueID: issue.ID, LabelID: label1.ID, Content: "1", }) - db.AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label1.ID}) - label1 = db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) + unittest.AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label1.ID}) + label1 = unittest.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) assert.EqualValues(t, 3, label1.NumIssues) assert.EqualValues(t, 1, label1.NumClosedIssues) - label2 = db.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) + label2 = unittest.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) assert.EqualValues(t, 1, label2.NumIssues) assert.EqualValues(t, 1, label2.NumClosedIssues) // corner case: test empty slice assert.NoError(t, NewIssueLabels(issue, []*Label{}, doer)) - CheckConsistencyFor(t, &Issue{}, &Label{}) + unittest.CheckConsistencyFor(t, &Issue{}, &Label{}) } func TestDeleteIssueLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(labelID, issueID, doerID int64) { - label := db.AssertExistsAndLoadBean(t, &Label{ID: labelID}).(*Label) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: issueID}).(*Issue) - doer := db.AssertExistsAndLoadBean(t, &User{ID: doerID}).(*User) + label := unittest.AssertExistsAndLoadBean(t, &Label{ID: labelID}).(*Label) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: issueID}).(*Issue) + doer := unittest.AssertExistsAndLoadBean(t, &User{ID: doerID}).(*User) expectedNumIssues := label.NumIssues expectedNumClosedIssues := label.NumClosedIssues - if db.BeanExists(t, &IssueLabel{IssueID: issueID, LabelID: labelID}) { + if unittest.BeanExists(t, &IssueLabel{IssueID: issueID, LabelID: labelID}) { expectedNumIssues-- if issue.IsClosed { expectedNumClosedIssues-- @@ -362,14 +363,14 @@ func TestDeleteIssueLabel(t *testing.T) { } assert.NoError(t, DeleteIssueLabel(issue, label, doer)) - db.AssertNotExistsBean(t, &IssueLabel{IssueID: issueID, LabelID: labelID}) - db.AssertExistsAndLoadBean(t, &Comment{ + unittest.AssertNotExistsBean(t, &IssueLabel{IssueID: issueID, LabelID: labelID}) + unittest.AssertExistsAndLoadBean(t, &Comment{ Type: CommentTypeLabel, PosterID: doerID, IssueID: issueID, LabelID: labelID, }, `content=""`) - label = db.AssertExistsAndLoadBean(t, &Label{ID: labelID}).(*Label) + label = unittest.AssertExistsAndLoadBean(t, &Label{ID: labelID}).(*Label) assert.EqualValues(t, expectedNumIssues, label.NumIssues) assert.EqualValues(t, expectedNumClosedIssues, label.NumClosedIssues) } @@ -377,5 +378,5 @@ func TestDeleteIssueLabel(t *testing.T) { testSuccess(2, 5, 2) testSuccess(1, 1, 2) // delete non-existent IssueLabel - CheckConsistencyFor(t, &Issue{}, &Label{}) + unittest.CheckConsistencyFor(t, &Issue{}, &Label{}) } diff --git a/models/issue_list_test.go b/models/issue_list_test.go index dadca3844c88..2916a7302f2a 100644 --- a/models/issue_list_test.go +++ b/models/issue_list_test.go @@ -7,19 +7,19 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestIssueList_LoadRepositories(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issueList := IssueList{ - db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue), - db.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue), - db.AssertExistsAndLoadBean(t, &Issue{ID: 4}).(*Issue), + unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue), + unittest.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue), + unittest.AssertExistsAndLoadBean(t, &Issue{ID: 4}).(*Issue), } repos, err := issueList.LoadRepositories() @@ -31,11 +31,11 @@ func TestIssueList_LoadRepositories(t *testing.T) { } func TestIssueList_LoadAttributes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) setting.Service.EnableTimetracking = true issueList := IssueList{ - db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue), - db.AssertExistsAndLoadBean(t, &Issue{ID: 4}).(*Issue), + unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue), + unittest.AssertExistsAndLoadBean(t, &Issue{ID: 4}).(*Issue), } assert.NoError(t, issueList.LoadAttributes()) @@ -43,7 +43,7 @@ func TestIssueList_LoadAttributes(t *testing.T) { assert.EqualValues(t, issue.RepoID, issue.Repo.ID) for _, label := range issue.Labels { assert.EqualValues(t, issue.RepoID, label.RepoID) - db.AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label.ID}) + unittest.AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issue.ID, LabelID: label.ID}) } if issue.PosterID > 0 { assert.EqualValues(t, issue.PosterID, issue.Poster.ID) diff --git a/models/issue_milestone_test.go b/models/issue_milestone_test.go index 099fe47c7c1c..2956e40f0658 100644 --- a/models/issue_milestone_test.go +++ b/models/issue_milestone_test.go @@ -9,6 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/timeutil" @@ -23,7 +24,7 @@ func TestMilestone_State(t *testing.T) { } func TestNewMilestone(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) milestone := &Milestone{ RepoID: 1, Name: "milestoneName", @@ -31,26 +32,26 @@ func TestNewMilestone(t *testing.T) { } assert.NoError(t, NewMilestone(milestone)) - db.AssertExistsAndLoadBean(t, milestone) - CheckConsistencyFor(t, &Repository{ID: milestone.RepoID}, &Milestone{}) + unittest.AssertExistsAndLoadBean(t, milestone) + unittest.CheckConsistencyFor(t, &Repository{ID: milestone.RepoID}, &Milestone{}) } func TestGetMilestoneByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) milestone, err := GetMilestoneByRepoID(1, 1) assert.NoError(t, err) assert.EqualValues(t, 1, milestone.ID) assert.EqualValues(t, 1, milestone.RepoID) - _, err = GetMilestoneByRepoID(db.NonexistentID, db.NonexistentID) + _, err = GetMilestoneByRepoID(unittest.NonexistentID, unittest.NonexistentID) assert.True(t, IsErrMilestoneNotExist(err)) } func TestGetMilestonesByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64, state api.StateType) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) milestones, _, err := GetMilestones(GetMilestonesOption{ RepoID: repo.ID, State: state, @@ -89,7 +90,7 @@ func TestGetMilestonesByRepoID(t *testing.T) { test(3, api.StateAll) milestones, _, err := GetMilestones(GetMilestonesOption{ - RepoID: db.NonexistentID, + RepoID: unittest.NonexistentID, State: api.StateOpen, }) assert.NoError(t, err) @@ -97,8 +98,8 @@ func TestGetMilestonesByRepoID(t *testing.T) { } func TestGetMilestones(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) test := func(sortType string, sortCond func(*Milestone) int) { for _, page := range []int{0, 1} { milestones, _, err := GetMilestones(GetMilestonesOption{ @@ -158,21 +159,21 @@ func TestGetMilestones(t *testing.T) { } func TestUpdateMilestone(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - milestone := db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) + milestone := unittest.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) milestone.Name = " newMilestoneName " milestone.Content = "newMilestoneContent" assert.NoError(t, UpdateMilestone(milestone, milestone.IsClosed)) - milestone = db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) + milestone = unittest.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) assert.EqualValues(t, "newMilestoneName", milestone.Name) - CheckConsistencyFor(t, &Milestone{}) + unittest.CheckConsistencyFor(t, &Milestone{}) } func TestCountRepoMilestones(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), repoID) assert.NoError(t, err) assert.EqualValues(t, repo.NumMilestones, count) @@ -181,15 +182,15 @@ func TestCountRepoMilestones(t *testing.T) { test(2) test(3) - count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), db.NonexistentID) + count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), unittest.NonexistentID) assert.NoError(t, err) assert.EqualValues(t, 0, count) } func TestCountRepoClosedMilestones(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) count, err := CountRepoClosedMilestones(repoID) assert.NoError(t, err) assert.EqualValues(t, repo.NumClosedMilestones, count) @@ -198,27 +199,27 @@ func TestCountRepoClosedMilestones(t *testing.T) { test(2) test(3) - count, err := CountRepoClosedMilestones(db.NonexistentID) + count, err := CountRepoClosedMilestones(unittest.NonexistentID) assert.NoError(t, err) assert.EqualValues(t, 0, count) } func TestChangeMilestoneStatus(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - milestone := db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) + assert.NoError(t, unittest.PrepareTestDatabase()) + milestone := unittest.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) assert.NoError(t, ChangeMilestoneStatus(milestone, true)) - db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}, "is_closed=1") - CheckConsistencyFor(t, &Repository{ID: milestone.RepoID}, &Milestone{}) + unittest.AssertExistsAndLoadBean(t, &Milestone{ID: 1}, "is_closed=1") + unittest.CheckConsistencyFor(t, &Repository{ID: milestone.RepoID}, &Milestone{}) assert.NoError(t, ChangeMilestoneStatus(milestone, false)) - db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}, "is_closed=0") - CheckConsistencyFor(t, &Repository{ID: milestone.RepoID}, &Milestone{}) + unittest.AssertExistsAndLoadBean(t, &Milestone{ID: 1}, "is_closed=0") + unittest.CheckConsistencyFor(t, &Repository{ID: milestone.RepoID}, &Milestone{}) } func TestUpdateMilestoneCounters(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{MilestoneID: 1}, + assert.NoError(t, unittest.PrepareTestDatabase()) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{MilestoneID: 1}, "is_closed=0").(*Issue) issue.IsClosed = true @@ -226,48 +227,48 @@ func TestUpdateMilestoneCounters(t *testing.T) { _, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) assert.NoError(t, err) assert.NoError(t, updateMilestoneCounters(db.GetEngine(db.DefaultContext), issue.MilestoneID)) - CheckConsistencyFor(t, &Milestone{}) + unittest.CheckConsistencyFor(t, &Milestone{}) issue.IsClosed = false issue.ClosedUnix = 0 _, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) assert.NoError(t, err) assert.NoError(t, updateMilestoneCounters(db.GetEngine(db.DefaultContext), issue.MilestoneID)) - CheckConsistencyFor(t, &Milestone{}) + unittest.CheckConsistencyFor(t, &Milestone{}) } func TestChangeMilestoneAssign(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{RepoID: 1}).(*Issue) - doer := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{RepoID: 1}).(*Issue) + doer := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) assert.NotNil(t, issue) assert.NotNil(t, doer) oldMilestoneID := issue.MilestoneID issue.MilestoneID = 2 assert.NoError(t, ChangeMilestoneAssign(issue, doer, oldMilestoneID)) - db.AssertExistsAndLoadBean(t, &Comment{ + unittest.AssertExistsAndLoadBean(t, &Comment{ IssueID: issue.ID, Type: CommentTypeMilestone, MilestoneID: issue.MilestoneID, OldMilestoneID: oldMilestoneID, }) - CheckConsistencyFor(t, &Milestone{}, &Issue{}) + unittest.CheckConsistencyFor(t, &Milestone{}, &Issue{}) } func TestDeleteMilestoneByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, DeleteMilestoneByRepoID(1, 1)) - db.AssertNotExistsBean(t, &Milestone{ID: 1}) - CheckConsistencyFor(t, &Repository{ID: 1}) + unittest.AssertNotExistsBean(t, &Milestone{ID: 1}) + unittest.CheckConsistencyFor(t, &Repository{ID: 1}) - assert.NoError(t, DeleteMilestoneByRepoID(db.NonexistentID, db.NonexistentID)) + assert.NoError(t, DeleteMilestoneByRepoID(unittest.NonexistentID, unittest.NonexistentID)) } func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) miles := MilestoneList{ - db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone), + unittest.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone), } assert.NoError(t, miles.LoadTotalTrackedTimes()) @@ -276,9 +277,9 @@ func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) { } func TestCountMilestonesByRepoIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) milestonesCount := func(repoID int64) (int, int) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) return repo.NumOpenMilestones, repo.NumClosedMilestones } repo1OpenCount, repo1ClosedCount := milestonesCount(1) @@ -296,9 +297,9 @@ func TestCountMilestonesByRepoIDs(t *testing.T) { } func TestGetMilestonesByRepoIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) test := func(sortType string, sortCond func(*Milestone) int) { for _, page := range []int{0, 1} { openMilestones, err := GetMilestonesByRepoIDs([]int64{repo1.ID, repo2.ID}, page, false, sortType) @@ -341,8 +342,8 @@ func TestGetMilestonesByRepoIDs(t *testing.T) { } func TestLoadTotalTrackedTime(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - milestone := db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) + assert.NoError(t, unittest.PrepareTestDatabase()) + milestone := unittest.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) assert.NoError(t, milestone.LoadTotalTrackedTime()) @@ -350,10 +351,10 @@ func TestLoadTotalTrackedTime(t *testing.T) { } func TestGetMilestonesStats(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) stats, err := GetMilestonesStatsByRepoCond(builder.And(builder.Eq{"repo_id": repoID})) assert.NoError(t, err) assert.EqualValues(t, repo.NumMilestones-repo.NumClosedMilestones, stats.OpenCount) @@ -363,13 +364,13 @@ func TestGetMilestonesStats(t *testing.T) { test(2) test(3) - stats, err := GetMilestonesStatsByRepoCond(builder.And(builder.Eq{"repo_id": db.NonexistentID})) + stats, err := GetMilestonesStatsByRepoCond(builder.And(builder.Eq{"repo_id": unittest.NonexistentID})) assert.NoError(t, err) assert.EqualValues(t, 0, stats.OpenCount) assert.EqualValues(t, 0, stats.ClosedCount) - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) milestoneStats, err := GetMilestonesStatsByRepoCond(builder.In("repo_id", []int64{repo1.ID, repo2.ID})) assert.NoError(t, err) diff --git a/models/issue_reaction_test.go b/models/issue_reaction_test.go index dd15b816c73f..c01e4add7acf 100644 --- a/models/issue_reaction_test.go +++ b/models/issue_reaction_test.go @@ -7,6 +7,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" @@ -25,23 +26,23 @@ func addReaction(t *testing.T, doer *User, issue *Issue, comment *Comment, conte } func TestIssueAddReaction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) - issue1 := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + issue1 := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) addReaction(t, user1, issue1, nil, "heart") - db.AssertExistsAndLoadBean(t, &Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1.ID}) + unittest.AssertExistsAndLoadBean(t, &Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1.ID}) } func TestIssueAddDuplicateReaction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) - issue1 := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + issue1 := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) addReaction(t, user1, issue1, nil, "heart") @@ -53,37 +54,37 @@ func TestIssueAddDuplicateReaction(t *testing.T) { assert.Error(t, err) assert.Equal(t, ErrReactionAlreadyExist{Reaction: "heart"}, err) - existingR := db.AssertExistsAndLoadBean(t, &Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1.ID}).(*Reaction) + existingR := unittest.AssertExistsAndLoadBean(t, &Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1.ID}).(*Reaction) assert.Equal(t, existingR.ID, reaction.ID) } func TestIssueDeleteReaction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) - issue1 := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + issue1 := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) addReaction(t, user1, issue1, nil, "heart") err := DeleteIssueReaction(user1, issue1, "heart") assert.NoError(t, err) - db.AssertNotExistsBean(t, &Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1.ID}) + unittest.AssertNotExistsBean(t, &Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1.ID}) } func TestIssueReactionCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) setting.UI.ReactionMaxUserNum = 2 - user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) - user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - user3 := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) - user4 := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) + user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user3 := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + user4 := unittest.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) ghost := NewGhostUser() - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) addReaction(t, user1, issue, nil, "heart") addReaction(t, user2, issue, nil, "heart") @@ -111,31 +112,31 @@ func TestIssueReactionCount(t *testing.T) { } func TestIssueCommentAddReaction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) - issue1 := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + issue1 := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) - comment1 := db.AssertExistsAndLoadBean(t, &Comment{ID: 1}).(*Comment) + comment1 := unittest.AssertExistsAndLoadBean(t, &Comment{ID: 1}).(*Comment) addReaction(t, user1, issue1, comment1, "heart") - db.AssertExistsAndLoadBean(t, &Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1.ID, CommentID: comment1.ID}) + unittest.AssertExistsAndLoadBean(t, &Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1.ID, CommentID: comment1.ID}) } func TestIssueCommentDeleteReaction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) - user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - user3 := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) - user4 := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) + user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user3 := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + user4 := unittest.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) - issue1 := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: issue1.RepoID}).(*Repository) + issue1 := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: issue1.RepoID}).(*Repository) - comment1 := db.AssertExistsAndLoadBean(t, &Comment{ID: 1}).(*Comment) + comment1 := unittest.AssertExistsAndLoadBean(t, &Comment{ID: 1}).(*Comment) addReaction(t, user1, issue1, comment1, "heart") addReaction(t, user2, issue1, comment1, "heart") @@ -152,16 +153,16 @@ func TestIssueCommentDeleteReaction(t *testing.T) { } func TestIssueCommentReactionCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user1 := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) - issue1 := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + issue1 := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) - comment1 := db.AssertExistsAndLoadBean(t, &Comment{ID: 1}).(*Comment) + comment1 := unittest.AssertExistsAndLoadBean(t, &Comment{ID: 1}).(*Comment) addReaction(t, user1, issue1, comment1, "heart") assert.NoError(t, DeleteCommentReaction(user1, issue1, comment1, "heart")) - db.AssertNotExistsBean(t, &Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1.ID, CommentID: comment1.ID}) + unittest.AssertNotExistsBean(t, &Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1.ID, CommentID: comment1.ID}) } diff --git a/models/issue_stopwatch_test.go b/models/issue_stopwatch_test.go index 11306efcf53f..ceb579d09557 100644 --- a/models/issue_stopwatch_test.go +++ b/models/issue_stopwatch_test.go @@ -7,14 +7,14 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" ) func TestCancelStopwatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1, err := GetUserByID(1) assert.NoError(t, err) @@ -26,22 +26,22 @@ func TestCancelStopwatch(t *testing.T) { err = CancelStopwatch(user1, issue1) assert.NoError(t, err) - db.AssertNotExistsBean(t, &Stopwatch{UserID: user1.ID, IssueID: issue1.ID}) + unittest.AssertNotExistsBean(t, &Stopwatch{UserID: user1.ID, IssueID: issue1.ID}) - _ = db.AssertExistsAndLoadBean(t, &Comment{Type: CommentTypeCancelTracking, PosterID: user1.ID, IssueID: issue1.ID}) + _ = unittest.AssertExistsAndLoadBean(t, &Comment{Type: CommentTypeCancelTracking, PosterID: user1.ID, IssueID: issue1.ID}) assert.Nil(t, CancelStopwatch(user1, issue2)) } func TestStopwatchExists(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, StopwatchExists(1, 1)) assert.False(t, StopwatchExists(1, 2)) } func TestHasUserStopwatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) exists, sw, err := HasUserStopwatch(1) assert.NoError(t, err) @@ -54,7 +54,7 @@ func TestHasUserStopwatch(t *testing.T) { } func TestCreateOrStopIssueStopwatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user2, err := GetUserByID(2) assert.NoError(t, err) @@ -67,10 +67,10 @@ func TestCreateOrStopIssueStopwatch(t *testing.T) { assert.NoError(t, err) assert.NoError(t, CreateOrStopIssueStopwatch(user3, issue1)) - sw := db.AssertExistsAndLoadBean(t, &Stopwatch{UserID: 3, IssueID: 1}).(*Stopwatch) + sw := unittest.AssertExistsAndLoadBean(t, &Stopwatch{UserID: 3, IssueID: 1}).(*Stopwatch) assert.LessOrEqual(t, sw.CreatedUnix, timeutil.TimeStampNow()) assert.NoError(t, CreateOrStopIssueStopwatch(user2, issue2)) - db.AssertNotExistsBean(t, &Stopwatch{UserID: 2, IssueID: 2}) - db.AssertExistsAndLoadBean(t, &TrackedTime{UserID: 2, IssueID: 2}) + unittest.AssertNotExistsBean(t, &Stopwatch{UserID: 2, IssueID: 2}) + unittest.AssertExistsAndLoadBean(t, &TrackedTime{UserID: 2, IssueID: 2}) } diff --git a/models/issue_test.go b/models/issue_test.go index 9df91aeb9944..f53febb1b30c 100644 --- a/models/issue_test.go +++ b/models/issue_test.go @@ -12,25 +12,26 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestIssue_ReplaceLabels(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(issueID int64, labelIDs []int64) { - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: issueID}).(*Issue) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository) - doer := db.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: issueID}).(*Issue) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository) + doer := unittest.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) labels := make([]*Label, len(labelIDs)) for i, labelID := range labelIDs { - labels[i] = db.AssertExistsAndLoadBean(t, &Label{ID: labelID, RepoID: repo.ID}).(*Label) + labels[i] = unittest.AssertExistsAndLoadBean(t, &Label{ID: labelID, RepoID: repo.ID}).(*Label) } assert.NoError(t, issue.ReplaceLabels(labels, doer)) - db.AssertCount(t, &IssueLabel{IssueID: issueID}, len(labelIDs)) + unittest.AssertCount(t, &IssueLabel{IssueID: issueID}, len(labelIDs)) for _, labelID := range labelIDs { - db.AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issueID, LabelID: labelID}) + unittest.AssertExistsAndLoadBean(t, &IssueLabel{IssueID: issueID, LabelID: labelID}) } } @@ -40,7 +41,7 @@ func TestIssue_ReplaceLabels(t *testing.T) { } func Test_GetIssueIDsByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) ids, err := GetIssueIDsByRepoID(1) assert.NoError(t, err) @@ -48,8 +49,8 @@ func Test_GetIssueIDsByRepoID(t *testing.T) { } func TestIssueAPIURL(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + assert.NoError(t, unittest.PrepareTestDatabase()) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) err := issue.LoadAttributes() assert.NoError(t, err) @@ -57,7 +58,7 @@ func TestIssueAPIURL(t *testing.T) { } func TestGetIssuesByIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(expectedIssueIDs, nonExistentIssueIDs []int64) { issues, err := GetIssuesByIDs(append(expectedIssueIDs, nonExistentIssueIDs...)) assert.NoError(t, err) @@ -68,11 +69,11 @@ func TestGetIssuesByIDs(t *testing.T) { assert.Equal(t, expectedIssueIDs, actualIssueIDs) } testSuccess([]int64{1, 2, 3}, []int64{}) - testSuccess([]int64{1, 2, 3}, []int64{db.NonexistentID}) + testSuccess([]int64{1, 2, 3}, []int64{unittest.NonexistentID}) } func TestGetParticipantIDsByIssue(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) checkParticipants := func(issueID int64, userIDs []int) { issue, err := GetIssueByID(issueID) @@ -106,17 +107,17 @@ func TestIssue_ClearLabels(t *testing.T) { {3, 2}, // pull-request, has no labels } for _, test := range tests { - assert.NoError(t, db.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: test.issueID}).(*Issue) - doer := db.AssertExistsAndLoadBean(t, &User{ID: test.doerID}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: test.issueID}).(*Issue) + doer := unittest.AssertExistsAndLoadBean(t, &User{ID: test.doerID}).(*User) assert.NoError(t, issue.ClearLabels(doer)) - db.AssertNotExistsBean(t, &IssueLabel{IssueID: test.issueID}) + unittest.AssertNotExistsBean(t, &IssueLabel{IssueID: test.issueID}) } } func TestUpdateIssueCols(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{}).(*Issue) + assert.NoError(t, unittest.PrepareTestDatabase()) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{}).(*Issue) const newTitle = "New Title for unit test" issue.Title = newTitle @@ -128,14 +129,14 @@ func TestUpdateIssueCols(t *testing.T) { assert.NoError(t, updateIssueCols(db.GetEngine(db.DefaultContext), issue, "name")) then := time.Now().Unix() - updatedIssue := db.AssertExistsAndLoadBean(t, &Issue{ID: issue.ID}).(*Issue) + updatedIssue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: issue.ID}).(*Issue) assert.EqualValues(t, newTitle, updatedIssue.Title) assert.EqualValues(t, prevContent, updatedIssue.Content) - db.AssertInt64InRange(t, now, then, int64(updatedIssue.UpdatedUnix)) + unittest.AssertInt64InRange(t, now, then, int64(updatedIssue.UpdatedUnix)) } func TestIssues(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) for _, test := range []struct { Opts IssuesOptions ExpectedIssueIDs []int64 @@ -190,7 +191,7 @@ func TestIssues(t *testing.T) { } func TestGetUserIssueStats(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) for _, test := range []struct { Opts UserIssueStatsOptions ExpectedIssueStats IssueStats @@ -287,7 +288,7 @@ func TestGetUserIssueStats(t *testing.T) { } func TestIssue_loadTotalTimes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) ms, err := GetIssueByID(2) assert.NoError(t, err) assert.NoError(t, ms.loadTotalTimes(db.GetEngine(db.DefaultContext))) @@ -295,7 +296,7 @@ func TestIssue_loadTotalTimes(t *testing.T) { } func TestIssue_SearchIssueIDsByKeyword(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) total, ids, err := SearchIssueIDsByKeyword("issue2", []int64{1}, 10, 0) assert.NoError(t, err) assert.EqualValues(t, 1, total) @@ -319,8 +320,8 @@ func TestIssue_SearchIssueIDsByKeyword(t *testing.T) { } func TestGetRepoIDsForIssuesOptions(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) for _, test := range []struct { Opts IssuesOptions ExpectedRepoIDs []int64 @@ -351,8 +352,8 @@ func TestGetRepoIDsForIssuesOptions(t *testing.T) { func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *Issue { var newIssue Issue t.Run(title, func(t *testing.T) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) issue := Issue{ RepoID: repo.ID, @@ -377,7 +378,7 @@ func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *Is } func TestIssue_InsertIssue(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // there are 5 issues and max index is 5 on repository 1, so this one should 6 issue := testInsertIssue(t, "my issue1", "special issue's comments?", 6) @@ -391,13 +392,13 @@ func TestIssue_InsertIssue(t *testing.T) { } func TestIssue_ResolveMentions(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(owner, repo, doer string, mentions []string, expected []int64) { - o := db.AssertExistsAndLoadBean(t, &User{LowerName: owner}).(*User) - r := db.AssertExistsAndLoadBean(t, &Repository{OwnerID: o.ID, LowerName: repo}).(*Repository) + o := unittest.AssertExistsAndLoadBean(t, &User{LowerName: owner}).(*User) + r := unittest.AssertExistsAndLoadBean(t, &Repository{OwnerID: o.ID, LowerName: repo}).(*Repository) issue := &Issue{RepoID: r.ID} - d := db.AssertExistsAndLoadBean(t, &User{LowerName: doer}).(*User) + d := unittest.AssertExistsAndLoadBean(t, &User{LowerName: doer}).(*User) resolved, err := issue.ResolveMentionsByVisibility(db.DefaultContext, d, mentions) assert.NoError(t, err) ids := make([]int64, len(resolved)) @@ -423,7 +424,7 @@ func TestIssue_ResolveMentions(t *testing.T) { } func TestResourceIndex(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) var wg sync.WaitGroup for i := 0; i < 100; i++ { @@ -437,7 +438,7 @@ func TestResourceIndex(t *testing.T) { } func TestCorrectIssueStats(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Because the condition is to have chunked database look-ups, // We have to more issues than `maxQueryParameters`, we will insert. diff --git a/models/issue_tracked_time_test.go b/models/issue_tracked_time_test.go index 7643360727fc..9bc966452178 100644 --- a/models/issue_tracked_time_test.go +++ b/models/issue_tracked_time_test.go @@ -8,12 +8,12 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestAddTime(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user3, err := GetUserByID(3) assert.NoError(t, err) @@ -28,15 +28,15 @@ func TestAddTime(t *testing.T) { assert.Equal(t, int64(1), trackedTime.IssueID) assert.Equal(t, int64(3661), trackedTime.Time) - tt := db.AssertExistsAndLoadBean(t, &TrackedTime{UserID: 3, IssueID: 1}).(*TrackedTime) + tt := unittest.AssertExistsAndLoadBean(t, &TrackedTime{UserID: 3, IssueID: 1}).(*TrackedTime) assert.Equal(t, int64(3661), tt.Time) - comment := db.AssertExistsAndLoadBean(t, &Comment{Type: CommentTypeAddTimeManual, PosterID: 3, IssueID: 1}).(*Comment) + comment := unittest.AssertExistsAndLoadBean(t, &Comment{Type: CommentTypeAddTimeManual, PosterID: 3, IssueID: 1}).(*Comment) assert.Equal(t, comment.Content, "1h 1min 1s") } func TestGetTrackedTimes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // by Issue times, err := GetTrackedTimes(&FindTrackedTimesOptions{IssueID: 1}) @@ -77,7 +77,7 @@ func TestGetTrackedTimes(t *testing.T) { } func TestTotalTimes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) total, err := TotalTimes(&FindTrackedTimesOptions{IssueID: 1}) assert.NoError(t, err) diff --git a/models/issue_user_test.go b/models/issue_user_test.go index d4e504719fc6..1be276370375 100644 --- a/models/issue_user_test.go +++ b/models/issue_user_test.go @@ -8,13 +8,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func Test_newIssueUsers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) newIssue := &Issue{ RepoID: repo.ID, PosterID: 4, @@ -24,35 +25,35 @@ func Test_newIssueUsers(t *testing.T) { } // artificially insert new issue - db.AssertSuccessfulInsert(t, newIssue) + unittest.AssertSuccessfulInsert(t, newIssue) assert.NoError(t, newIssueUsers(db.GetEngine(db.DefaultContext), repo, newIssue)) // issue_user table should now have entries for new issue - db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID}) - db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: repo.OwnerID}) + unittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID}) + unittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: newIssue.ID, UID: repo.OwnerID}) } func TestUpdateIssueUserByRead(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + assert.NoError(t, unittest.PrepareTestDatabase()) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) assert.NoError(t, UpdateIssueUserByRead(4, issue.ID)) - db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1") + unittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1") assert.NoError(t, UpdateIssueUserByRead(4, issue.ID)) - db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1") + unittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1") - assert.NoError(t, UpdateIssueUserByRead(db.NonexistentID, db.NonexistentID)) + assert.NoError(t, UpdateIssueUserByRead(unittest.NonexistentID, unittest.NonexistentID)) } func TestUpdateIssueUsersByMentions(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + assert.NoError(t, unittest.PrepareTestDatabase()) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) uids := []int64{2, 5} assert.NoError(t, UpdateIssueUsersByMentions(db.DefaultContext, issue.ID, uids)) for _, uid := range uids { - db.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1") + unittest.AssertExistsAndLoadBean(t, &IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1") } } diff --git a/models/issue_watch_test.go b/models/issue_watch_test.go index 139ed41cb608..18d49bfce55b 100644 --- a/models/issue_watch_test.go +++ b/models/issue_watch_test.go @@ -8,23 +8,24 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestCreateOrUpdateIssueWatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, CreateOrUpdateIssueWatch(3, 1, true)) - iw := db.AssertExistsAndLoadBean(t, &IssueWatch{UserID: 3, IssueID: 1}).(*IssueWatch) + iw := unittest.AssertExistsAndLoadBean(t, &IssueWatch{UserID: 3, IssueID: 1}).(*IssueWatch) assert.True(t, iw.IsWatching) assert.NoError(t, CreateOrUpdateIssueWatch(1, 1, false)) - iw = db.AssertExistsAndLoadBean(t, &IssueWatch{UserID: 1, IssueID: 1}).(*IssueWatch) + iw = unittest.AssertExistsAndLoadBean(t, &IssueWatch{UserID: 1, IssueID: 1}).(*IssueWatch) assert.False(t, iw.IsWatching) } func TestGetIssueWatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) _, exists, err := GetIssueWatch(9, 1) assert.True(t, exists) @@ -41,7 +42,7 @@ func TestGetIssueWatch(t *testing.T) { } func TestGetIssueWatchers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) iws, err := GetIssueWatchers(1, db.ListOptions{}) assert.NoError(t, err) diff --git a/models/issue_xref_test.go b/models/issue_xref_test.go index bf498e471073..551c29dcba47 100644 --- a/models/issue_xref_test.go +++ b/models/issue_xref_test.go @@ -9,13 +9,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/references" "github.com/stretchr/testify/assert" ) func TestXRef_AddCrossReferences(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Issue #1 to test against itarget := testCreateIssue(t, 1, 2, "title1", "content1", false) @@ -23,7 +24,7 @@ func TestXRef_AddCrossReferences(t *testing.T) { // PR to close issue #1 content := fmt.Sprintf("content2, closes #%d", itarget.Index) pr := testCreateIssue(t, 1, 2, "title2", content, true) - ref := db.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: pr.ID, RefCommentID: 0}).(*Comment) + ref := unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: pr.ID, RefCommentID: 0}).(*Comment) assert.Equal(t, CommentTypePullRef, ref.Type) assert.Equal(t, pr.RepoID, ref.RefRepoID) assert.True(t, ref.RefIsPull) @@ -32,7 +33,7 @@ func TestXRef_AddCrossReferences(t *testing.T) { // Comment on PR to reopen issue #1 content = fmt.Sprintf("content2, reopens #%d", itarget.Index) c := testCreateComment(t, 1, 2, pr.ID, content) - ref = db.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: pr.ID, RefCommentID: c.ID}).(*Comment) + ref = unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: pr.ID, RefCommentID: c.ID}).(*Comment) assert.Equal(t, CommentTypeCommentRef, ref.Type) assert.Equal(t, pr.RepoID, ref.RefRepoID) assert.True(t, ref.RefIsPull) @@ -41,7 +42,7 @@ func TestXRef_AddCrossReferences(t *testing.T) { // Issue mentioning issue #1 content = fmt.Sprintf("content3, mentions #%d", itarget.Index) i := testCreateIssue(t, 1, 2, "title3", content, false) - ref = db.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment) + ref = unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment) assert.Equal(t, CommentTypeIssueRef, ref.Type) assert.Equal(t, pr.RepoID, ref.RefRepoID) assert.False(t, ref.RefIsPull) @@ -53,7 +54,7 @@ func TestXRef_AddCrossReferences(t *testing.T) { // Cross-reference to issue #4 by admin content = fmt.Sprintf("content5, mentions user3/repo3#%d", itarget.Index) i = testCreateIssue(t, 2, 1, "title5", content, false) - ref = db.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment) + ref = unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment) assert.Equal(t, CommentTypeIssueRef, ref.Type) assert.Equal(t, i.RepoID, ref.RefRepoID) assert.False(t, ref.RefIsPull) @@ -62,11 +63,11 @@ func TestXRef_AddCrossReferences(t *testing.T) { // Cross-reference to issue #4 with no permission content = fmt.Sprintf("content6, mentions user3/repo3#%d", itarget.Index) i = testCreateIssue(t, 4, 5, "title6", content, false) - db.AssertNotExistsBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}) + unittest.AssertNotExistsBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}) } func TestXRef_NeuterCrossReferences(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Issue #1 to test against itarget := testCreateIssue(t, 1, 2, "title1", "content1", false) @@ -74,23 +75,23 @@ func TestXRef_NeuterCrossReferences(t *testing.T) { // Issue mentioning issue #1 title := fmt.Sprintf("title2, mentions #%d", itarget.Index) i := testCreateIssue(t, 1, 2, title, "content2", false) - ref := db.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment) + ref := unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment) assert.Equal(t, CommentTypeIssueRef, ref.Type) assert.Equal(t, references.XRefActionNone, ref.RefAction) - d := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + d := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) i.Title = "title2, no mentions" assert.NoError(t, i.ChangeTitle(d, title)) - ref = db.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment) + ref = unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}).(*Comment) assert.Equal(t, CommentTypeIssueRef, ref.Type) assert.Equal(t, references.XRefActionNeutered, ref.RefAction) } func TestXRef_ResolveCrossReferences(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - d := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + d := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) i1 := testCreateIssue(t, 1, 2, "title1", "content1", false) i2 := testCreateIssue(t, 1, 2, "title2", "content2", false) @@ -99,21 +100,21 @@ func TestXRef_ResolveCrossReferences(t *testing.T) { assert.NoError(t, err) pr := testCreatePR(t, 1, 2, "titlepr", fmt.Sprintf("closes #%d", i1.Index)) - rp := db.AssertExistsAndLoadBean(t, &Comment{IssueID: i1.ID, RefIssueID: pr.Issue.ID, RefCommentID: 0}).(*Comment) + rp := unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: i1.ID, RefIssueID: pr.Issue.ID, RefCommentID: 0}).(*Comment) c1 := testCreateComment(t, 1, 2, pr.Issue.ID, fmt.Sprintf("closes #%d", i2.Index)) - r1 := db.AssertExistsAndLoadBean(t, &Comment{IssueID: i2.ID, RefIssueID: pr.Issue.ID, RefCommentID: c1.ID}).(*Comment) + r1 := unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: i2.ID, RefIssueID: pr.Issue.ID, RefCommentID: c1.ID}).(*Comment) // Must be ignored c2 := testCreateComment(t, 1, 2, pr.Issue.ID, fmt.Sprintf("mentions #%d", i2.Index)) - db.AssertExistsAndLoadBean(t, &Comment{IssueID: i2.ID, RefIssueID: pr.Issue.ID, RefCommentID: c2.ID}) + unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: i2.ID, RefIssueID: pr.Issue.ID, RefCommentID: c2.ID}) // Must be superseded by c4/r4 c3 := testCreateComment(t, 1, 2, pr.Issue.ID, fmt.Sprintf("reopens #%d", i3.Index)) - db.AssertExistsAndLoadBean(t, &Comment{IssueID: i3.ID, RefIssueID: pr.Issue.ID, RefCommentID: c3.ID}) + unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: i3.ID, RefIssueID: pr.Issue.ID, RefCommentID: c3.ID}) c4 := testCreateComment(t, 1, 2, pr.Issue.ID, fmt.Sprintf("closes #%d", i3.Index)) - r4 := db.AssertExistsAndLoadBean(t, &Comment{IssueID: i3.ID, RefIssueID: pr.Issue.ID, RefCommentID: c4.ID}).(*Comment) + r4 := unittest.AssertExistsAndLoadBean(t, &Comment{IssueID: i3.ID, RefIssueID: pr.Issue.ID, RefCommentID: c4.ID}).(*Comment) refs, err := pr.ResolveCrossReferences() assert.NoError(t, err) @@ -124,8 +125,8 @@ func TestXRef_ResolveCrossReferences(t *testing.T) { } func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispull bool) *Issue { - r := db.AssertExistsAndLoadBean(t, &Repository{ID: repo}).(*Repository) - d := db.AssertExistsAndLoadBean(t, &User{ID: doer}).(*User) + r := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repo}).(*Repository) + d := unittest.AssertExistsAndLoadBean(t, &User{ID: doer}).(*User) idx, err := db.GetNextResourceIndex("issue_index", r.ID) assert.NoError(t, err) @@ -156,8 +157,8 @@ func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispu } func testCreatePR(t *testing.T, repo, doer int64, title, content string) *PullRequest { - r := db.AssertExistsAndLoadBean(t, &Repository{ID: repo}).(*Repository) - d := db.AssertExistsAndLoadBean(t, &User{ID: doer}).(*User) + r := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repo}).(*Repository) + d := unittest.AssertExistsAndLoadBean(t, &User{ID: doer}).(*User) i := &Issue{RepoID: r.ID, PosterID: d.ID, Poster: d, Title: title, Content: content, IsPull: true} pr := &PullRequest{HeadRepoID: repo, BaseRepoID: repo, HeadBranch: "head", BaseBranch: "base", Status: PullRequestStatusMergeable} assert.NoError(t, NewPullRequest(r, i, nil, nil, pr)) @@ -166,8 +167,8 @@ func testCreatePR(t *testing.T, repo, doer int64, title, content string) *PullRe } func testCreateComment(t *testing.T, repo, doer, issue int64, content string) *Comment { - d := db.AssertExistsAndLoadBean(t, &User{ID: doer}).(*User) - i := db.AssertExistsAndLoadBean(t, &Issue{ID: issue}).(*Issue) + d := unittest.AssertExistsAndLoadBean(t, &User{ID: doer}).(*User) + i := unittest.AssertExistsAndLoadBean(t, &Issue{ID: issue}).(*Issue) c := &Comment{Type: CommentTypeComment, PosterID: doer, Poster: d, IssueID: issue, Issue: i, Content: content} sess := db.NewSession(db.DefaultContext) diff --git a/models/issues/content_history_test.go b/models/issues/content_history_test.go index dadeb484b13f..f040a7dc57f1 100644 --- a/models/issues/content_history_test.go +++ b/models/issues/content_history_test.go @@ -8,13 +8,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" ) func TestContentHistory(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) dbCtx := db.DefaultContext dbEngine := db.GetEngine(dbCtx) diff --git a/models/issues/main_test.go b/models/issues/main_test.go index 61a15c53b787..af71f038d63e 100644 --- a/models/issues/main_test.go +++ b/models/issues/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", ".."), "") + unittest.MainTest(m, filepath.Join("..", ".."), "") } diff --git a/models/login/main_test.go b/models/login/main_test.go index 141952a5941d..0666eeaad018 100644 --- a/models/login/main_test.go +++ b/models/login/main_test.go @@ -8,11 +8,11 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", ".."), + unittest.MainTest(m, filepath.Join("..", ".."), "login_source.yml", "oauth2_application.yml", "oauth2_authorization_code.yml", diff --git a/models/login/oauth2_application_test.go b/models/login/oauth2_application_test.go index cb064cef1b4d..47e6a27ce968 100644 --- a/models/login/oauth2_application_test.go +++ b/models/login/oauth2_application_test.go @@ -7,7 +7,7 @@ package login import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) @@ -15,17 +15,17 @@ import ( //////////////////// Application func TestOAuth2Application_GenerateClientSecret(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - app := db.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) + assert.NoError(t, unittest.PrepareTestDatabase()) + app := unittest.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) secret, err := app.GenerateClientSecret() assert.NoError(t, err) assert.True(t, len(secret) > 0) - db.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1, ClientSecret: app.ClientSecret}) + unittest.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1, ClientSecret: app.ClientSecret}) } func BenchmarkOAuth2Application_GenerateClientSecret(b *testing.B) { - assert.NoError(b, db.PrepareTestDatabase()) - app := db.AssertExistsAndLoadBean(b, &OAuth2Application{ID: 1}).(*OAuth2Application) + assert.NoError(b, unittest.PrepareTestDatabase()) + app := unittest.AssertExistsAndLoadBean(b, &OAuth2Application{ID: 1}).(*OAuth2Application) for i := 0; i < b.N; i++ { _, _ = app.GenerateClientSecret() } @@ -42,8 +42,8 @@ func TestOAuth2Application_ContainsRedirectURI(t *testing.T) { } func TestOAuth2Application_ValidateClientSecret(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - app := db.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) + assert.NoError(t, unittest.PrepareTestDatabase()) + app := unittest.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) secret, err := app.GenerateClientSecret() assert.NoError(t, err) assert.True(t, app.ValidateClientSecret([]byte(secret))) @@ -51,7 +51,7 @@ func TestOAuth2Application_ValidateClientSecret(t *testing.T) { } func TestGetOAuth2ApplicationByClientID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) app, err := GetOAuth2ApplicationByClientID("da7da3ba-9a13-4167-856f-3899de0b0138") assert.NoError(t, err) assert.Equal(t, "da7da3ba-9a13-4167-856f-3899de0b0138", app.ClientID) @@ -62,12 +62,12 @@ func TestGetOAuth2ApplicationByClientID(t *testing.T) { } func TestCreateOAuth2Application(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) app, err := CreateOAuth2Application(CreateOAuth2ApplicationOptions{Name: "newapp", UserID: 1}) assert.NoError(t, err) assert.Equal(t, "newapp", app.Name) assert.Len(t, app.ClientID, 36) - db.AssertExistsAndLoadBean(t, &OAuth2Application{Name: "newapp"}) + unittest.AssertExistsAndLoadBean(t, &OAuth2Application{Name: "newapp"}) } func TestOAuth2Application_TableName(t *testing.T) { @@ -75,8 +75,8 @@ func TestOAuth2Application_TableName(t *testing.T) { } func TestOAuth2Application_GetGrantByUserID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - app := db.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) + assert.NoError(t, unittest.PrepareTestDatabase()) + app := unittest.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) grant, err := app.GetGrantByUserID(1) assert.NoError(t, err) assert.Equal(t, int64(1), grant.UserID) @@ -87,8 +87,8 @@ func TestOAuth2Application_GetGrantByUserID(t *testing.T) { } func TestOAuth2Application_CreateGrant(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - app := db.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) + assert.NoError(t, unittest.PrepareTestDatabase()) + app := unittest.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) grant, err := app.CreateGrant(2, "") assert.NoError(t, err) assert.NotNil(t, grant) @@ -100,7 +100,7 @@ func TestOAuth2Application_CreateGrant(t *testing.T) { //////////////////// Grant func TestGetOAuth2GrantByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) grant, err := GetOAuth2GrantByID(1) assert.NoError(t, err) assert.Equal(t, int64(1), grant.ID) @@ -111,16 +111,16 @@ func TestGetOAuth2GrantByID(t *testing.T) { } func TestOAuth2Grant_IncreaseCounter(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - grant := db.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Counter: 1}).(*OAuth2Grant) + assert.NoError(t, unittest.PrepareTestDatabase()) + grant := unittest.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Counter: 1}).(*OAuth2Grant) assert.NoError(t, grant.IncreaseCounter()) assert.Equal(t, int64(2), grant.Counter) - db.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Counter: 2}) + unittest.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Counter: 2}) } func TestOAuth2Grant_ScopeContains(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - grant := db.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Scope: "openid profile"}).(*OAuth2Grant) + assert.NoError(t, unittest.PrepareTestDatabase()) + grant := unittest.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Scope: "openid profile"}).(*OAuth2Grant) assert.True(t, grant.ScopeContains("openid")) assert.True(t, grant.ScopeContains("profile")) assert.False(t, grant.ScopeContains("profil")) @@ -128,8 +128,8 @@ func TestOAuth2Grant_ScopeContains(t *testing.T) { } func TestOAuth2Grant_GenerateNewAuthorizationCode(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - grant := db.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1}).(*OAuth2Grant) + assert.NoError(t, unittest.PrepareTestDatabase()) + grant := unittest.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1}).(*OAuth2Grant) code, err := grant.GenerateNewAuthorizationCode("https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256") assert.NoError(t, err) assert.NotNil(t, code) @@ -141,7 +141,7 @@ func TestOAuth2Grant_TableName(t *testing.T) { } func TestGetOAuth2GrantsByUserID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) result, err := GetOAuth2GrantsByUserID(1) assert.NoError(t, err) assert.Len(t, result, 1) @@ -154,15 +154,15 @@ func TestGetOAuth2GrantsByUserID(t *testing.T) { } func TestRevokeOAuth2Grant(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, RevokeOAuth2Grant(1, 1)) - db.AssertNotExistsBean(t, &OAuth2Grant{ID: 1, UserID: 1}) + unittest.AssertNotExistsBean(t, &OAuth2Grant{ID: 1, UserID: 1}) } //////////////////// Authorization Code func TestGetOAuth2AuthorizationByCode(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) code, err := GetOAuth2AuthorizationByCode("authcode") assert.NoError(t, err) assert.NotNil(t, code) @@ -222,10 +222,10 @@ func TestOAuth2AuthorizationCode_GenerateRedirectURI(t *testing.T) { } func TestOAuth2AuthorizationCode_Invalidate(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - code := db.AssertExistsAndLoadBean(t, &OAuth2AuthorizationCode{Code: "authcode"}).(*OAuth2AuthorizationCode) + assert.NoError(t, unittest.PrepareTestDatabase()) + code := unittest.AssertExistsAndLoadBean(t, &OAuth2AuthorizationCode{Code: "authcode"}).(*OAuth2AuthorizationCode) assert.NoError(t, code.Invalidate()) - db.AssertNotExistsBean(t, &OAuth2AuthorizationCode{Code: "authcode"}) + unittest.AssertNotExistsBean(t, &OAuth2AuthorizationCode{Code: "authcode"}) } func TestOAuth2AuthorizationCode_TableName(t *testing.T) { diff --git a/models/login/source_test.go b/models/login/source_test.go index d98609037cd5..e7ef7c70488c 100644 --- a/models/login/source_test.go +++ b/models/login/source_test.go @@ -9,6 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" @@ -34,7 +35,7 @@ func (source *TestSource) ToDB() ([]byte, error) { } func TestDumpLoginSource(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) loginSourceSchema, err := db.TableInfo(new(Source)) assert.NoError(t, err) diff --git a/models/login/u2f_test.go b/models/login/u2f_test.go index 8f5cea61508a..06a37f8132e9 100644 --- a/models/login/u2f_test.go +++ b/models/login/u2f_test.go @@ -8,14 +8,14 @@ import ( "encoding/hex" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" "github.com/tstranex/u2f" ) func TestGetU2FRegistrationByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) res, err := GetU2FRegistrationByID(1) assert.NoError(t, err) @@ -27,7 +27,7 @@ func TestGetU2FRegistrationByID(t *testing.T) { } func TestGetU2FRegistrationsByUID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) res, err := GetU2FRegistrationsByUID(32) @@ -41,38 +41,38 @@ func TestU2FRegistration_TableName(t *testing.T) { } func TestU2FRegistration_UpdateCounter(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - reg := db.AssertExistsAndLoadBean(t, &U2FRegistration{ID: 1}).(*U2FRegistration) + assert.NoError(t, unittest.PrepareTestDatabase()) + reg := unittest.AssertExistsAndLoadBean(t, &U2FRegistration{ID: 1}).(*U2FRegistration) reg.Counter = 1 assert.NoError(t, reg.UpdateCounter()) - db.AssertExistsIf(t, true, &U2FRegistration{ID: 1, Counter: 1}) + unittest.AssertExistsIf(t, true, &U2FRegistration{ID: 1, Counter: 1}) } func TestU2FRegistration_UpdateLargeCounter(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - reg := db.AssertExistsAndLoadBean(t, &U2FRegistration{ID: 1}).(*U2FRegistration) + assert.NoError(t, unittest.PrepareTestDatabase()) + reg := unittest.AssertExistsAndLoadBean(t, &U2FRegistration{ID: 1}).(*U2FRegistration) reg.Counter = 0xffffffff assert.NoError(t, reg.UpdateCounter()) - db.AssertExistsIf(t, true, &U2FRegistration{ID: 1, Counter: 0xffffffff}) + unittest.AssertExistsIf(t, true, &U2FRegistration{ID: 1, Counter: 0xffffffff}) } func TestCreateRegistration(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) res, err := CreateRegistration(1, "U2F Created Key", &u2f.Registration{Raw: []byte("Test")}) assert.NoError(t, err) assert.Equal(t, "U2F Created Key", res.Name) assert.Equal(t, []byte("Test"), res.Raw) - db.AssertExistsIf(t, true, &U2FRegistration{Name: "U2F Created Key", UserID: 1}) + unittest.AssertExistsIf(t, true, &U2FRegistration{Name: "U2F Created Key", UserID: 1}) } func TestDeleteRegistration(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - reg := db.AssertExistsAndLoadBean(t, &U2FRegistration{ID: 1}).(*U2FRegistration) + assert.NoError(t, unittest.PrepareTestDatabase()) + reg := unittest.AssertExistsAndLoadBean(t, &U2FRegistration{ID: 1}).(*U2FRegistration) assert.NoError(t, DeleteRegistration(reg)) - db.AssertNotExistsBean(t, &U2FRegistration{ID: 1}) + unittest.AssertNotExistsBean(t, &U2FRegistration{ID: 1}) } const validU2FRegistrationResponseHex = "0504b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9402a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c253082013c3081e4a003020102020a47901280001155957352300a06082a8648ce3d0403023017311530130603550403130c476e756262792050696c6f74301e170d3132303831343138323933325a170d3133303831343138323933325a3031312f302d0603550403132650696c6f74476e756262792d302e342e312d34373930313238303030313135353935373335323059301306072a8648ce3d020106082a8648ce3d030107034200048d617e65c9508e64bcc5673ac82a6799da3c1446682c258c463fffdf58dfd2fa3e6c378b53d795c4a4dffb4199edd7862f23abaf0203b4b8911ba0569994e101300a06082a8648ce3d0403020347003044022060cdb6061e9c22262d1aac1d96d8c70829b2366531dda268832cb836bcd30dfa0220631b1459f09e6330055722c8d89b7f48883b9089b88d60d1d9795902b30410df304502201471899bcc3987e62e8202c9b39c33c19033f7340352dba80fcab017db9230e402210082677d673d891933ade6f617e5dbde2e247e70423fd5ad7804a6d3d3961ef871" diff --git a/models/main_test.go b/models/main_test.go index ad9276330f1a..5c99a2b2f7b0 100644 --- a/models/main_test.go +++ b/models/main_test.go @@ -7,17 +7,25 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) // TestFixturesAreConsistent assert that test fixtures are consistent func TestFixturesAreConsistent(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - CheckConsistencyForAll(t) + assert.NoError(t, unittest.PrepareTestDatabase()) + unittest.CheckConsistencyFor(t, + &User{}, + &Repository{}, + &Issue{}, + &PullRequest{}, + &Milestone{}, + &Label{}, + &Team{}, + &Action{}) } func TestMain(m *testing.M) { - db.MainTest(m, "..") + unittest.MainTest(m, "..") } diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 2686dfb3cff9..c0d8f111d376 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -7,6 +7,7 @@ package migrations import ( "context" + "errors" "fmt" "os" "reflect" @@ -791,8 +792,14 @@ func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin } tableSQL := string(res[0]["sql"]) + // Get the string offset for column definitions: `CREATE TABLE ( column-definitions... )` + columnDefinitionsIndex := strings.Index(tableSQL, "(") + if columnDefinitionsIndex < 0 { + return errors.New("couldn't find column definitions") + } + // Separate out the column definitions - tableSQL = tableSQL[strings.Index(tableSQL, "("):] + tableSQL = tableSQL[columnDefinitionsIndex:] // Remove the required columnNames for _, name := range columnNames { diff --git a/models/migrations/migrations_test.go b/models/migrations/migrations_test.go index 46c8c66a24fa..f46070cf8e58 100644 --- a/models/migrations/migrations_test.go +++ b/models/migrations/migrations_test.go @@ -15,6 +15,7 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/setting" @@ -241,14 +242,14 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.En if _, err := os.Stat(fixturesDir); err == nil { t.Logf("initializing fixtures from: %s", fixturesDir) - if err := db.InitFixtures( - db.FixturesOptions{ + if err := unittest.InitFixtures( + unittest.FixturesOptions{ Dir: fixturesDir, }, x); err != nil { t.Errorf("error whilst initializing fixtures from %s: %v", fixturesDir, err) return x, deferFn } - if err := db.LoadFixtures(x); err != nil { + if err := unittest.LoadFixtures(x); err != nil { t.Errorf("error whilst loading fixtures from %s: %v", fixturesDir, err) return x, deferFn } diff --git a/models/notification_test.go b/models/notification_test.go index 588882bed3ff..db2164a2f59b 100644 --- a/models/notification_test.go +++ b/models/notification_test.go @@ -7,28 +7,28 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestCreateOrUpdateIssueNotifications(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) + assert.NoError(t, unittest.PrepareTestDatabase()) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) assert.NoError(t, CreateOrUpdateIssueNotifications(issue.ID, 0, 2, 0)) // User 9 is inactive, thus notifications for user 1 and 4 are created - notf := db.AssertExistsAndLoadBean(t, &Notification{UserID: 1, IssueID: issue.ID}).(*Notification) + notf := unittest.AssertExistsAndLoadBean(t, &Notification{UserID: 1, IssueID: issue.ID}).(*Notification) assert.Equal(t, NotificationStatusUnread, notf.Status) - CheckConsistencyFor(t, &Issue{ID: issue.ID}) + unittest.CheckConsistencyFor(t, &Issue{ID: issue.ID}) - notf = db.AssertExistsAndLoadBean(t, &Notification{UserID: 4, IssueID: issue.ID}).(*Notification) + notf = unittest.AssertExistsAndLoadBean(t, &Notification{UserID: 4, IssueID: issue.ID}).(*Notification) assert.Equal(t, NotificationStatusUnread, notf.Status) } func TestNotificationsForUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) statuses := []NotificationStatus{NotificationStatusRead, NotificationStatusUnread} notfs, err := NotificationsForUser(user, statuses, 1, 10) assert.NoError(t, err) @@ -43,8 +43,8 @@ func TestNotificationsForUser(t *testing.T) { } func TestNotification_GetRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - notf := db.AssertExistsAndLoadBean(t, &Notification{RepoID: 1}).(*Notification) + assert.NoError(t, unittest.PrepareTestDatabase()) + notf := unittest.AssertExistsAndLoadBean(t, &Notification{RepoID: 1}).(*Notification) repo, err := notf.GetRepo() assert.NoError(t, err) assert.Equal(t, repo, notf.Repository) @@ -52,8 +52,8 @@ func TestNotification_GetRepo(t *testing.T) { } func TestNotification_GetIssue(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - notf := db.AssertExistsAndLoadBean(t, &Notification{RepoID: 1}).(*Notification) + assert.NoError(t, unittest.PrepareTestDatabase()) + notf := unittest.AssertExistsAndLoadBean(t, &Notification{RepoID: 1}).(*Notification) issue, err := notf.GetIssue() assert.NoError(t, err) assert.Equal(t, issue, notf.Issue) @@ -61,8 +61,8 @@ func TestNotification_GetIssue(t *testing.T) { } func TestGetNotificationCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) cnt, err := GetNotificationCount(user, NotificationStatusRead) assert.NoError(t, err) assert.EqualValues(t, 0, cnt) @@ -73,35 +73,35 @@ func TestGetNotificationCount(t *testing.T) { } func TestSetNotificationStatus(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - notf := db.AssertExistsAndLoadBean(t, + assert.NoError(t, unittest.PrepareTestDatabase()) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + notf := unittest.AssertExistsAndLoadBean(t, &Notification{UserID: user.ID, Status: NotificationStatusRead}).(*Notification) _, err := SetNotificationStatus(notf.ID, user, NotificationStatusPinned) assert.NoError(t, err) - db.AssertExistsAndLoadBean(t, + unittest.AssertExistsAndLoadBean(t, &Notification{ID: notf.ID, Status: NotificationStatusPinned}) _, err = SetNotificationStatus(1, user, NotificationStatusRead) assert.Error(t, err) - _, err = SetNotificationStatus(db.NonexistentID, user, NotificationStatusRead) + _, err = SetNotificationStatus(unittest.NonexistentID, user, NotificationStatusRead) assert.Error(t, err) } func TestUpdateNotificationStatuses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - notfUnread := db.AssertExistsAndLoadBean(t, + assert.NoError(t, unittest.PrepareTestDatabase()) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + notfUnread := unittest.AssertExistsAndLoadBean(t, &Notification{UserID: user.ID, Status: NotificationStatusUnread}).(*Notification) - notfRead := db.AssertExistsAndLoadBean(t, + notfRead := unittest.AssertExistsAndLoadBean(t, &Notification{UserID: user.ID, Status: NotificationStatusRead}).(*Notification) - notfPinned := db.AssertExistsAndLoadBean(t, + notfPinned := unittest.AssertExistsAndLoadBean(t, &Notification{UserID: user.ID, Status: NotificationStatusPinned}).(*Notification) assert.NoError(t, UpdateNotificationStatuses(user, NotificationStatusUnread, NotificationStatusRead)) - db.AssertExistsAndLoadBean(t, + unittest.AssertExistsAndLoadBean(t, &Notification{ID: notfUnread.ID, Status: NotificationStatusRead}) - db.AssertExistsAndLoadBean(t, + unittest.AssertExistsAndLoadBean(t, &Notification{ID: notfRead.ID, Status: NotificationStatusRead}) - db.AssertExistsAndLoadBean(t, + unittest.AssertExistsAndLoadBean(t, &Notification{ID: notfPinned.ID, Status: NotificationStatusPinned}) } diff --git a/models/org_team_test.go b/models/org_team_test.go index f1c8f8887932..9277ac4f5edf 100644 --- a/models/org_team_test.go +++ b/models/org_team_test.go @@ -8,43 +8,43 @@ import ( "strings" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestTeam_IsOwnerTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - team := db.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) assert.True(t, team.IsOwnerTeam()) - team = db.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) + team = unittest.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) assert.False(t, team.IsOwnerTeam()) } func TestTeam_IsMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - team := db.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) assert.True(t, team.IsMember(2)) assert.False(t, team.IsMember(4)) - assert.False(t, team.IsMember(db.NonexistentID)) + assert.False(t, team.IsMember(unittest.NonexistentID)) - team = db.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) + team = unittest.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) assert.True(t, team.IsMember(2)) assert.True(t, team.IsMember(4)) - assert.False(t, team.IsMember(db.NonexistentID)) + assert.False(t, team.IsMember(unittest.NonexistentID)) } func TestTeam_GetRepositories(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID int64) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) assert.NoError(t, team.GetRepositories(&SearchTeamOptions{})) assert.Len(t, team.Repos, team.NumRepos) for _, repo := range team.Repos { - db.AssertExistsAndLoadBean(t, &TeamRepo{TeamID: teamID, RepoID: repo.ID}) + unittest.AssertExistsAndLoadBean(t, &TeamRepo{TeamID: teamID, RepoID: repo.ID}) } } test(1) @@ -52,14 +52,14 @@ func TestTeam_GetRepositories(t *testing.T) { } func TestTeam_GetMembers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID int64) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) assert.NoError(t, team.GetMembers(&SearchMembersOptions{})) assert.Len(t, team.Members, team.NumMembers) for _, member := range team.Members { - db.AssertExistsAndLoadBean(t, &TeamUser{UID: member.ID, TeamID: teamID}) + unittest.AssertExistsAndLoadBean(t, &TeamUser{UID: member.ID, TeamID: teamID}) } } test(1) @@ -67,13 +67,13 @@ func TestTeam_GetMembers(t *testing.T) { } func TestTeam_AddMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, userID int64) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) assert.NoError(t, team.AddMember(userID)) - db.AssertExistsAndLoadBean(t, &TeamUser{UID: userID, TeamID: teamID}) - CheckConsistencyFor(t, &Team{ID: teamID}, &User{ID: team.OrgID}) + unittest.AssertExistsAndLoadBean(t, &TeamUser{UID: userID, TeamID: teamID}) + unittest.CheckConsistencyFor(t, &Team{ID: teamID}, &User{ID: team.OrgID}) } test(1, 2) test(1, 4) @@ -81,71 +81,71 @@ func TestTeam_AddMember(t *testing.T) { } func TestTeam_RemoveMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, userID int64) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) assert.NoError(t, team.RemoveMember(userID)) - db.AssertNotExistsBean(t, &TeamUser{UID: userID, TeamID: teamID}) - CheckConsistencyFor(t, &Team{ID: teamID}) + unittest.AssertNotExistsBean(t, &TeamUser{UID: userID, TeamID: teamID}) + unittest.CheckConsistencyFor(t, &Team{ID: teamID}) } testSuccess(1, 4) testSuccess(2, 2) testSuccess(3, 2) - testSuccess(3, db.NonexistentID) + testSuccess(3, unittest.NonexistentID) - team := db.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) err := team.RemoveMember(2) assert.True(t, IsErrLastOrgOwner(err)) } func TestTeam_HasRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, repoID int64, expected bool) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) assert.Equal(t, expected, team.HasRepository(repoID)) } test(1, 1, false) test(1, 3, true) test(1, 5, true) - test(1, db.NonexistentID, false) + test(1, unittest.NonexistentID, false) test(2, 3, true) test(2, 5, false) } func TestTeam_AddRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, repoID int64) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) assert.NoError(t, team.AddRepository(repo)) - db.AssertExistsAndLoadBean(t, &TeamRepo{TeamID: teamID, RepoID: repoID}) - CheckConsistencyFor(t, &Team{ID: teamID}, &Repository{ID: repoID}) + unittest.AssertExistsAndLoadBean(t, &TeamRepo{TeamID: teamID, RepoID: repoID}) + unittest.CheckConsistencyFor(t, &Team{ID: teamID}, &Repository{ID: repoID}) } testSuccess(2, 3) testSuccess(2, 5) - team := db.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.Error(t, team.AddRepository(repo)) - CheckConsistencyFor(t, &Team{ID: 1}, &Repository{ID: 1}) + unittest.CheckConsistencyFor(t, &Team{ID: 1}, &Repository{ID: 1}) } func TestTeam_RemoveRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, repoID int64) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) assert.NoError(t, team.RemoveRepository(repoID)) - db.AssertNotExistsBean(t, &TeamRepo{TeamID: teamID, RepoID: repoID}) - CheckConsistencyFor(t, &Team{ID: teamID}, &Repository{ID: repoID}) + unittest.AssertNotExistsBean(t, &TeamRepo{TeamID: teamID, RepoID: repoID}) + unittest.CheckConsistencyFor(t, &Team{ID: teamID}, &Repository{ID: repoID}) } testSuccess(2, 3) testSuccess(2, 5) - testSuccess(1, db.NonexistentID) + testSuccess(1, unittest.NonexistentID) } func TestIsUsableTeamName(t *testing.T) { @@ -154,17 +154,17 @@ func TestIsUsableTeamName(t *testing.T) { } func TestNewTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) const teamName = "newTeamName" team := &Team{Name: teamName, OrgID: 3} assert.NoError(t, NewTeam(team)) - db.AssertExistsAndLoadBean(t, &Team{Name: teamName}) - CheckConsistencyFor(t, &Team{}, &User{ID: team.OrgID}) + unittest.AssertExistsAndLoadBean(t, &Team{Name: teamName}) + unittest.CheckConsistencyFor(t, &Team{}, &User{ID: team.OrgID}) } func TestGetTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID int64, name string) { team, err := GetTeam(orgID, name) @@ -177,12 +177,12 @@ func TestGetTeam(t *testing.T) { _, err := GetTeam(3, "nonexistent") assert.Error(t, err) - _, err = GetTeam(db.NonexistentID, "Owners") + _, err = GetTeam(unittest.NonexistentID, "Owners") assert.Error(t, err) } func TestGetTeamByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID int64) { team, err := GetTeamByID(teamID) @@ -194,63 +194,63 @@ func TestGetTeamByID(t *testing.T) { testSuccess(3) testSuccess(4) - _, err := GetTeamByID(db.NonexistentID) + _, err := GetTeamByID(unittest.NonexistentID) assert.Error(t, err) } func TestUpdateTeam(t *testing.T) { // successful update - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - team := db.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) team.LowerName = "newname" team.Name = "newName" team.Description = strings.Repeat("A long description!", 100) team.Authorize = AccessModeAdmin assert.NoError(t, UpdateTeam(team, true, false)) - team = db.AssertExistsAndLoadBean(t, &Team{Name: "newName"}).(*Team) + team = unittest.AssertExistsAndLoadBean(t, &Team{Name: "newName"}).(*Team) assert.True(t, strings.HasPrefix(team.Description, "A long description!")) - access := db.AssertExistsAndLoadBean(t, &Access{UserID: 4, RepoID: 3}).(*Access) + access := unittest.AssertExistsAndLoadBean(t, &Access{UserID: 4, RepoID: 3}).(*Access) assert.EqualValues(t, AccessModeAdmin, access.Mode) - CheckConsistencyFor(t, &Team{ID: team.ID}) + unittest.CheckConsistencyFor(t, &Team{ID: team.ID}) } func TestUpdateTeam2(t *testing.T) { // update to already-existing team - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - team := db.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) team.LowerName = "owners" team.Name = "Owners" team.Description = strings.Repeat("A long description!", 100) err := UpdateTeam(team, true, false) assert.True(t, IsErrTeamAlreadyExist(err)) - CheckConsistencyFor(t, &Team{ID: team.ID}) + unittest.CheckConsistencyFor(t, &Team{ID: team.ID}) } func TestDeleteTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - team := db.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) assert.NoError(t, DeleteTeam(team)) - db.AssertNotExistsBean(t, &Team{ID: team.ID}) - db.AssertNotExistsBean(t, &TeamRepo{TeamID: team.ID}) - db.AssertNotExistsBean(t, &TeamUser{TeamID: team.ID}) + unittest.AssertNotExistsBean(t, &Team{ID: team.ID}) + unittest.AssertNotExistsBean(t, &TeamRepo{TeamID: team.ID}) + unittest.AssertNotExistsBean(t, &TeamUser{TeamID: team.ID}) // check that team members don't have "leftover" access to repos - user := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) accessMode, err := AccessLevel(user, repo) assert.NoError(t, err) assert.True(t, accessMode < AccessModeWrite) } func TestIsTeamMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, teamID, userID int64, expected bool) { isMember, err := IsTeamMember(orgID, teamID, userID) assert.NoError(t, err) @@ -259,25 +259,25 @@ func TestIsTeamMember(t *testing.T) { test(3, 1, 2, true) test(3, 1, 4, false) - test(3, 1, db.NonexistentID, false) + test(3, 1, unittest.NonexistentID, false) test(3, 2, 2, true) test(3, 2, 4, true) - test(3, db.NonexistentID, db.NonexistentID, false) - test(db.NonexistentID, db.NonexistentID, db.NonexistentID, false) + test(3, unittest.NonexistentID, unittest.NonexistentID, false) + test(unittest.NonexistentID, unittest.NonexistentID, unittest.NonexistentID, false) } func TestGetTeamMembers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID int64) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) members, err := GetTeamMembers(teamID) assert.NoError(t, err) assert.Len(t, members, team.NumMembers) for _, member := range members { - db.AssertExistsAndLoadBean(t, &TeamUser{UID: member.ID, TeamID: teamID}) + unittest.AssertExistsAndLoadBean(t, &TeamUser{UID: member.ID, TeamID: teamID}) } } test(1) @@ -285,42 +285,42 @@ func TestGetTeamMembers(t *testing.T) { } func TestGetUserTeams(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(userID int64) { teams, _, err := SearchTeam(&SearchTeamOptions{UserID: userID}) assert.NoError(t, err) for _, team := range teams { - db.AssertExistsAndLoadBean(t, &TeamUser{TeamID: team.ID, UID: userID}) + unittest.AssertExistsAndLoadBean(t, &TeamUser{TeamID: team.ID, UID: userID}) } } test(2) test(5) - test(db.NonexistentID) + test(unittest.NonexistentID) } func TestGetUserOrgTeams(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64) { teams, err := GetUserOrgTeams(orgID, userID) assert.NoError(t, err) for _, team := range teams { assert.EqualValues(t, orgID, team.OrgID) - db.AssertExistsAndLoadBean(t, &TeamUser{TeamID: team.ID, UID: userID}) + unittest.AssertExistsAndLoadBean(t, &TeamUser{TeamID: team.ID, UID: userID}) } } test(3, 2) test(3, 4) - test(3, db.NonexistentID) + test(3, unittest.NonexistentID) } func TestAddTeamMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, userID int64) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) assert.NoError(t, AddTeamMember(team, userID)) - db.AssertExistsAndLoadBean(t, &TeamUser{UID: userID, TeamID: teamID}) - CheckConsistencyFor(t, &Team{ID: teamID}, &User{ID: team.OrgID}) + unittest.AssertExistsAndLoadBean(t, &TeamUser{UID: userID, TeamID: teamID}) + unittest.CheckConsistencyFor(t, &Team{ID: teamID}, &User{ID: team.OrgID}) } test(1, 2) test(1, 4) @@ -328,42 +328,42 @@ func TestAddTeamMember(t *testing.T) { } func TestRemoveTeamMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, userID int64) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) assert.NoError(t, RemoveTeamMember(team, userID)) - db.AssertNotExistsBean(t, &TeamUser{UID: userID, TeamID: teamID}) - CheckConsistencyFor(t, &Team{ID: teamID}) + unittest.AssertNotExistsBean(t, &TeamUser{UID: userID, TeamID: teamID}) + unittest.CheckConsistencyFor(t, &Team{ID: teamID}) } testSuccess(1, 4) testSuccess(2, 2) testSuccess(3, 2) - testSuccess(3, db.NonexistentID) + testSuccess(3, unittest.NonexistentID) - team := db.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) err := RemoveTeamMember(team, 2) assert.True(t, IsErrLastOrgOwner(err)) } func TestHasTeamRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, repoID int64, expected bool) { - team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) assert.Equal(t, expected, HasTeamRepo(team.OrgID, teamID, repoID)) } test(1, 1, false) test(1, 3, true) test(1, 5, true) - test(1, db.NonexistentID, false) + test(1, unittest.NonexistentID, false) test(2, 3, true) test(2, 5, false) } func TestUsersInTeamsCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamIDs, userIDs []int64, expected int64) { count, err := UsersInTeamsCount(teamIDs, userIDs) diff --git a/models/org_test.go b/models/org_test.go index 2df89b2afcac..2bc4d74fc355 100644 --- a/models/org_test.go +++ b/models/org_test.go @@ -8,6 +8,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" @@ -15,7 +16,7 @@ import ( ) func TestUser_IsOwnedBy(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) for _, testCase := range []struct { OrgID int64 UserID int64 @@ -28,7 +29,7 @@ func TestUser_IsOwnedBy(t *testing.T) { {2, 2, false}, // user2 is not an organization {2, 3, false}, } { - org := db.AssertExistsAndLoadBean(t, &User{ID: testCase.OrgID}).(*User) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: testCase.OrgID}).(*User) isOwner, err := org.IsOwnedBy(testCase.UserID) assert.NoError(t, err) assert.Equal(t, testCase.ExpectedOwner, isOwner) @@ -36,7 +37,7 @@ func TestUser_IsOwnedBy(t *testing.T) { } func TestUser_IsOrgMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) for _, testCase := range []struct { OrgID int64 UserID int64 @@ -49,7 +50,7 @@ func TestUser_IsOrgMember(t *testing.T) { {2, 2, false}, // user2 is not an organization {2, 3, false}, } { - org := db.AssertExistsAndLoadBean(t, &User{ID: testCase.OrgID}).(*User) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: testCase.OrgID}).(*User) isMember, err := org.IsOrgMember(testCase.UserID) assert.NoError(t, err) assert.Equal(t, testCase.ExpectedMember, isMember) @@ -57,8 +58,8 @@ func TestUser_IsOrgMember(t *testing.T) { } func TestUser_GetTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) team, err := org.GetTeam("team1") assert.NoError(t, err) assert.Equal(t, org.ID, team.OrgID) @@ -67,26 +68,26 @@ func TestUser_GetTeam(t *testing.T) { _, err = org.GetTeam("does not exist") assert.True(t, IsErrTeamNotExist(err)) - nonOrg := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + nonOrg := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) _, err = nonOrg.GetTeam("team") assert.True(t, IsErrTeamNotExist(err)) } func TestUser_GetOwnerTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) team, err := org.GetOwnerTeam() assert.NoError(t, err) assert.Equal(t, org.ID, team.OrgID) - nonOrg := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + nonOrg := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) _, err = nonOrg.GetOwnerTeam() assert.True(t, IsErrTeamNotExist(err)) } func TestUser_GetTeams(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) assert.NoError(t, org.LoadTeams()) if assert.Len(t, org.Teams, 4) { assert.Equal(t, int64(1), org.Teams[0].ID) @@ -97,8 +98,8 @@ func TestUser_GetTeams(t *testing.T) { } func TestUser_GetMembers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) assert.NoError(t, org.GetMembers()) if assert.Len(t, org.Members, 3) { assert.Equal(t, int64(2), org.Members[0].ID) @@ -108,69 +109,69 @@ func TestUser_GetMembers(t *testing.T) { } func TestUser_AddMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) // add a user that is not a member - db.AssertNotExistsBean(t, &OrgUser{UID: 5, OrgID: 3}) + unittest.AssertNotExistsBean(t, &OrgUser{UID: 5, OrgID: 3}) prevNumMembers := org.NumMembers assert.NoError(t, org.AddMember(5)) - db.AssertExistsAndLoadBean(t, &OrgUser{UID: 5, OrgID: 3}) - org = db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + unittest.AssertExistsAndLoadBean(t, &OrgUser{UID: 5, OrgID: 3}) + org = unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) assert.Equal(t, prevNumMembers+1, org.NumMembers) // add a user that is already a member - db.AssertExistsAndLoadBean(t, &OrgUser{UID: 4, OrgID: 3}) + unittest.AssertExistsAndLoadBean(t, &OrgUser{UID: 4, OrgID: 3}) prevNumMembers = org.NumMembers assert.NoError(t, org.AddMember(4)) - db.AssertExistsAndLoadBean(t, &OrgUser{UID: 4, OrgID: 3}) - org = db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + unittest.AssertExistsAndLoadBean(t, &OrgUser{UID: 4, OrgID: 3}) + org = unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) assert.Equal(t, prevNumMembers, org.NumMembers) - CheckConsistencyFor(t, &User{}) + unittest.CheckConsistencyFor(t, &User{}) } func TestUser_RemoveMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) // remove a user that is a member - db.AssertExistsAndLoadBean(t, &OrgUser{UID: 4, OrgID: 3}) + unittest.AssertExistsAndLoadBean(t, &OrgUser{UID: 4, OrgID: 3}) prevNumMembers := org.NumMembers assert.NoError(t, org.RemoveMember(4)) - db.AssertNotExistsBean(t, &OrgUser{UID: 4, OrgID: 3}) - org = db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + unittest.AssertNotExistsBean(t, &OrgUser{UID: 4, OrgID: 3}) + org = unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) assert.Equal(t, prevNumMembers-1, org.NumMembers) // remove a user that is not a member - db.AssertNotExistsBean(t, &OrgUser{UID: 5, OrgID: 3}) + unittest.AssertNotExistsBean(t, &OrgUser{UID: 5, OrgID: 3}) prevNumMembers = org.NumMembers assert.NoError(t, org.RemoveMember(5)) - db.AssertNotExistsBean(t, &OrgUser{UID: 5, OrgID: 3}) - org = db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + unittest.AssertNotExistsBean(t, &OrgUser{UID: 5, OrgID: 3}) + org = unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) assert.Equal(t, prevNumMembers, org.NumMembers) - CheckConsistencyFor(t, &User{}, &Team{}) + unittest.CheckConsistencyFor(t, &User{}, &Team{}) } func TestUser_RemoveOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) - repo := db.AssertExistsAndLoadBean(t, &Repository{OwnerID: org.ID}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{OwnerID: org.ID}).(*Repository) // remove a repo that does belong to org - db.AssertExistsAndLoadBean(t, &TeamRepo{RepoID: repo.ID, OrgID: org.ID}) + unittest.AssertExistsAndLoadBean(t, &TeamRepo{RepoID: repo.ID, OrgID: org.ID}) assert.NoError(t, org.RemoveOrgRepo(repo.ID)) - db.AssertNotExistsBean(t, &TeamRepo{RepoID: repo.ID, OrgID: org.ID}) - db.AssertExistsAndLoadBean(t, &Repository{ID: repo.ID}) // repo should still exist + unittest.AssertNotExistsBean(t, &TeamRepo{RepoID: repo.ID, OrgID: org.ID}) + unittest.AssertExistsAndLoadBean(t, &Repository{ID: repo.ID}) // repo should still exist // remove a repo that does not belong to org assert.NoError(t, org.RemoveOrgRepo(repo.ID)) - db.AssertNotExistsBean(t, &TeamRepo{RepoID: repo.ID, OrgID: org.ID}) + unittest.AssertNotExistsBean(t, &TeamRepo{RepoID: repo.ID, OrgID: org.ID}) - assert.NoError(t, org.RemoveOrgRepo(db.NonexistentID)) + assert.NoError(t, org.RemoveOrgRepo(unittest.NonexistentID)) - CheckConsistencyFor(t, + unittest.CheckConsistencyFor(t, &User{ID: org.ID}, &Team{OrgID: org.ID}, &Repository{ID: repo.ID}) @@ -178,68 +179,68 @@ func TestUser_RemoveOrgRepo(t *testing.T) { func TestCreateOrganization(t *testing.T) { // successful creation of org - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) const newOrgName = "neworg" org := &User{ Name: newOrgName, } - db.AssertNotExistsBean(t, &User{Name: newOrgName, Type: UserTypeOrganization}) + unittest.AssertNotExistsBean(t, &User{Name: newOrgName, Type: UserTypeOrganization}) assert.NoError(t, CreateOrganization(org, owner)) - org = db.AssertExistsAndLoadBean(t, + org = unittest.AssertExistsAndLoadBean(t, &User{Name: newOrgName, Type: UserTypeOrganization}).(*User) - ownerTeam := db.AssertExistsAndLoadBean(t, + ownerTeam := unittest.AssertExistsAndLoadBean(t, &Team{Name: ownerTeamName, OrgID: org.ID}).(*Team) - db.AssertExistsAndLoadBean(t, &TeamUser{UID: owner.ID, TeamID: ownerTeam.ID}) - CheckConsistencyFor(t, &User{}, &Team{}) + unittest.AssertExistsAndLoadBean(t, &TeamUser{UID: owner.ID, TeamID: ownerTeam.ID}) + unittest.CheckConsistencyFor(t, &User{}, &Team{}) } func TestCreateOrganization2(t *testing.T) { // unauthorized creation of org - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - owner := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) const newOrgName = "neworg" org := &User{ Name: newOrgName, } - db.AssertNotExistsBean(t, &User{Name: newOrgName, Type: UserTypeOrganization}) + unittest.AssertNotExistsBean(t, &User{Name: newOrgName, Type: UserTypeOrganization}) err := CreateOrganization(org, owner) assert.Error(t, err) assert.True(t, IsErrUserNotAllowedCreateOrg(err)) - db.AssertNotExistsBean(t, &User{Name: newOrgName, Type: UserTypeOrganization}) - CheckConsistencyFor(t, &User{}, &Team{}) + unittest.AssertNotExistsBean(t, &User{Name: newOrgName, Type: UserTypeOrganization}) + unittest.CheckConsistencyFor(t, &User{}, &Team{}) } func TestCreateOrganization3(t *testing.T) { // create org with same name as existent org - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - org := &User{Name: "user3"} // should already exist - db.AssertExistsAndLoadBean(t, &User{Name: org.Name}) // sanity check + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + org := &User{Name: "user3"} // should already exist + unittest.AssertExistsAndLoadBean(t, &User{Name: org.Name}) // sanity check err := CreateOrganization(org, owner) assert.Error(t, err) assert.True(t, IsErrUserAlreadyExist(err)) - CheckConsistencyFor(t, &User{}, &Team{}) + unittest.CheckConsistencyFor(t, &User{}, &Team{}) } func TestCreateOrganization4(t *testing.T) { // create org with unusable name - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) err := CreateOrganization(&User{Name: "assets"}, owner) assert.Error(t, err) assert.True(t, IsErrNameReserved(err)) - CheckConsistencyFor(t, &User{}, &Team{}) + unittest.CheckConsistencyFor(t, &User{}, &Team{}) } func TestGetOrgByName(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org, err := GetOrgByName("user3") assert.NoError(t, err) @@ -254,32 +255,32 @@ func TestGetOrgByName(t *testing.T) { } func TestCountOrganizations(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) expected, err := db.GetEngine(db.DefaultContext).Where("type=?", UserTypeOrganization).Count(&User{}) assert.NoError(t, err) assert.Equal(t, expected, CountOrganizations()) } func TestDeleteOrganization(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 6}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 6}).(*User) assert.NoError(t, DeleteOrganization(org)) - db.AssertNotExistsBean(t, &User{ID: 6}) - db.AssertNotExistsBean(t, &OrgUser{OrgID: 6}) - db.AssertNotExistsBean(t, &Team{OrgID: 6}) + unittest.AssertNotExistsBean(t, &User{ID: 6}) + unittest.AssertNotExistsBean(t, &OrgUser{OrgID: 6}) + unittest.AssertNotExistsBean(t, &Team{OrgID: 6}) - org = db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + org = unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) err := DeleteOrganization(org) assert.Error(t, err) assert.True(t, IsErrUserOwnRepos(err)) - user := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) assert.Error(t, DeleteOrganization(user)) - CheckConsistencyFor(t, &User{}, &Team{}) + unittest.CheckConsistencyFor(t, &User{}, &Team{}) } func TestIsOrganizationOwner(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64, expected bool) { isOwner, err := IsOrganizationOwner(orgID, userID) assert.NoError(t, err) @@ -289,11 +290,11 @@ func TestIsOrganizationOwner(t *testing.T) { test(3, 3, false) test(6, 5, true) test(6, 4, false) - test(db.NonexistentID, db.NonexistentID, false) + test(unittest.NonexistentID, unittest.NonexistentID, false) } func TestIsOrganizationMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64, expected bool) { isMember, err := IsOrganizationMember(orgID, userID) assert.NoError(t, err) @@ -304,11 +305,11 @@ func TestIsOrganizationMember(t *testing.T) { test(3, 4, true) test(6, 5, true) test(6, 4, false) - test(db.NonexistentID, db.NonexistentID, false) + test(unittest.NonexistentID, unittest.NonexistentID, false) } func TestIsPublicMembership(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64, expected bool) { isMember, err := IsPublicMembership(orgID, userID) assert.NoError(t, err) @@ -319,11 +320,11 @@ func TestIsPublicMembership(t *testing.T) { test(3, 4, false) test(6, 5, true) test(6, 4, false) - test(db.NonexistentID, db.NonexistentID, false) + test(unittest.NonexistentID, unittest.NonexistentID, false) } func TestGetOrgsByUserID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) orgs, err := GetOrgsByUserID(4, true) assert.NoError(t, err) @@ -337,7 +338,7 @@ func TestGetOrgsByUserID(t *testing.T) { } func TestGetOwnedOrgsByUserID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) orgs, err := GetOwnedOrgsByUserID(2) assert.NoError(t, err) @@ -351,7 +352,7 @@ func TestGetOwnedOrgsByUserID(t *testing.T) { } func TestGetOwnedOrgsByUserIDDesc(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) orgs, err := GetOwnedOrgsByUserIDDesc(5, "id") assert.NoError(t, err) @@ -366,7 +367,7 @@ func TestGetOwnedOrgsByUserIDDesc(t *testing.T) { } func TestGetOrgUsersByUserID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) orgUsers, err := GetOrgUsersByUserID(5, &SearchOrganizationsOptions{All: true}) assert.NoError(t, err) @@ -396,7 +397,7 @@ func TestGetOrgUsersByUserID(t *testing.T) { } func TestGetOrgUsersByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) orgUsers, err := GetOrgUsersByOrgID(&FindOrgMembersOpts{ ListOptions: db.ListOptions{}, @@ -421,7 +422,7 @@ func TestGetOrgUsersByOrgID(t *testing.T) { orgUsers, err = GetOrgUsersByOrgID(&FindOrgMembersOpts{ ListOptions: db.ListOptions{}, - OrgID: db.NonexistentID, + OrgID: unittest.NonexistentID, PublicOnly: false, }) assert.NoError(t, err) @@ -429,33 +430,33 @@ func TestGetOrgUsersByOrgID(t *testing.T) { } func TestChangeOrgUserStatus(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID, userID int64, public bool) { assert.NoError(t, ChangeOrgUserStatus(orgID, userID, public)) - orgUser := db.AssertExistsAndLoadBean(t, &OrgUser{OrgID: orgID, UID: userID}).(*OrgUser) + orgUser := unittest.AssertExistsAndLoadBean(t, &OrgUser{OrgID: orgID, UID: userID}).(*OrgUser) assert.Equal(t, public, orgUser.IsPublic) } testSuccess(3, 2, false) testSuccess(3, 2, false) testSuccess(3, 4, true) - assert.NoError(t, ChangeOrgUserStatus(db.NonexistentID, db.NonexistentID, true)) + assert.NoError(t, ChangeOrgUserStatus(unittest.NonexistentID, unittest.NonexistentID, true)) } func TestAddOrgUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID, userID int64, isPublic bool) { - org := db.AssertExistsAndLoadBean(t, &User{ID: orgID}).(*User) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: orgID}).(*User) expectedNumMembers := org.NumMembers - if !db.BeanExists(t, &OrgUser{OrgID: orgID, UID: userID}) { + if !unittest.BeanExists(t, &OrgUser{OrgID: orgID, UID: userID}) { expectedNumMembers++ } assert.NoError(t, AddOrgUser(orgID, userID)) ou := &OrgUser{OrgID: orgID, UID: userID} - db.AssertExistsAndLoadBean(t, ou) + unittest.AssertExistsAndLoadBean(t, ou) assert.Equal(t, isPublic, ou.IsPublic) - org = db.AssertExistsAndLoadBean(t, &User{ID: orgID}).(*User) + org = unittest.AssertExistsAndLoadBean(t, &User{ID: orgID}).(*User) assert.EqualValues(t, expectedNumMembers, org.NumMembers) } @@ -467,20 +468,20 @@ func TestAddOrgUser(t *testing.T) { setting.Service.DefaultOrgMemberVisible = true testSuccess(6, 3, true) - CheckConsistencyFor(t, &User{}, &Team{}) + unittest.CheckConsistencyFor(t, &User{}, &Team{}) } func TestRemoveOrgUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID, userID int64) { - org := db.AssertExistsAndLoadBean(t, &User{ID: orgID}).(*User) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: orgID}).(*User) expectedNumMembers := org.NumMembers - if db.BeanExists(t, &OrgUser{OrgID: orgID, UID: userID}) { + if unittest.BeanExists(t, &OrgUser{OrgID: orgID, UID: userID}) { expectedNumMembers-- } assert.NoError(t, RemoveOrgUser(orgID, userID)) - db.AssertNotExistsBean(t, &OrgUser{OrgID: orgID, UID: userID}) - org = db.AssertExistsAndLoadBean(t, &User{ID: orgID}).(*User) + unittest.AssertNotExistsBean(t, &OrgUser{OrgID: orgID, UID: userID}) + org = unittest.AssertExistsAndLoadBean(t, &User{ID: orgID}).(*User) assert.EqualValues(t, expectedNumMembers, org.NumMembers) } testSuccess(3, 4) @@ -489,13 +490,13 @@ func TestRemoveOrgUser(t *testing.T) { err := RemoveOrgUser(7, 5) assert.Error(t, err) assert.True(t, IsErrLastOrgOwner(err)) - db.AssertExistsAndLoadBean(t, &OrgUser{OrgID: 7, UID: 5}) - CheckConsistencyFor(t, &User{}, &Team{}) + unittest.AssertExistsAndLoadBean(t, &OrgUser{OrgID: 7, UID: 5}) + unittest.CheckConsistencyFor(t, &User{}, &Team{}) } func TestUser_GetUserTeamIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) testSuccess := func(userID int64, expected []int64) { teamIDs, err := org.GetUserTeamIDs(userID) assert.NoError(t, err) @@ -503,12 +504,12 @@ func TestUser_GetUserTeamIDs(t *testing.T) { } testSuccess(2, []int64{1, 2}) testSuccess(4, []int64{2}) - testSuccess(db.NonexistentID, []int64{}) + testSuccess(unittest.NonexistentID, []int64{}) } func TestAccessibleReposEnv_CountRepos(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) testSuccess := func(userID, expectedCount int64) { env, err := org.AccessibleReposEnv(userID) assert.NoError(t, err) @@ -521,8 +522,8 @@ func TestAccessibleReposEnv_CountRepos(t *testing.T) { } func TestAccessibleReposEnv_RepoIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) testSuccess := func(userID, _, pageSize int64, expectedRepoIDs []int64) { env, err := org.AccessibleReposEnv(userID) assert.NoError(t, err) @@ -535,8 +536,8 @@ func TestAccessibleReposEnv_RepoIDs(t *testing.T) { } func TestAccessibleReposEnv_Repos(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) testSuccess := func(userID int64, expectedRepoIDs []int64) { env, err := org.AccessibleReposEnv(userID) assert.NoError(t, err) @@ -544,7 +545,7 @@ func TestAccessibleReposEnv_Repos(t *testing.T) { assert.NoError(t, err) expectedRepos := make([]*Repository, len(expectedRepoIDs)) for i, repoID := range expectedRepoIDs { - expectedRepos[i] = db.AssertExistsAndLoadBean(t, + expectedRepos[i] = unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) } assert.Equal(t, expectedRepos, repos) @@ -554,8 +555,8 @@ func TestAccessibleReposEnv_Repos(t *testing.T) { } func TestAccessibleReposEnv_MirrorRepos(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) testSuccess := func(userID int64, expectedRepoIDs []int64) { env, err := org.AccessibleReposEnv(userID) assert.NoError(t, err) @@ -563,7 +564,7 @@ func TestAccessibleReposEnv_MirrorRepos(t *testing.T) { assert.NoError(t, err) expectedRepos := make([]*Repository, len(expectedRepoIDs)) for i, repoID := range expectedRepoIDs { - expectedRepos[i] = db.AssertExistsAndLoadBean(t, + expectedRepos[i] = unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) } assert.Equal(t, expectedRepos, repos) @@ -573,9 +574,9 @@ func TestAccessibleReposEnv_MirrorRepos(t *testing.T) { } func TestHasOrgVisibleTypePublic(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - user3 := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user3 := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) const newOrgName = "test-org-public" org := &User{ @@ -583,9 +584,9 @@ func TestHasOrgVisibleTypePublic(t *testing.T) { Visibility: structs.VisibleTypePublic, } - db.AssertNotExistsBean(t, &User{Name: org.Name, Type: UserTypeOrganization}) + unittest.AssertNotExistsBean(t, &User{Name: org.Name, Type: UserTypeOrganization}) assert.NoError(t, CreateOrganization(org, owner)) - org = db.AssertExistsAndLoadBean(t, + org = unittest.AssertExistsAndLoadBean(t, &User{Name: org.Name, Type: UserTypeOrganization}).(*User) test1 := HasOrgOrUserVisible(org, owner) test2 := HasOrgOrUserVisible(org, user3) @@ -596,9 +597,9 @@ func TestHasOrgVisibleTypePublic(t *testing.T) { } func TestHasOrgVisibleTypeLimited(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - user3 := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user3 := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) const newOrgName = "test-org-limited" org := &User{ @@ -606,9 +607,9 @@ func TestHasOrgVisibleTypeLimited(t *testing.T) { Visibility: structs.VisibleTypeLimited, } - db.AssertNotExistsBean(t, &User{Name: org.Name, Type: UserTypeOrganization}) + unittest.AssertNotExistsBean(t, &User{Name: org.Name, Type: UserTypeOrganization}) assert.NoError(t, CreateOrganization(org, owner)) - org = db.AssertExistsAndLoadBean(t, + org = unittest.AssertExistsAndLoadBean(t, &User{Name: org.Name, Type: UserTypeOrganization}).(*User) test1 := HasOrgOrUserVisible(org, owner) test2 := HasOrgOrUserVisible(org, user3) @@ -619,9 +620,9 @@ func TestHasOrgVisibleTypeLimited(t *testing.T) { } func TestHasOrgVisibleTypePrivate(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - user3 := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user3 := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) const newOrgName = "test-org-private" org := &User{ @@ -629,9 +630,9 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) { Visibility: structs.VisibleTypePrivate, } - db.AssertNotExistsBean(t, &User{Name: org.Name, Type: UserTypeOrganization}) + unittest.AssertNotExistsBean(t, &User{Name: org.Name, Type: UserTypeOrganization}) assert.NoError(t, CreateOrganization(org, owner)) - org = db.AssertExistsAndLoadBean(t, + org = unittest.AssertExistsAndLoadBean(t, &User{Name: org.Name, Type: UserTypeOrganization}).(*User) test1 := HasOrgOrUserVisible(org, owner) test2 := HasOrgOrUserVisible(org, user3) @@ -642,7 +643,7 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) { } func TestGetUsersWhoCanCreateOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) users, err := GetUsersWhoCanCreateOrgRepo(3) assert.NoError(t, err) diff --git a/models/project_test.go b/models/project_test.go index 8c630d8bedd5..70dabb7674fe 100644 --- a/models/project_test.go +++ b/models/project_test.go @@ -7,7 +7,7 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" @@ -32,7 +32,7 @@ func TestIsProjectTypeValid(t *testing.T) { } func TestGetProjects(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) projects, _, err := GetProjects(ProjectSearchOptions{RepoID: 1}) assert.NoError(t, err) @@ -48,7 +48,7 @@ func TestGetProjects(t *testing.T) { } func TestProject(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) project := &Project{ Type: ProjectTypeRepository, diff --git a/models/protected_tag_test.go b/models/protected_tag_test.go index fd29f7e64b2c..ed838483d2e5 100644 --- a/models/protected_tag_test.go +++ b/models/protected_tag_test.go @@ -7,12 +7,13 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestIsUserAllowed(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pt := &ProtectedTag{} allowed, err := pt.IsUserAllowed(1) diff --git a/models/pull_test.go b/models/pull_test.go index e6855240db06..0225b421fb53 100644 --- a/models/pull_test.go +++ b/models/pull_test.go @@ -9,20 +9,21 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestPullRequest_LoadAttributes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) + assert.NoError(t, unittest.PrepareTestDatabase()) + pr := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) assert.NoError(t, pr.LoadAttributes()) assert.NotNil(t, pr.Merger) assert.Equal(t, pr.MergerID, pr.Merger.ID) } func TestPullRequest_LoadIssue(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) + assert.NoError(t, unittest.PrepareTestDatabase()) + pr := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) assert.NoError(t, pr.LoadIssue()) assert.NotNil(t, pr.Issue) assert.Equal(t, int64(2), pr.Issue.ID) @@ -32,8 +33,8 @@ func TestPullRequest_LoadIssue(t *testing.T) { } func TestPullRequest_LoadBaseRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) + assert.NoError(t, unittest.PrepareTestDatabase()) + pr := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) assert.NoError(t, pr.LoadBaseRepo()) assert.NotNil(t, pr.BaseRepo) assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID) @@ -43,8 +44,8 @@ func TestPullRequest_LoadBaseRepo(t *testing.T) { } func TestPullRequest_LoadHeadRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) + assert.NoError(t, unittest.PrepareTestDatabase()) + pr := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) assert.NoError(t, pr.LoadHeadRepo()) assert.NotNil(t, pr.HeadRepo) assert.Equal(t, pr.HeadRepoID, pr.HeadRepo.ID) @@ -55,7 +56,7 @@ func TestPullRequest_LoadHeadRepo(t *testing.T) { // TODO TestNewPullRequest func TestPullRequestsNewest(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) prs, count, err := PullRequests(1, &PullRequestsOptions{ ListOptions: db.ListOptions{ Page: 1, @@ -74,7 +75,7 @@ func TestPullRequestsNewest(t *testing.T) { } func TestPullRequestsOldest(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) prs, count, err := PullRequests(1, &PullRequestsOptions{ ListOptions: db.ListOptions{ Page: 1, @@ -93,7 +94,7 @@ func TestPullRequestsOldest(t *testing.T) { } func TestGetUnmergedPullRequest(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr, err := GetUnmergedPullRequest(1, 1, "branch2", "master", PullRequestFlowGithub) assert.NoError(t, err) assert.Equal(t, int64(2), pr.ID) @@ -104,7 +105,7 @@ func TestGetUnmergedPullRequest(t *testing.T) { } func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) prs, err := GetUnmergedPullRequestsByHeadInfo(1, "branch2") assert.NoError(t, err) assert.Len(t, prs, 1) @@ -115,7 +116,7 @@ func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) { } func TestGetUnmergedPullRequestsByBaseInfo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) prs, err := GetUnmergedPullRequestsByBaseInfo(1, "master") assert.NoError(t, err) assert.Len(t, prs, 1) @@ -126,7 +127,7 @@ func TestGetUnmergedPullRequestsByBaseInfo(t *testing.T) { } func TestGetPullRequestByIndex(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr, err := GetPullRequestByIndex(1, 2) assert.NoError(t, err) assert.Equal(t, int64(1), pr.BaseRepoID) @@ -142,7 +143,7 @@ func TestGetPullRequestByIndex(t *testing.T) { } func TestGetPullRequestByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr, err := GetPullRequestByID(1) assert.NoError(t, err) assert.Equal(t, int64(1), pr.ID) @@ -154,7 +155,7 @@ func TestGetPullRequestByID(t *testing.T) { } func TestGetPullRequestByIssueID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr, err := GetPullRequestByIssueID(2) assert.NoError(t, err) assert.Equal(t, int64(2), pr.IssueID) @@ -165,20 +166,20 @@ func TestGetPullRequestByIssueID(t *testing.T) { } func TestPullRequest_Update(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) + assert.NoError(t, unittest.PrepareTestDatabase()) + pr := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) pr.BaseBranch = "baseBranch" pr.HeadBranch = "headBranch" pr.Update() - pr = db.AssertExistsAndLoadBean(t, &PullRequest{ID: pr.ID}).(*PullRequest) + pr = unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: pr.ID}).(*PullRequest) assert.Equal(t, "baseBranch", pr.BaseBranch) assert.Equal(t, "headBranch", pr.HeadBranch) - CheckConsistencyFor(t, pr) + unittest.CheckConsistencyFor(t, pr) } func TestPullRequest_UpdateCols(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr := &PullRequest{ ID: 1, BaseBranch: "baseBranch", @@ -186,18 +187,18 @@ func TestPullRequest_UpdateCols(t *testing.T) { } assert.NoError(t, pr.UpdateCols("head_branch")) - pr = db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) + pr = unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) assert.Equal(t, "master", pr.BaseBranch) assert.Equal(t, "headBranch", pr.HeadBranch) - CheckConsistencyFor(t, pr) + unittest.CheckConsistencyFor(t, pr) } func TestPullRequestList_LoadAttributes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) prs := []*PullRequest{ - db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest), - db.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest), + unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest), + unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest), } assert.NoError(t, PullRequestList(prs).LoadAttributes()) for _, pr := range prs { @@ -211,9 +212,9 @@ func TestPullRequestList_LoadAttributes(t *testing.T) { // TODO TestAddTestPullRequestTask func TestPullRequest_IsWorkInProgress(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) + pr := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) pr.LoadIssue() assert.False(t, pr.IsWorkInProgress()) @@ -226,9 +227,9 @@ func TestPullRequest_IsWorkInProgress(t *testing.T) { } func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) + pr := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) pr.LoadIssue() assert.Empty(t, pr.GetWorkInProgressPrefix()) @@ -242,8 +243,8 @@ func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) { } func TestPullRequest_GetDefaultMergeMessage_InternalTracker(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) + assert.NoError(t, unittest.PrepareTestDatabase()) + pr := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) assert.Equal(t, "Merge pull request 'issue3' (#3) from branch2 into master", pr.GetDefaultMergeMessage()) @@ -253,7 +254,7 @@ func TestPullRequest_GetDefaultMergeMessage_InternalTracker(t *testing.T) { } func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) externalTracker := RepoUnit{ Type: unit.TypeExternalTracker, @@ -265,7 +266,7 @@ func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) { baseRepo.Owner = &User{Name: "testOwner"} baseRepo.Units = []*RepoUnit{&externalTracker} - pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 2, BaseRepo: baseRepo}).(*PullRequest) + pr := unittest.AssertExistsAndLoadBean(t, &PullRequest{ID: 2, BaseRepo: baseRepo}).(*PullRequest) assert.Equal(t, "Merge pull request 'issue3' (!3) from branch2 into master", pr.GetDefaultMergeMessage()) diff --git a/models/repo_collaboration_test.go b/models/repo_collaboration_test.go index 326fb4dbf7a8..9b698c0af640 100644 --- a/models/repo_collaboration_test.go +++ b/models/repo_collaboration_test.go @@ -8,18 +8,19 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestRepository_AddCollaborator(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(repoID, userID int64) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) assert.NoError(t, repo.GetOwner()) - user := db.AssertExistsAndLoadBean(t, &User{ID: userID}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: userID}).(*User) assert.NoError(t, repo.AddCollaborator(user)) - CheckConsistencyFor(t, &Repository{ID: repoID}, &User{ID: userID}) + unittest.CheckConsistencyFor(t, &Repository{ID: repoID}, &User{ID: userID}) } testSuccess(1, 4) testSuccess(1, 4) @@ -27,9 +28,9 @@ func TestRepository_AddCollaborator(t *testing.T) { } func TestRepository_GetCollaborators(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) collaborators, err := repo.GetCollaborators(db.ListOptions{}) assert.NoError(t, err) expectedLen, err := db.GetEngine(db.DefaultContext).Count(&Collaboration{RepoID: repoID}) @@ -47,49 +48,49 @@ func TestRepository_GetCollaborators(t *testing.T) { } func TestRepository_IsCollaborator(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID, userID int64, expected bool) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) actual, err := repo.IsCollaborator(userID) assert.NoError(t, err) assert.Equal(t, expected, actual) } test(3, 2, true) - test(3, db.NonexistentID, false) + test(3, unittest.NonexistentID, false) test(4, 2, false) test(4, 4, true) } func TestRepository_ChangeCollaborationAccessMode(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) assert.NoError(t, repo.ChangeCollaborationAccessMode(4, AccessModeAdmin)) - collaboration := db.AssertExistsAndLoadBean(t, &Collaboration{RepoID: repo.ID, UserID: 4}).(*Collaboration) + collaboration := unittest.AssertExistsAndLoadBean(t, &Collaboration{RepoID: repo.ID, UserID: 4}).(*Collaboration) assert.EqualValues(t, AccessModeAdmin, collaboration.Mode) - access := db.AssertExistsAndLoadBean(t, &Access{UserID: 4, RepoID: repo.ID}).(*Access) + access := unittest.AssertExistsAndLoadBean(t, &Access{UserID: 4, RepoID: repo.ID}).(*Access) assert.EqualValues(t, AccessModeAdmin, access.Mode) assert.NoError(t, repo.ChangeCollaborationAccessMode(4, AccessModeAdmin)) - assert.NoError(t, repo.ChangeCollaborationAccessMode(db.NonexistentID, AccessModeAdmin)) + assert.NoError(t, repo.ChangeCollaborationAccessMode(unittest.NonexistentID, AccessModeAdmin)) - CheckConsistencyFor(t, &Repository{ID: repo.ID}) + unittest.CheckConsistencyFor(t, &Repository{ID: repo.ID}) } func TestRepository_DeleteCollaboration(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) assert.NoError(t, repo.GetOwner()) assert.NoError(t, repo.DeleteCollaboration(4)) - db.AssertNotExistsBean(t, &Collaboration{RepoID: repo.ID, UserID: 4}) + unittest.AssertNotExistsBean(t, &Collaboration{RepoID: repo.ID, UserID: 4}) assert.NoError(t, repo.DeleteCollaboration(4)) - db.AssertNotExistsBean(t, &Collaboration{RepoID: repo.ID, UserID: 4}) + unittest.AssertNotExistsBean(t, &Collaboration{RepoID: repo.ID, UserID: 4}) - CheckConsistencyFor(t, &Repository{ID: repo.ID}) + unittest.CheckConsistencyFor(t, &Repository{ID: repo.ID}) } diff --git a/models/repo_list_test.go b/models/repo_list_test.go index 3c30cad564d6..4722b073a3c2 100644 --- a/models/repo_list_test.go +++ b/models/repo_list_test.go @@ -8,13 +8,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" ) func TestSearchRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // test search public repository on explore page repos, count, err := SearchRepositoryByName(&SearchRepoOptions{ @@ -77,7 +78,7 @@ func TestSearchRepository(t *testing.T) { assert.Len(t, repos, 3) // Test non existing owner - repos, count, err = SearchRepositoryByName(&SearchRepoOptions{OwnerID: db.NonexistentID}) + repos, count, err = SearchRepositoryByName(&SearchRepoOptions{OwnerID: unittest.NonexistentID}) assert.NoError(t, err) assert.Empty(t, repos) @@ -324,7 +325,7 @@ func TestSearchRepository(t *testing.T) { } func TestSearchRepositoryByTopicName(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testCases := []struct { name string diff --git a/models/repo_permission_test.go b/models/repo_permission_test.go index 5e43937776f7..b64fe37911df 100644 --- a/models/repo_permission_test.go +++ b/models/repo_permission_test.go @@ -9,18 +9,19 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // public non-organization repo - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) // plain user - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) perm, err := GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -38,7 +39,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { } // collaborator - collaborator := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) + collaborator := unittest.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) perm, err = GetUserRepoPermission(repo, collaborator) assert.NoError(t, err) for _, unit := range repo.Units { @@ -47,7 +48,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { } // owner - owner := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) perm, err = GetUserRepoPermission(repo, owner) assert.NoError(t, err) for _, unit := range repo.Units { @@ -56,7 +57,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { } // admin - admin := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + admin := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) perm, err = GetUserRepoPermission(repo, admin) assert.NoError(t, err) for _, unit := range repo.Units { @@ -66,14 +67,14 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { } func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // private non-organization repo - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) // plain user - user := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) perm, err := GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -99,7 +100,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { } // owner - owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) perm, err = GetUserRepoPermission(repo, owner) assert.NoError(t, err) for _, unit := range repo.Units { @@ -108,7 +109,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { } // admin - admin := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + admin := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) perm, err = GetUserRepoPermission(repo, admin) assert.NoError(t, err) for _, unit := range repo.Units { @@ -118,14 +119,14 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { } func TestRepoPermissionPublicOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // public organization repo - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 32}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 32}).(*Repository) assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) // plain user - user := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) perm, err := GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -151,7 +152,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { } // org member team owner - owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) perm, err = GetUserRepoPermission(repo, owner) assert.NoError(t, err) for _, unit := range repo.Units { @@ -160,7 +161,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { } // org member team tester - member := db.AssertExistsAndLoadBean(t, &User{ID: 15}).(*User) + member := unittest.AssertExistsAndLoadBean(t, &User{ID: 15}).(*User) perm, err = GetUserRepoPermission(repo, member) assert.NoError(t, err) for _, unit := range repo.Units { @@ -170,7 +171,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { assert.False(t, perm.CanWrite(unit.TypeCode)) // admin - admin := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + admin := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) perm, err = GetUserRepoPermission(repo, admin) assert.NoError(t, err) for _, unit := range repo.Units { @@ -180,14 +181,14 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { } func TestRepoPermissionPrivateOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // private organization repo - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository) assert.NoError(t, repo.getUnits(db.GetEngine(db.DefaultContext))) // plain user - user := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) perm, err := GetUserRepoPermission(repo, user) assert.NoError(t, err) for _, unit := range repo.Units { @@ -213,7 +214,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { } // org member team owner - owner := db.AssertExistsAndLoadBean(t, &User{ID: 15}).(*User) + owner := unittest.AssertExistsAndLoadBean(t, &User{ID: 15}).(*User) perm, err = GetUserRepoPermission(repo, owner) assert.NoError(t, err) for _, unit := range repo.Units { @@ -222,7 +223,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { } // update team information and then check permission - team := db.AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team) + team := unittest.AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team) err = UpdateTeamUnits(team, nil) assert.NoError(t, err) perm, err = GetUserRepoPermission(repo, owner) @@ -233,7 +234,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { } // org member team tester - tester := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + tester := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) perm, err = GetUserRepoPermission(repo, tester) assert.NoError(t, err) assert.True(t, perm.CanWrite(unit.TypeIssues)) @@ -241,7 +242,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { assert.False(t, perm.CanRead(unit.TypeCode)) // org member team reviewer - reviewer := db.AssertExistsAndLoadBean(t, &User{ID: 20}).(*User) + reviewer := unittest.AssertExistsAndLoadBean(t, &User{ID: 20}).(*User) perm, err = GetUserRepoPermission(repo, reviewer) assert.NoError(t, err) assert.False(t, perm.CanRead(unit.TypeIssues)) @@ -249,7 +250,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { assert.True(t, perm.CanRead(unit.TypeCode)) // admin - admin := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + admin := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) perm, err = GetUserRepoPermission(repo, admin) assert.NoError(t, err) for _, unit := range repo.Units { diff --git a/models/repo_pushmirror_test.go b/models/repo_pushmirror_test.go index 65ef91814163..aa4465082f7c 100644 --- a/models/repo_pushmirror_test.go +++ b/models/repo_pushmirror_test.go @@ -8,14 +8,14 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" ) func TestPushMirrorsIterate(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) now := timeutil.TimeStampNow() diff --git a/models/repo_redirect_test.go b/models/repo_redirect_test.go index 9400422752cb..a9d3cc14942a 100644 --- a/models/repo_redirect_test.go +++ b/models/repo_redirect_test.go @@ -8,33 +8,34 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestLookupRepoRedirect(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repoID, err := LookupRepoRedirect(2, "oldrepo1") assert.NoError(t, err) assert.EqualValues(t, 1, repoID) - _, err = LookupRepoRedirect(db.NonexistentID, "doesnotexist") + _, err = LookupRepoRedirect(unittest.NonexistentID, "doesnotexist") assert.True(t, IsErrRepoRedirectNotExist(err)) } func TestNewRepoRedirect(t *testing.T) { // redirect to a completely new name - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "newreponame")) - db.AssertExistsAndLoadBean(t, &RepoRedirect{ + unittest.AssertExistsAndLoadBean(t, &RepoRedirect{ OwnerID: repo.OwnerID, LowerName: repo.LowerName, RedirectRepoID: repo.ID, }) - db.AssertExistsAndLoadBean(t, &RepoRedirect{ + unittest.AssertExistsAndLoadBean(t, &RepoRedirect{ OwnerID: repo.OwnerID, LowerName: "oldrepo1", RedirectRepoID: repo.ID, @@ -43,17 +44,17 @@ func TestNewRepoRedirect(t *testing.T) { func TestNewRepoRedirect2(t *testing.T) { // redirect to previously used name - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "oldrepo1")) - db.AssertExistsAndLoadBean(t, &RepoRedirect{ + unittest.AssertExistsAndLoadBean(t, &RepoRedirect{ OwnerID: repo.OwnerID, LowerName: repo.LowerName, RedirectRepoID: repo.ID, }) - db.AssertNotExistsBean(t, &RepoRedirect{ + unittest.AssertNotExistsBean(t, &RepoRedirect{ OwnerID: repo.OwnerID, LowerName: "oldrepo1", RedirectRepoID: repo.ID, @@ -62,12 +63,12 @@ func TestNewRepoRedirect2(t *testing.T) { func TestNewRepoRedirect3(t *testing.T) { // redirect for a previously-unredirected repo - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "newreponame")) - db.AssertExistsAndLoadBean(t, &RepoRedirect{ + unittest.AssertExistsAndLoadBean(t, &RepoRedirect{ OwnerID: repo.OwnerID, LowerName: repo.LowerName, RedirectRepoID: repo.ID, diff --git a/models/repo_test.go b/models/repo_test.go index 425e8c01913e..685570adc8e6 100644 --- a/models/repo_test.go +++ b/models/repo_test.go @@ -14,13 +14,14 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/markup" "github.com/stretchr/testify/assert" ) func TestMetas(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := &Repository{Name: "testRepo"} repo.Owner = &User{Name: "testOwner"} @@ -68,7 +69,7 @@ func TestMetas(t *testing.T) { } func TestGetRepositoryCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) count, err1 := GetRepositoryCount(&User{ID: int64(10)}) privateCount, err2 := GetPrivateRepositoryCount(&User{ID: int64(10)}) @@ -81,7 +82,7 @@ func TestGetRepositoryCount(t *testing.T) { } func TestGetPublicRepositoryCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) count, err := GetPublicRepositoryCount(&User{ID: int64(10)}) assert.NoError(t, err) @@ -89,7 +90,7 @@ func TestGetPublicRepositoryCount(t *testing.T) { } func TestGetPrivateRepositoryCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) count, err := GetPrivateRepositoryCount(&User{ID: int64(10)}) assert.NoError(t, err) @@ -97,7 +98,7 @@ func TestGetPrivateRepositoryCount(t *testing.T) { } func TestUpdateRepositoryVisibilityChanged(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Get sample repo and change visibility repo, err := GetRepositoryByID(9) @@ -117,7 +118,7 @@ func TestUpdateRepositoryVisibilityChanged(t *testing.T) { } func TestGetUserFork(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // User13 has repo 11 forked from repo10 repo, err := GetRepositoryByID(10) @@ -136,8 +137,8 @@ func TestGetUserFork(t *testing.T) { } func TestRepoAPIURL(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) assert.Equal(t, "https://try.gitea.io/api/v1/repos/user12/repo10", repo.APIURL()) } @@ -148,8 +149,8 @@ func TestUploadAvatar(t *testing.T) { var buff bytes.Buffer png.Encode(&buff, myImage) - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) err := repo.UploadAvatar(buff.Bytes()) assert.NoError(t, err) @@ -162,8 +163,8 @@ func TestUploadBigAvatar(t *testing.T) { var buff bytes.Buffer png.Encode(&buff, myImage) - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) err := repo.UploadAvatar(buff.Bytes()) assert.Error(t, err) @@ -175,8 +176,8 @@ func TestDeleteAvatar(t *testing.T) { var buff bytes.Buffer png.Encode(&buff, myImage) - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) err := repo.UploadAvatar(buff.Bytes()) assert.NoError(t, err) @@ -188,37 +189,37 @@ func TestDeleteAvatar(t *testing.T) { } func TestDoctorUserStarNum(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, DoctorUserStarNum()) } func TestRepoGetReviewers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // test public repo - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) reviewers, err := repo1.GetReviewers(2, 2) assert.NoError(t, err) assert.Len(t, reviewers, 4) // test private repo - repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) + repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) reviewers, err = repo2.GetReviewers(2, 2) assert.NoError(t, err) assert.Empty(t, reviewers) } func TestRepoGetReviewerTeams(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) + repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) teams, err := repo2.GetReviewerTeams() assert.NoError(t, err) assert.Empty(t, teams) - repo3 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) + repo3 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) teams, err = repo3.GetReviewerTeams() assert.NoError(t, err) assert.Len(t, teams, 2) diff --git a/models/repo_transfer_test.go b/models/repo_transfer_test.go index 4c6b7254c21a..df4f83919ba1 100644 --- a/models/repo_transfer_test.go +++ b/models/repo_transfer_test.go @@ -7,15 +7,15 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestRepositoryTransfer(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - doer := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) + doer := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) transfer, err := GetPendingRepositoryTransfer(repo) assert.NoError(t, err) @@ -29,7 +29,7 @@ func TestRepositoryTransfer(t *testing.T) { assert.Nil(t, transfer) assert.True(t, IsErrNoPendingTransfer(err)) - user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) assert.NoError(t, CreatePendingRepositoryTransfer(doer, user2, repo.ID, nil)) @@ -38,7 +38,7 @@ func TestRepositoryTransfer(t *testing.T) { assert.NoError(t, transfer.LoadAttributes()) assert.Equal(t, "user2", transfer.Recipient.Name) - user6 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user6 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) // Only transfer can be started at any given time err = CreatePendingRepositoryTransfer(doer, user6, repo.ID, nil) diff --git a/models/repo_watch_test.go b/models/repo_watch_test.go index 52222af2ca14..b7efcba71abb 100644 --- a/models/repo_watch_test.go +++ b/models/repo_watch_test.go @@ -8,13 +8,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestIsWatching(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, IsWatching(1, 1)) assert.True(t, IsWatching(4, 1)) @@ -22,27 +23,27 @@ func TestIsWatching(t *testing.T) { assert.False(t, IsWatching(1, 5)) assert.False(t, IsWatching(8, 1)) - assert.False(t, IsWatching(db.NonexistentID, db.NonexistentID)) + assert.False(t, IsWatching(unittest.NonexistentID, unittest.NonexistentID)) } func TestWatchRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) const repoID = 3 const userID = 2 assert.NoError(t, WatchRepo(userID, repoID, true)) - db.AssertExistsAndLoadBean(t, &Watch{RepoID: repoID, UserID: userID}) - CheckConsistencyFor(t, &Repository{ID: repoID}) + unittest.AssertExistsAndLoadBean(t, &Watch{RepoID: repoID, UserID: userID}) + unittest.CheckConsistencyFor(t, &Repository{ID: repoID}) assert.NoError(t, WatchRepo(userID, repoID, false)) - db.AssertNotExistsBean(t, &Watch{RepoID: repoID, UserID: userID}) - CheckConsistencyFor(t, &Repository{ID: repoID}) + unittest.AssertNotExistsBean(t, &Watch{RepoID: repoID, UserID: userID}) + unittest.CheckConsistencyFor(t, &Repository{ID: repoID}) } func TestGetWatchers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) watches, err := GetWatchers(repo.ID) assert.NoError(t, err) // One watchers are inactive, thus minus 1 @@ -51,30 +52,30 @@ func TestGetWatchers(t *testing.T) { assert.EqualValues(t, repo.ID, watch.RepoID) } - watches, err = GetWatchers(db.NonexistentID) + watches, err = GetWatchers(unittest.NonexistentID) assert.NoError(t, err) assert.Len(t, watches, 0) } func TestRepository_GetWatchers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) watchers, err := repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) for _, watcher := range watchers { - db.AssertExistsAndLoadBean(t, &Watch{UserID: watcher.ID, RepoID: repo.ID}) + unittest.AssertExistsAndLoadBean(t, &Watch{UserID: watcher.ID, RepoID: repo.ID}) } - repo = db.AssertExistsAndLoadBean(t, &Repository{ID: 9}).(*Repository) + repo = unittest.AssertExistsAndLoadBean(t, &Repository{ID: 9}).(*Repository) watchers, err = repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, 0) } func TestNotifyWatchers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) action := &Action{ ActUserID: 8, @@ -84,25 +85,25 @@ func TestNotifyWatchers(t *testing.T) { assert.NoError(t, NotifyWatchers(action)) // One watchers are inactive, thus action is only created for user 8, 1, 4, 11 - db.AssertExistsAndLoadBean(t, &Action{ + unittest.AssertExistsAndLoadBean(t, &Action{ ActUserID: action.ActUserID, UserID: 8, RepoID: action.RepoID, OpType: action.OpType, }) - db.AssertExistsAndLoadBean(t, &Action{ + unittest.AssertExistsAndLoadBean(t, &Action{ ActUserID: action.ActUserID, UserID: 1, RepoID: action.RepoID, OpType: action.OpType, }) - db.AssertExistsAndLoadBean(t, &Action{ + unittest.AssertExistsAndLoadBean(t, &Action{ ActUserID: action.ActUserID, UserID: 4, RepoID: action.RepoID, OpType: action.OpType, }) - db.AssertExistsAndLoadBean(t, &Action{ + unittest.AssertExistsAndLoadBean(t, &Action{ ActUserID: action.ActUserID, UserID: 11, RepoID: action.RepoID, @@ -111,9 +112,9 @@ func TestNotifyWatchers(t *testing.T) { } func TestWatchIfAuto(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) watchers, err := repo.GetWatchers(db.ListOptions{Page: 1}) assert.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) @@ -168,22 +169,22 @@ func TestWatchIfAuto(t *testing.T) { } func TestWatchRepoMode(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - db.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 0) + unittest.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 0) assert.NoError(t, WatchRepoMode(12, 1, RepoWatchModeAuto)) - db.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 1) - db.AssertCount(t, &Watch{UserID: 12, RepoID: 1, Mode: RepoWatchModeAuto}, 1) + unittest.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 1) + unittest.AssertCount(t, &Watch{UserID: 12, RepoID: 1, Mode: RepoWatchModeAuto}, 1) assert.NoError(t, WatchRepoMode(12, 1, RepoWatchModeNormal)) - db.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 1) - db.AssertCount(t, &Watch{UserID: 12, RepoID: 1, Mode: RepoWatchModeNormal}, 1) + unittest.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 1) + unittest.AssertCount(t, &Watch{UserID: 12, RepoID: 1, Mode: RepoWatchModeNormal}, 1) assert.NoError(t, WatchRepoMode(12, 1, RepoWatchModeDont)) - db.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 1) - db.AssertCount(t, &Watch{UserID: 12, RepoID: 1, Mode: RepoWatchModeDont}, 1) + unittest.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 1) + unittest.AssertCount(t, &Watch{UserID: 12, RepoID: 1, Mode: RepoWatchModeDont}, 1) assert.NoError(t, WatchRepoMode(12, 1, RepoWatchModeNone)) - db.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 0) + unittest.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 0) } diff --git a/models/review_test.go b/models/review_test.go index c809a3d66222..2d07ea2ce4d5 100644 --- a/models/review_test.go +++ b/models/review_test.go @@ -7,12 +7,12 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestGetReviewByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) review, err := GetReviewByID(1) assert.NoError(t, err) assert.Equal(t, "Demo Review", review.Content) @@ -24,23 +24,23 @@ func TestGetReviewByID(t *testing.T) { } func TestReview_LoadAttributes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - review := db.AssertExistsAndLoadBean(t, &Review{ID: 1}).(*Review) + assert.NoError(t, unittest.PrepareTestDatabase()) + review := unittest.AssertExistsAndLoadBean(t, &Review{ID: 1}).(*Review) assert.NoError(t, review.LoadAttributes()) assert.NotNil(t, review.Issue) assert.NotNil(t, review.Reviewer) - invalidReview1 := db.AssertExistsAndLoadBean(t, &Review{ID: 2}).(*Review) + invalidReview1 := unittest.AssertExistsAndLoadBean(t, &Review{ID: 2}).(*Review) assert.Error(t, invalidReview1.LoadAttributes()) - invalidReview2 := db.AssertExistsAndLoadBean(t, &Review{ID: 3}).(*Review) + invalidReview2 := unittest.AssertExistsAndLoadBean(t, &Review{ID: 3}).(*Review) assert.Error(t, invalidReview2.LoadAttributes()) } func TestReview_LoadCodeComments(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - review := db.AssertExistsAndLoadBean(t, &Review{ID: 4}).(*Review) + review := unittest.AssertExistsAndLoadBean(t, &Review{ID: 4}).(*Review) assert.NoError(t, review.LoadAttributes()) assert.NoError(t, review.LoadCodeComments()) assert.Len(t, review.CodeComments, 1) @@ -57,7 +57,7 @@ func TestReviewType_Icon(t *testing.T) { } func TestFindReviews(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) reviews, err := FindReviews(FindReviewOptions{ Type: ReviewTypeApprove, IssueID: 2, @@ -69,9 +69,9 @@ func TestFindReviews(t *testing.T) { } func TestGetCurrentReview(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) - user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) review, err := GetCurrentReview(user, issue) assert.NoError(t, err) @@ -79,7 +79,7 @@ func TestGetCurrentReview(t *testing.T) { assert.Equal(t, ReviewTypePending, review.Type) assert.Equal(t, "Pending Review", review.Content) - user2 := db.AssertExistsAndLoadBean(t, &User{ID: 7}).(*User) + user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 7}).(*User) review2, err := GetCurrentReview(user2, issue) assert.Error(t, err) assert.True(t, IsErrReviewNotExist(err)) @@ -87,10 +87,10 @@ func TestGetCurrentReview(t *testing.T) { } func TestCreateReview(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) - user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) review, err := CreateReview(CreateReviewOptions{ Content: "New Review", @@ -100,16 +100,16 @@ func TestCreateReview(t *testing.T) { }) assert.NoError(t, err) assert.Equal(t, "New Review", review.Content) - db.AssertExistsAndLoadBean(t, &Review{Content: "New Review"}) + unittest.AssertExistsAndLoadBean(t, &Review{Content: "New Review"}) } func TestGetReviewersByIssueID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 3}).(*Issue) - user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - user3 := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) - user4 := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) + issue := unittest.AssertExistsAndLoadBean(t, &Issue{ID: 3}).(*Issue) + user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user3 := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + user4 := unittest.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) expectedReviews := []*Review{} expectedReviews = append(expectedReviews, @@ -144,45 +144,45 @@ func TestGetReviewersByIssueID(t *testing.T) { } func TestDismissReview(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - rejectReviewExample := db.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) - requestReviewExample := db.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) - approveReviewExample := db.AssertExistsAndLoadBean(t, &Review{ID: 8}).(*Review) + rejectReviewExample := unittest.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) + requestReviewExample := unittest.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) + approveReviewExample := unittest.AssertExistsAndLoadBean(t, &Review{ID: 8}).(*Review) assert.False(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) assert.NoError(t, DismissReview(rejectReviewExample, true)) - rejectReviewExample = db.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) - requestReviewExample = db.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) + rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) + requestReviewExample = unittest.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) assert.True(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.NoError(t, DismissReview(requestReviewExample, true)) - rejectReviewExample = db.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) - requestReviewExample = db.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) + rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) + requestReviewExample = unittest.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) assert.True(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) assert.NoError(t, DismissReview(requestReviewExample, true)) - rejectReviewExample = db.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) - requestReviewExample = db.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) + rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) + requestReviewExample = unittest.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) assert.True(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) assert.NoError(t, DismissReview(requestReviewExample, false)) - rejectReviewExample = db.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) - requestReviewExample = db.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) + rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) + requestReviewExample = unittest.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) assert.True(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) assert.NoError(t, DismissReview(requestReviewExample, false)) - rejectReviewExample = db.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) - requestReviewExample = db.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) + rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) + requestReviewExample = unittest.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) assert.True(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) diff --git a/models/star_test.go b/models/star_test.go index 326da8a861d9..e1313727332e 100644 --- a/models/star_test.go +++ b/models/star_test.go @@ -8,32 +8,33 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestStarRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) const userID = 2 const repoID = 1 - db.AssertNotExistsBean(t, &Star{UID: userID, RepoID: repoID}) + unittest.AssertNotExistsBean(t, &Star{UID: userID, RepoID: repoID}) assert.NoError(t, StarRepo(userID, repoID, true)) - db.AssertExistsAndLoadBean(t, &Star{UID: userID, RepoID: repoID}) + unittest.AssertExistsAndLoadBean(t, &Star{UID: userID, RepoID: repoID}) assert.NoError(t, StarRepo(userID, repoID, true)) - db.AssertExistsAndLoadBean(t, &Star{UID: userID, RepoID: repoID}) + unittest.AssertExistsAndLoadBean(t, &Star{UID: userID, RepoID: repoID}) assert.NoError(t, StarRepo(userID, repoID, false)) - db.AssertNotExistsBean(t, &Star{UID: userID, RepoID: repoID}) + unittest.AssertNotExistsBean(t, &Star{UID: userID, RepoID: repoID}) } func TestIsStaring(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, IsStaring(2, 4)) assert.False(t, IsStaring(3, 4)) } func TestRepository_GetStargazers(t *testing.T) { // repo with stargazers - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) gazers, err := repo.GetStargazers(db.ListOptions{Page: 0}) assert.NoError(t, err) if assert.Len(t, gazers, 1) { @@ -43,8 +44,8 @@ func TestRepository_GetStargazers(t *testing.T) { func TestRepository_GetStargazers2(t *testing.T) { // repo with stargazers - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) gazers, err := repo.GetStargazers(db.ListOptions{Page: 0}) assert.NoError(t, err) assert.Len(t, gazers, 0) @@ -52,9 +53,9 @@ func TestRepository_GetStargazers2(t *testing.T) { func TestUser_GetStarredRepos(t *testing.T) { // user who has starred repos - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) starred, err := user.GetStarredRepos(false, 1, 10, "") assert.NoError(t, err) if assert.Len(t, starred, 1) { @@ -71,9 +72,9 @@ func TestUser_GetStarredRepos(t *testing.T) { func TestUser_GetStarredRepos2(t *testing.T) { // user who has no starred repos - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) starred, err := user.GetStarredRepos(false, 1, 10, "") assert.NoError(t, err) assert.Len(t, starred, 0) @@ -84,9 +85,9 @@ func TestUser_GetStarredRepos2(t *testing.T) { } func TestUserGetStarredRepoCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) counts, err := user.GetStarredRepoCount(false) assert.NoError(t, err) assert.Equal(t, int64(1), counts) diff --git a/models/task.go b/models/task.go index 7da9307c9596..c8af1a4967ff 100644 --- a/models/task.go +++ b/models/task.go @@ -9,7 +9,7 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/json" - migration "code.gitea.io/gitea/modules/migrations/base" + "code.gitea.io/gitea/modules/migration" "code.gitea.io/gitea/modules/secret" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" diff --git a/models/token_test.go b/models/token_test.go index 21d827ea6158..191da7820ed4 100644 --- a/models/token_test.go +++ b/models/token_test.go @@ -7,18 +7,18 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestNewAccessToken(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) token := &AccessToken{ UID: 3, Name: "Token C", } assert.NoError(t, NewAccessToken(token)) - db.AssertExistsAndLoadBean(t, token) + unittest.AssertExistsAndLoadBean(t, token) invalidToken := &AccessToken{ ID: token.ID, // duplicate @@ -31,7 +31,7 @@ func TestNewAccessToken(t *testing.T) { func TestAccessTokenByNameExists(t *testing.T) { name := "Token Gitea" - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) token := &AccessToken{ UID: 3, Name: name, @@ -44,7 +44,7 @@ func TestAccessTokenByNameExists(t *testing.T) { // Save it to the database assert.NoError(t, NewAccessToken(token)) - db.AssertExistsAndLoadBean(t, token) + unittest.AssertExistsAndLoadBean(t, token) // This token must be found by name in the DB now exist, err = AccessTokenByNameExists(token) @@ -64,7 +64,7 @@ func TestAccessTokenByNameExists(t *testing.T) { } func TestGetAccessTokenBySHA(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) token, err := GetAccessTokenBySHA("d2c6c1ba3890b309189a8e618c72a162e4efbf36") assert.NoError(t, err) assert.Equal(t, int64(1), token.UID) @@ -82,7 +82,7 @@ func TestGetAccessTokenBySHA(t *testing.T) { } func TestListAccessTokens(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tokens, err := ListAccessTokens(ListAccessTokensOptions{UserID: 1}) assert.NoError(t, err) if assert.Len(t, tokens, 2) { @@ -105,24 +105,24 @@ func TestListAccessTokens(t *testing.T) { } func TestUpdateAccessToken(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) token, err := GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") assert.NoError(t, err) token.Name = "Token Z" assert.NoError(t, UpdateAccessToken(token)) - db.AssertExistsAndLoadBean(t, token) + unittest.AssertExistsAndLoadBean(t, token) } func TestDeleteAccessTokenByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) token, err := GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") assert.NoError(t, err) assert.Equal(t, int64(1), token.UID) assert.NoError(t, DeleteAccessTokenByID(token.ID, 1)) - db.AssertNotExistsBean(t, token) + unittest.AssertNotExistsBean(t, token) err = DeleteAccessTokenByID(100, 100) assert.Error(t, err) diff --git a/models/topic_test.go b/models/topic_test.go index b069deaba3c2..def946b66688 100644 --- a/models/topic_test.go +++ b/models/topic_test.go @@ -8,6 +8,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) @@ -16,7 +17,7 @@ func TestAddTopic(t *testing.T) { repo1NrOfTopics := 3 repo2NrOfTopics := 2 - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) topics, _, err := FindTopics(&FindTopicOptions{}) assert.NoError(t, err) diff --git a/models/unittest/consistency.go b/models/unittest/consistency.go new file mode 100644 index 000000000000..2645084d3ede --- /dev/null +++ b/models/unittest/consistency.go @@ -0,0 +1,190 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package unittest + +import ( + "reflect" + "strconv" + "strings" + + "code.gitea.io/gitea/models/db" + + "github.com/stretchr/testify/assert" + "xorm.io/builder" +) + +const ( + // these const values are copied from `models` package to prevent from cycle-import + modelsUserTypeOrganization = 1 + modelsRepoWatchModeDont = 2 + modelsCommentTypeComment = 0 +) + +var consistencyCheckMap = make(map[string]func(t assert.TestingT, bean interface{})) + +// CheckConsistencyFor test that all matching database entries are consistent +func CheckConsistencyFor(t assert.TestingT, beansToCheck ...interface{}) { + for _, bean := range beansToCheck { + sliceType := reflect.SliceOf(reflect.TypeOf(bean)) + sliceValue := reflect.MakeSlice(sliceType, 0, 10) + + ptrToSliceValue := reflect.New(sliceType) + ptrToSliceValue.Elem().Set(sliceValue) + + assert.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface())) + sliceValue = ptrToSliceValue.Elem() + + for i := 0; i < sliceValue.Len(); i++ { + entity := sliceValue.Index(i).Interface() + checkForConsistency(t, entity) + } + } +} + +func checkForConsistency(t assert.TestingT, bean interface{}) { + tb, err := db.TableInfo(bean) + assert.NoError(t, err) + f := consistencyCheckMap[tb.Name] + if f == nil { + assert.Fail(t, "unknown bean type: %#v", bean) + return + } + f(t, bean) +} + +func init() { + parseBool := func(v string) bool { + b, _ := strconv.ParseBool(v) + return b + } + parseInt := func(v string) int { + i, _ := strconv.Atoi(v) + return i + } + + checkForUserConsistency := func(t assert.TestingT, bean interface{}) { + user := reflectionWrap(bean) + AssertCountByCond(t, "repository", builder.Eq{"owner_id": user.int("ID")}, user.int("NumRepos")) + AssertCountByCond(t, "star", builder.Eq{"uid": user.int("ID")}, user.int("NumStars")) + AssertCountByCond(t, "org_user", builder.Eq{"org_id": user.int("ID")}, user.int("NumMembers")) + AssertCountByCond(t, "team", builder.Eq{"org_id": user.int("ID")}, user.int("NumTeams")) + AssertCountByCond(t, "follow", builder.Eq{"user_id": user.int("ID")}, user.int("NumFollowing")) + AssertCountByCond(t, "follow", builder.Eq{"follow_id": user.int("ID")}, user.int("NumFollowers")) + if user.int("Type") != modelsUserTypeOrganization { + assert.EqualValues(t, 0, user.int("NumMembers")) + assert.EqualValues(t, 0, user.int("NumTeams")) + } + } + + checkForRepoConsistency := func(t assert.TestingT, bean interface{}) { + repo := reflectionWrap(bean) + assert.Equal(t, repo.str("LowerName"), strings.ToLower(repo.str("Name")), "repo: %+v", repo) + AssertCountByCond(t, "star", builder.Eq{"repo_id": repo.int("ID")}, repo.int("NumStars")) + AssertCountByCond(t, "milestone", builder.Eq{"repo_id": repo.int("ID")}, repo.int("NumMilestones")) + AssertCountByCond(t, "repository", builder.Eq{"fork_id": repo.int("ID")}, repo.int("NumForks")) + if repo.bool("IsFork") { + AssertExistsAndLoadMap(t, "repository", builder.Eq{"id": repo.int("ForkID")}) + } + + actual := GetCountByCond(t, "watch", builder.Eq{"repo_id": repo.int("ID")}. + And(builder.Neq{"mode": modelsRepoWatchModeDont})) + assert.EqualValues(t, repo.int("NumWatches"), actual, + "Unexpected number of watches for repo %+v", repo) + + actual = GetCountByCond(t, "issue", builder.Eq{"is_pull": false, "repo_id": repo.int("ID")}) + assert.EqualValues(t, repo.int("NumIssues"), actual, + "Unexpected number of issues for repo %+v", repo) + + actual = GetCountByCond(t, "issue", builder.Eq{"is_pull": false, "is_closed": true, "repo_id": repo.int("ID")}) + assert.EqualValues(t, repo.int("NumClosedIssues"), actual, + "Unexpected number of closed issues for repo %+v", repo) + + actual = GetCountByCond(t, "issue", builder.Eq{"is_pull": true, "repo_id": repo.int("ID")}) + assert.EqualValues(t, repo.int("NumPulls"), actual, + "Unexpected number of pulls for repo %+v", repo) + + actual = GetCountByCond(t, "issue", builder.Eq{"is_pull": true, "is_closed": true, "repo_id": repo.int("ID")}) + assert.EqualValues(t, repo.int("NumClosedPulls"), actual, + "Unexpected number of closed pulls for repo %+v", repo) + + actual = GetCountByCond(t, "milestone", builder.Eq{"is_closed": true, "repo_id": repo.int("ID")}) + assert.EqualValues(t, repo.int("NumClosedMilestones"), actual, + "Unexpected number of closed milestones for repo %+v", repo) + } + + checkForIssueConsistency := func(t assert.TestingT, bean interface{}) { + issue := reflectionWrap(bean) + typeComment := modelsCommentTypeComment + actual := GetCountByCond(t, "comment", builder.Eq{"`type`": typeComment, "issue_id": issue.int("ID")}) + assert.EqualValues(t, issue.int("NumComments"), actual, "Unexpected number of comments for issue %+v", issue) + if issue.bool("IsPull") { + prRow := AssertExistsAndLoadMap(t, "pull_request", builder.Eq{"issue_id": issue.int("ID")}) + assert.EqualValues(t, parseInt(prRow["index"]), issue.int("Index")) + } + } + + checkForPullRequestConsistency := func(t assert.TestingT, bean interface{}) { + pr := reflectionWrap(bean) + issueRow := AssertExistsAndLoadMap(t, "issue", builder.Eq{"id": pr.int("IssueID")}) + assert.True(t, parseBool(issueRow["is_pull"])) + assert.EqualValues(t, parseInt(issueRow["index"]), pr.int("Index")) + } + + checkForMilestoneConsistency := func(t assert.TestingT, bean interface{}) { + milestone := reflectionWrap(bean) + AssertCountByCond(t, "issue", builder.Eq{"milestone_id": milestone.int("ID")}, milestone.int("NumIssues")) + + actual := GetCountByCond(t, "issue", builder.Eq{"is_closed": true, "milestone_id": milestone.int("ID")}) + assert.EqualValues(t, milestone.int("NumClosedIssues"), actual, "Unexpected number of closed issues for milestone %+v", milestone) + + completeness := 0 + if milestone.int("NumIssues") > 0 { + completeness = milestone.int("NumClosedIssues") * 100 / milestone.int("NumIssues") + } + assert.Equal(t, completeness, milestone.int("Completeness")) + } + + checkForLabelConsistency := func(t assert.TestingT, bean interface{}) { + label := reflectionWrap(bean) + issueLabels, err := db.GetEngine(db.DefaultContext).Table("issue_label"). + Where(builder.Eq{"label_id": label.int("ID")}). + Query() + assert.NoError(t, err) + + assert.EqualValues(t, label.int("NumIssues"), len(issueLabels), "Unexpected number of issue for label %+v", label) + + issueIDs := make([]int, len(issueLabels)) + for i, issueLabel := range issueLabels { + issueIDs[i], _ = strconv.Atoi(string(issueLabel["issue_id"])) + } + + expected := int64(0) + if len(issueIDs) > 0 { + expected = GetCountByCond(t, "issue", builder.In("id", issueIDs).And(builder.Eq{"is_closed": true})) + } + assert.EqualValues(t, expected, label.int("NumClosedIssues"), "Unexpected number of closed issues for label %+v", label) + } + + checkForTeamConsistency := func(t assert.TestingT, bean interface{}) { + team := reflectionWrap(bean) + AssertCountByCond(t, "team_user", builder.Eq{"team_id": team.int("ID")}, team.int("NumMembers")) + AssertCountByCond(t, "team_repo", builder.Eq{"team_id": team.int("ID")}, team.int("NumRepos")) + } + + checkForActionConsistency := func(t assert.TestingT, bean interface{}) { + action := reflectionWrap(bean) + repoRow := AssertExistsAndLoadMap(t, "repository", builder.Eq{"id": action.int("RepoID")}) + assert.Equal(t, parseBool(repoRow["is_private"]), action.bool("IsPrivate"), "action: %+v", action) + } + + consistencyCheckMap["user"] = checkForUserConsistency + consistencyCheckMap["repository"] = checkForRepoConsistency + consistencyCheckMap["issue"] = checkForIssueConsistency + consistencyCheckMap["pull_request"] = checkForPullRequestConsistency + consistencyCheckMap["milestone"] = checkForMilestoneConsistency + consistencyCheckMap["label"] = checkForLabelConsistency + consistencyCheckMap["team"] = checkForTeamConsistency + consistencyCheckMap["action"] = checkForActionConsistency +} diff --git a/models/db/test_fixtures.go b/models/unittest/fixtures.go similarity index 89% rename from models/db/test_fixtures.go rename to models/unittest/fixtures.go index 2715b688ea35..af60df7b68e8 100644 --- a/models/db/test_fixtures.go +++ b/models/unittest/fixtures.go @@ -1,28 +1,34 @@ -// Copyright 2017 The Gitea Authors. All rights reserved. +// Copyright 2021 The Gitea Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package db +package unittest import ( "fmt" "os" "time" + "code.gitea.io/gitea/models/db" + "github.com/go-testfixtures/testfixtures/v3" + "xorm.io/xorm" "xorm.io/xorm/schemas" ) var fixtures *testfixtures.Loader -// InitFixtures initialize test fixtures for a test database -func InitFixtures(opts FixturesOptions, engine ...*xorm.Engine) (err error) { - e := x +func getXORMEngine(engine ...*xorm.Engine) (x *xorm.Engine) { if len(engine) == 1 { - e = engine[0] + return engine[0] } + return db.DefaultContext.(*db.Context).Engine().(*xorm.Engine) +} +// InitFixtures initialize test fixtures for a test database +func InitFixtures(opts FixturesOptions, engine ...*xorm.Engine) (err error) { + e := getXORMEngine(engine...) var testfiles func(*testfixtures.Loader) error if opts.Dir != "" { testfiles = testfixtures.Directory(opts.Dir) @@ -64,10 +70,7 @@ func InitFixtures(opts FixturesOptions, engine ...*xorm.Engine) (err error) { // LoadFixtures load fixtures for a test database func LoadFixtures(engine ...*xorm.Engine) error { - e := x - if len(engine) == 1 { - e = engine[0] - } + e := getXORMEngine(engine...) var err error // Database transaction conflicts could occur and result in ROLLBACK // As a simple workaround, we just retry 20 times. diff --git a/models/unittest/reflection.go b/models/unittest/reflection.go new file mode 100644 index 000000000000..68c312ac9e38 --- /dev/null +++ b/models/unittest/reflection.go @@ -0,0 +1,41 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package unittest + +import ( + "log" + "reflect" +) + +func fieldByName(v reflect.Value, field string) reflect.Value { + if v.Kind() == reflect.Ptr { + v = v.Elem() + } + f := v.FieldByName(field) + if !f.IsValid() { + log.Panicf("can not read %s for %v", field, v) + } + return f +} + +type reflectionValue struct { + v reflect.Value +} + +func reflectionWrap(v interface{}) *reflectionValue { + return &reflectionValue{v: reflect.ValueOf(v)} +} + +func (rv *reflectionValue) int(field string) int { + return int(fieldByName(rv.v, field).Int()) +} + +func (rv *reflectionValue) str(field string) string { + return fieldByName(rv.v, field).String() +} + +func (rv *reflectionValue) bool(field string) bool { + return fieldByName(rv.v, field).Bool() +} diff --git a/models/db/unit_tests.go b/models/unittest/testdb.go similarity index 54% rename from models/db/unit_tests.go rename to models/unittest/testdb.go index 6f079c8676ce..8771bc1d2139 100644 --- a/models/db/unit_tests.go +++ b/models/unittest/testdb.go @@ -1,18 +1,17 @@ -// Copyright 2016 The Gitea Authors. All rights reserved. +// Copyright 2021 The Gitea Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package db +package unittest import ( - "context" "fmt" - "math" "net/url" "os" "path/filepath" "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/storage" @@ -23,9 +22,6 @@ import ( "xorm.io/xorm/names" ) -// NonexistentID an ID that will never exist -const NonexistentID = int64(math.MaxInt64) - // giteaRoot a path to the gitea root var ( giteaRoot string @@ -38,7 +34,7 @@ func FixturesDir() string { } func fatalTestError(fmtStr string, args ...interface{}) { - fmt.Fprintf(os.Stderr, fmtStr, args...) + _, _ = fmt.Fprintf(os.Stderr, fmtStr, args...) os.Exit(1) } @@ -46,6 +42,7 @@ func fatalTestError(fmtStr string, args ...interface{}) { // test database. Creates the test database, and sets necessary settings. func MainTest(m *testing.M, pathToGiteaRoot string, fixtureFiles ...string) { var err error + giteaRoot = pathToGiteaRoot fixturesDir = filepath.Join(pathToGiteaRoot, "models", "fixtures") @@ -122,13 +119,14 @@ type FixturesOptions struct { // CreateTestEngine creates a memory database and loads the fixture data from fixturesDir func CreateTestEngine(opts FixturesOptions) error { - var err error - x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared&_txlock=immediate") + x, err := xorm.NewEngine("sqlite3", "file::memory:?cache=shared&_txlock=immediate") if err != nil { return err } x.SetMapper(names.GonicMapper{}) - if err = syncTables(); err != nil { + db.SetEngine(x) + + if err = db.SyncAllTables(); err != nil { return err } switch os.Getenv("GITEA_UNIT_TESTS_VERBOSE") { @@ -136,11 +134,6 @@ func CreateTestEngine(opts FixturesOptions) error { x.ShowSQL(true) } - DefaultContext = &Context{ - Context: context.Background(), - e: x, - } - return InitFixtures(opts) } @@ -158,96 +151,3 @@ func PrepareTestEnv(t testing.TB) { assert.NoError(t, util.CopyDir(metaPath, setting.RepoRootPath)) base.SetupGiteaRoot() // Makes sure GITEA_ROOT is set } - -type testCond struct { - query interface{} - args []interface{} -} - -// Cond create a condition with arguments for a test -func Cond(query interface{}, args ...interface{}) interface{} { - return &testCond{query: query, args: args} -} - -func whereConditions(sess *xorm.Session, conditions []interface{}) { - for _, condition := range conditions { - switch cond := condition.(type) { - case *testCond: - sess.Where(cond.query, cond.args...) - default: - sess.Where(cond) - } - } -} - -// LoadBeanIfExists loads beans from fixture database if exist -func LoadBeanIfExists(bean interface{}, conditions ...interface{}) (bool, error) { - return loadBeanIfExists(bean, conditions...) -} - -func loadBeanIfExists(bean interface{}, conditions ...interface{}) (bool, error) { - sess := x.NewSession() - defer sess.Close() - whereConditions(sess, conditions) - return sess.Get(bean) -} - -// BeanExists for testing, check if a bean exists -func BeanExists(t testing.TB, bean interface{}, conditions ...interface{}) bool { - exists, err := loadBeanIfExists(bean, conditions...) - assert.NoError(t, err) - return exists -} - -// AssertExistsAndLoadBean assert that a bean exists and load it from the test -// database -func AssertExistsAndLoadBean(t testing.TB, bean interface{}, conditions ...interface{}) interface{} { - exists, err := loadBeanIfExists(bean, conditions...) - assert.NoError(t, err) - assert.True(t, exists, - "Expected to find %+v (of type %T, with conditions %+v), but did not", - bean, bean, conditions) - return bean -} - -// GetCount get the count of a bean -func GetCount(t testing.TB, bean interface{}, conditions ...interface{}) int { - sess := x.NewSession() - defer sess.Close() - whereConditions(sess, conditions) - count, err := sess.Count(bean) - assert.NoError(t, err) - return int(count) -} - -// AssertNotExistsBean assert that a bean does not exist in the test database -func AssertNotExistsBean(t testing.TB, bean interface{}, conditions ...interface{}) { - exists, err := loadBeanIfExists(bean, conditions...) - assert.NoError(t, err) - assert.False(t, exists) -} - -// AssertExistsIf asserts that a bean exists or does not exist, depending on -// what is expected. -func AssertExistsIf(t *testing.T, expected bool, bean interface{}, conditions ...interface{}) { - exists, err := loadBeanIfExists(bean, conditions...) - assert.NoError(t, err) - assert.Equal(t, expected, exists) -} - -// AssertSuccessfulInsert assert that beans is successfully inserted -func AssertSuccessfulInsert(t testing.TB, beans ...interface{}) { - _, err := x.Insert(beans...) - assert.NoError(t, err) -} - -// AssertCount assert the count of a bean -func AssertCount(t testing.TB, bean, expected interface{}) { - assert.EqualValues(t, expected, GetCount(t, bean)) -} - -// AssertInt64InRange assert value is in range [low, high] -func AssertInt64InRange(t testing.TB, low, high, value int64) { - assert.True(t, value >= low && value <= high, - "Expected value in range [%d, %d], found %d", low, high, value) -} diff --git a/models/unittest/unit_tests.go b/models/unittest/unit_tests.go new file mode 100644 index 000000000000..6c20c2781bb4 --- /dev/null +++ b/models/unittest/unit_tests.go @@ -0,0 +1,139 @@ +// Copyright 2016 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package unittest + +import ( + "math" + + "code.gitea.io/gitea/models/db" + + "github.com/stretchr/testify/assert" + "xorm.io/builder" +) + +// Code in this file is mainly used by unittest.CheckConsistencyFor, which is not in the unit test for various reasons. +// In the future if we can decouple CheckConsistencyFor into separate unit test code, then this file can be moved into unittest package too. + +// NonexistentID an ID that will never exist +const NonexistentID = int64(math.MaxInt64) + +type testCond struct { + query interface{} + args []interface{} +} + +// Cond create a condition with arguments for a test +func Cond(query interface{}, args ...interface{}) interface{} { + return &testCond{query: query, args: args} +} + +func whereConditions(e db.Engine, conditions []interface{}) db.Engine { + for _, condition := range conditions { + switch cond := condition.(type) { + case *testCond: + e = e.Where(cond.query, cond.args...) + default: + e = e.Where(cond) + } + } + return e +} + +// LoadBeanIfExists loads beans from fixture database if exist +func LoadBeanIfExists(bean interface{}, conditions ...interface{}) (bool, error) { + e := db.GetEngine(db.DefaultContext) + return whereConditions(e, conditions).Get(bean) +} + +// BeanExists for testing, check if a bean exists +func BeanExists(t assert.TestingT, bean interface{}, conditions ...interface{}) bool { + exists, err := LoadBeanIfExists(bean, conditions...) + assert.NoError(t, err) + return exists +} + +// AssertExistsAndLoadBean assert that a bean exists and load it from the test database +func AssertExistsAndLoadBean(t assert.TestingT, bean interface{}, conditions ...interface{}) interface{} { + exists, err := LoadBeanIfExists(bean, conditions...) + assert.NoError(t, err) + assert.True(t, exists, + "Expected to find %+v (of type %T, with conditions %+v), but did not", + bean, bean, conditions) + return bean +} + +// AssertExistsAndLoadMap assert that a row exists and load it from the test database +func AssertExistsAndLoadMap(t assert.TestingT, table string, conditions ...interface{}) map[string]string { + e := db.GetEngine(db.DefaultContext).Table(table) + res, err := whereConditions(e, conditions).Query() + assert.NoError(t, err) + assert.True(t, len(res) == 1, + "Expected to find one row in %s (with conditions %+v), but found %d", + table, conditions, len(res), + ) + + if len(res) == 1 { + rec := map[string]string{} + for k, v := range res[0] { + rec[k] = string(v) + } + return rec + } + return nil +} + +// GetCount get the count of a bean +func GetCount(t assert.TestingT, bean interface{}, conditions ...interface{}) int { + e := db.GetEngine(db.DefaultContext) + count, err := whereConditions(e, conditions).Count(bean) + assert.NoError(t, err) + return int(count) +} + +// AssertNotExistsBean assert that a bean does not exist in the test database +func AssertNotExistsBean(t assert.TestingT, bean interface{}, conditions ...interface{}) { + exists, err := LoadBeanIfExists(bean, conditions...) + assert.NoError(t, err) + assert.False(t, exists) +} + +// AssertExistsIf asserts that a bean exists or does not exist, depending on +// what is expected. +func AssertExistsIf(t assert.TestingT, expected bool, bean interface{}, conditions ...interface{}) { + exists, err := LoadBeanIfExists(bean, conditions...) + assert.NoError(t, err) + assert.Equal(t, expected, exists) +} + +// AssertSuccessfulInsert assert that beans is successfully inserted +func AssertSuccessfulInsert(t assert.TestingT, beans ...interface{}) { + err := db.Insert(db.DefaultContext, beans...) + assert.NoError(t, err) +} + +// AssertCount assert the count of a bean +func AssertCount(t assert.TestingT, bean, expected interface{}) { + assert.EqualValues(t, expected, GetCount(t, bean)) +} + +// AssertInt64InRange assert value is in range [low, high] +func AssertInt64InRange(t assert.TestingT, low, high, value int64) { + assert.True(t, value >= low && value <= high, + "Expected value in range [%d, %d], found %d", low, high, value) +} + +// GetCountByCond get the count of database entries matching bean +func GetCountByCond(t assert.TestingT, tableName string, cond builder.Cond) int64 { + e := db.GetEngine(db.DefaultContext) + count, err := e.Table(tableName).Where(cond).Count() + assert.NoError(t, err) + return count +} + +// AssertCountByCond test the count of database entries matching bean +func AssertCountByCond(t assert.TestingT, tableName string, cond builder.Cond, expected int) { + assert.EqualValues(t, expected, GetCountByCond(t, tableName, cond), + "Failed consistency test, the counted bean (of table %s) was %+v", tableName, cond) +} diff --git a/models/user/email_address_test.go b/models/user/email_address_test.go index 5ed0bf88841a..642c2b387697 100644 --- a/models/user/email_address_test.go +++ b/models/user/email_address_test.go @@ -8,12 +8,13 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestGetEmailAddresses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) emails, _ := GetEmailAddresses(int64(1)) if assert.Len(t, emails, 3) { @@ -30,7 +31,7 @@ func TestGetEmailAddresses(t *testing.T) { } func TestIsEmailUsed(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) isExist, _ := IsEmailUsed(db.DefaultContext, "") assert.True(t, isExist) @@ -41,7 +42,7 @@ func TestIsEmailUsed(t *testing.T) { } func TestAddEmailAddress(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, AddEmailAddress(&EmailAddress{ Email: "user1234567890@example.com", @@ -60,7 +61,7 @@ func TestAddEmailAddress(t *testing.T) { } func TestAddEmailAddresses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // insert multiple email address emails := make([]*EmailAddress, 2) @@ -83,7 +84,7 @@ func TestAddEmailAddresses(t *testing.T) { } func TestDeleteEmailAddress(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, DeleteEmailAddress(&EmailAddress{ UID: int64(1), @@ -108,7 +109,7 @@ func TestDeleteEmailAddress(t *testing.T) { } func TestDeleteEmailAddresses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // delete multiple email address emails := make([]*EmailAddress, 2) diff --git a/models/user/main_test.go b/models/user/main_test.go index 2999c4c81db5..1dd9fb278131 100644 --- a/models/user/main_test.go +++ b/models/user/main_test.go @@ -8,11 +8,11 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", ".."), + unittest.MainTest(m, filepath.Join("..", ".."), "email_address.yml", "user_redirect.yml", ) diff --git a/models/user/redirect_test.go b/models/user/redirect_test.go index b33c42cf3d7c..82a0a0a2e21e 100644 --- a/models/user/redirect_test.go +++ b/models/user/redirect_test.go @@ -7,12 +7,13 @@ package user import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestLookupUserRedirect(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) userID, err := LookupUserRedirect("olduser1") assert.NoError(t, err) diff --git a/models/user_email_test.go b/models/user_email_test.go index 8c2bb48b9452..bde0778b6442 100644 --- a/models/user_email_test.go +++ b/models/user_email_test.go @@ -8,6 +8,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/util" @@ -15,7 +16,7 @@ import ( ) func TestMakeEmailPrimary(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) email := &user_model.EmailAddress{ Email: "user567890@example.com", @@ -49,7 +50,7 @@ func TestMakeEmailPrimary(t *testing.T) { } func TestActivate(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) email := &user_model.EmailAddress{ ID: int64(1), @@ -68,7 +69,7 @@ func TestActivate(t *testing.T) { } func TestListEmails(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Must find all users and their emails opts := &SearchEmailOptions{ diff --git a/models/user_follow_test.go b/models/user_follow_test.go index ae8faad6fa97..5ba922728a9a 100644 --- a/models/user_follow_test.go +++ b/models/user_follow_test.go @@ -7,44 +7,44 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestIsFollowing(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, IsFollowing(4, 2)) assert.False(t, IsFollowing(2, 4)) - assert.False(t, IsFollowing(5, db.NonexistentID)) - assert.False(t, IsFollowing(db.NonexistentID, 5)) - assert.False(t, IsFollowing(db.NonexistentID, db.NonexistentID)) + assert.False(t, IsFollowing(5, unittest.NonexistentID)) + assert.False(t, IsFollowing(unittest.NonexistentID, 5)) + assert.False(t, IsFollowing(unittest.NonexistentID, unittest.NonexistentID)) } func TestFollowUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(followerID, followedID int64) { assert.NoError(t, FollowUser(followerID, followedID)) - db.AssertExistsAndLoadBean(t, &Follow{UserID: followerID, FollowID: followedID}) + unittest.AssertExistsAndLoadBean(t, &Follow{UserID: followerID, FollowID: followedID}) } testSuccess(4, 2) testSuccess(5, 2) assert.NoError(t, FollowUser(2, 2)) - CheckConsistencyFor(t, &User{}) + unittest.CheckConsistencyFor(t, &User{}) } func TestUnfollowUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(followerID, followedID int64) { assert.NoError(t, UnfollowUser(followerID, followedID)) - db.AssertNotExistsBean(t, &Follow{UserID: followerID, FollowID: followedID}) + unittest.AssertNotExistsBean(t, &Follow{UserID: followerID, FollowID: followedID}) } testSuccess(4, 2) testSuccess(5, 2) testSuccess(2, 2) - CheckConsistencyFor(t, &User{}) + unittest.CheckConsistencyFor(t, &User{}) } diff --git a/models/user_heatmap_test.go b/models/user_heatmap_test.go index 8d2002b1a0f3..2abbbfc6f336 100644 --- a/models/user_heatmap_test.go +++ b/models/user_heatmap_test.go @@ -9,7 +9,7 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/timeutil" @@ -39,17 +39,17 @@ func TestGetUserHeatmapDataByUser(t *testing.T) { {10, 10, 3, `[{"timestamp":1603009800,"contributions":1},{"timestamp":1603010700,"contributions":2}]`}, } // Prepare - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Mock time timeutil.Set(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)) defer timeutil.Unset() for i, tc := range testCases { - user := db.AssertExistsAndLoadBean(t, &User{ID: tc.userID}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: tc.userID}).(*User) doer := &User{ID: tc.doerID} - _, err := db.LoadBeanIfExists(doer) + _, err := unittest.LoadBeanIfExists(doer) assert.NoError(t, err) if tc.doerID == 0 { doer = nil diff --git a/models/user_openid_test.go b/models/user_openid_test.go index 3c17b0742c87..d0d801ad187c 100644 --- a/models/user_openid_test.go +++ b/models/user_openid_test.go @@ -7,12 +7,13 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestGetUserOpenIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) oids, err := GetUserOpenIDs(int64(1)) if assert.NoError(t, err) && assert.Len(t, oids, 2) { @@ -30,7 +31,7 @@ func TestGetUserOpenIDs(t *testing.T) { } func TestGetUserByOpenID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) _, err := GetUserByOpenID("https://unknown") if assert.Error(t, err) { @@ -49,7 +50,7 @@ func TestGetUserByOpenID(t *testing.T) { } func TestToggleUserOpenIDVisibility(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) oids, err := GetUserOpenIDs(int64(2)) if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { return diff --git a/models/user_test.go b/models/user_test.go index 58044d1e99f9..dc273ce1bcd1 100644 --- a/models/user_test.go +++ b/models/user_test.go @@ -12,6 +12,7 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/login" + "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/structs" @@ -21,15 +22,15 @@ import ( ) func TestOAuth2Application_LoadUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - app := db.AssertExistsAndLoadBean(t, &login.OAuth2Application{ID: 1}).(*login.OAuth2Application) + assert.NoError(t, unittest.PrepareTestDatabase()) + app := unittest.AssertExistsAndLoadBean(t, &login.OAuth2Application{ID: 1}).(*login.OAuth2Application) user, err := GetUserByID(app.UID) assert.NoError(t, err) assert.NotNil(t, user) } func TestUserIsPublicMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { uid int64 @@ -55,7 +56,7 @@ func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) { } func TestIsUserOrgOwner(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { uid int64 @@ -81,7 +82,7 @@ func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) { } func TestGetUserEmailsByNames(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // ignore none active user email assert.Equal(t, []string{"user8@example.com"}, GetUserEmailsByNames([]string{"user8", "user9"})) @@ -91,12 +92,12 @@ func TestGetUserEmailsByNames(t *testing.T) { } func TestCanCreateOrganization(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - admin := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + admin := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) assert.True(t, admin.CanCreateOrganization()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) assert.True(t, user.CanCreateOrganization()) // Disable user create organization permission. user.AllowCreateOrganization = false @@ -109,7 +110,7 @@ func TestCanCreateOrganization(t *testing.T) { } func TestSearchUsers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(opts *SearchUserOptions, expectedUserOrOrgIDs []int64) { users, _, err := SearchUsers(opts) assert.NoError(t, err) @@ -178,8 +179,8 @@ func TestSearchUsers(t *testing.T) { func TestDeleteUser(t *testing.T) { test := func(userID int64) { - assert.NoError(t, db.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: userID}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: userID}).(*User) ownedRepos := make([]*Repository, 0, 10) assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&ownedRepos, &Repository{OwnerID: userID})) @@ -199,20 +200,20 @@ func TestDeleteUser(t *testing.T) { } } assert.NoError(t, DeleteUser(user)) - db.AssertNotExistsBean(t, &User{ID: userID}) - CheckConsistencyFor(t, &User{}, &Repository{}) + unittest.AssertNotExistsBean(t, &User{ID: userID}) + unittest.CheckConsistencyFor(t, &User{}, &Repository{}) } test(2) test(4) test(8) test(11) - org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) + org := unittest.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) assert.Error(t, DeleteUser(org)) } func TestEmailNotificationPreferences(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) for _, test := range []struct { expected string @@ -228,7 +229,7 @@ func TestEmailNotificationPreferences(t *testing.T) { {EmailNotificationsEnabled, 8}, {EmailNotificationsOnMention, 9}, } { - user := db.AssertExistsAndLoadBean(t, &User{ID: test.userID}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: test.userID}).(*User) assert.Equal(t, test.expected, user.EmailNotifications()) // Try all possible settings @@ -280,10 +281,10 @@ func BenchmarkHashPassword(b *testing.B) { } func TestGetOrgRepositoryIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) - user4 := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) - user5 := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + user2 := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user4 := unittest.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) + user5 := unittest.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) accessibleRepos, err := user2.GetOrgRepositoryIDs() assert.NoError(t, err) @@ -393,7 +394,7 @@ func TestCreateUser_Issue5882(t *testing.T) { } func TestGetUserIDsByNames(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // ignore non existing IDs, err := GetUserIDsByNames([]string{"user1", "user2", "none_existing_user"}, true) @@ -407,7 +408,7 @@ func TestGetUserIDsByNames(t *testing.T) { } func TestGetMaileableUsersByIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) results, err := GetMaileableUsersByIDs([]int64{1, 4}, false) assert.NoError(t, err) @@ -426,9 +427,9 @@ func TestGetMaileableUsersByIDs(t *testing.T) { } func TestAddLdapSSHPublicKeys(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) s := &login.Source{ID: 1} testCases := []struct { @@ -494,19 +495,19 @@ ssh-dss AAAAB3NzaC1kc3MAAACBAOChCC7lf6Uo9n7BmZ6M8St19PZf4Tn59NriyboW2x/DZuYAz3ib } func TestUpdateUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + assert.NoError(t, unittest.PrepareTestDatabase()) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user.KeepActivityPrivate = true assert.NoError(t, UpdateUser(user)) - user = db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user = unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) assert.True(t, user.KeepActivityPrivate) setting.Service.AllowedUserVisibilityModesSlice = []bool{true, false, false} user.KeepActivityPrivate = false user.Visibility = structs.VisibleTypePrivate assert.Error(t, UpdateUser(user)) - user = db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user = unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) assert.True(t, user.KeepActivityPrivate) user.Email = "no mail@mail.org" @@ -515,16 +516,16 @@ func TestUpdateUser(t *testing.T) { func TestNewUserRedirect(t *testing.T) { // redirect to a completely new name - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "newusername")) - db.AssertExistsAndLoadBean(t, &user_model.Redirect{ + unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{ LowerName: user.LowerName, RedirectUserID: user.ID, }) - db.AssertExistsAndLoadBean(t, &user_model.Redirect{ + unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{ LowerName: "olduser1", RedirectUserID: user.ID, }) @@ -532,16 +533,16 @@ func TestNewUserRedirect(t *testing.T) { func TestNewUserRedirect2(t *testing.T) { // redirect to previously used name - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "olduser1")) - db.AssertExistsAndLoadBean(t, &user_model.Redirect{ + unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{ LowerName: user.LowerName, RedirectUserID: user.ID, }) - db.AssertNotExistsBean(t, &user_model.Redirect{ + unittest.AssertNotExistsBean(t, &user_model.Redirect{ LowerName: "olduser1", RedirectUserID: user.ID, }) @@ -549,12 +550,12 @@ func TestNewUserRedirect2(t *testing.T) { func TestNewUserRedirect3(t *testing.T) { // redirect for a previously-unredirected user - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) + user := unittest.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "newusername")) - db.AssertExistsAndLoadBean(t, &user_model.Redirect{ + unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{ LowerName: user.LowerName, RedirectUserID: user.ID, }) diff --git a/models/userlist_test.go b/models/userlist_test.go index 9e75f783f192..2b8518c92f2e 100644 --- a/models/userlist_test.go +++ b/models/userlist_test.go @@ -8,12 +8,13 @@ import ( "fmt" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestUserListIsPublicMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { orgid int64 expected map[int64]bool @@ -39,7 +40,7 @@ func testUserListIsPublicMember(t *testing.T, orgID int64, expected map[int64]bo } func TestUserListIsUserOrgOwner(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { orgid int64 expected map[int64]bool @@ -65,7 +66,7 @@ func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bo } func TestUserListIsTwoFaEnrolled(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { orgid int64 expected map[int64]bool diff --git a/models/webhook/main_test.go b/models/webhook/main_test.go index f94612a755b0..89c947b061fd 100644 --- a/models/webhook/main_test.go +++ b/models/webhook/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", ".."), "webhook.yml", "hook_task.yml") + unittest.MainTest(m, filepath.Join("..", ".."), "webhook.yml", "hook_task.yml") } diff --git a/models/webhook/webhook_test.go b/models/webhook/webhook_test.go index df2c37b355f8..d1a76795fdbe 100644 --- a/models/webhook/webhook_test.go +++ b/models/webhook/webhook_test.go @@ -10,6 +10,7 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" @@ -29,23 +30,23 @@ func TestIsValidHookContentType(t *testing.T) { } func TestWebhook_History(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - webhook := db.AssertExistsAndLoadBean(t, &Webhook{ID: 1}).(*Webhook) + assert.NoError(t, unittest.PrepareTestDatabase()) + webhook := unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 1}).(*Webhook) tasks, err := webhook.History(0) assert.NoError(t, err) if assert.Len(t, tasks, 1) { assert.Equal(t, int64(1), tasks[0].ID) } - webhook = db.AssertExistsAndLoadBean(t, &Webhook{ID: 2}).(*Webhook) + webhook = unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 2}).(*Webhook) tasks, err = webhook.History(0) assert.NoError(t, err) assert.Len(t, tasks, 0) } func TestWebhook_UpdateEvent(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - webhook := db.AssertExistsAndLoadBean(t, &Webhook{ID: 1}).(*Webhook) + assert.NoError(t, unittest.PrepareTestDatabase()) + webhook := unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 1}).(*Webhook) hookEvent := &HookEvent{ PushOnly: true, SendEverything: false, @@ -91,35 +92,35 @@ func TestCreateWebhook(t *testing.T) { ContentType: ContentTypeJSON, Events: `{"push_only":false,"send_everything":false,"choose_events":false,"events":{"create":false,"push":true,"pull_request":true}}`, } - db.AssertNotExistsBean(t, hook) + unittest.AssertNotExistsBean(t, hook) assert.NoError(t, CreateWebhook(db.DefaultContext, hook)) - db.AssertExistsAndLoadBean(t, hook) + unittest.AssertExistsAndLoadBean(t, hook) } func TestGetWebhookByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hook, err := GetWebhookByRepoID(1, 1) assert.NoError(t, err) assert.Equal(t, int64(1), hook.ID) - _, err = GetWebhookByRepoID(db.NonexistentID, db.NonexistentID) + _, err = GetWebhookByRepoID(unittest.NonexistentID, unittest.NonexistentID) assert.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } func TestGetWebhookByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hook, err := GetWebhookByOrgID(3, 3) assert.NoError(t, err) assert.Equal(t, int64(3), hook.ID) - _, err = GetWebhookByOrgID(db.NonexistentID, db.NonexistentID) + _, err = GetWebhookByOrgID(unittest.NonexistentID, unittest.NonexistentID) assert.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } func TestGetActiveWebhooksByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hooks, err := ListWebhooksByOpts(&ListWebhookOptions{RepoID: 1, IsActive: util.OptionalBoolTrue}) assert.NoError(t, err) if assert.Len(t, hooks, 1) { @@ -129,7 +130,7 @@ func TestGetActiveWebhooksByRepoID(t *testing.T) { } func TestGetWebhooksByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hooks, err := ListWebhooksByOpts(&ListWebhookOptions{RepoID: 1}) assert.NoError(t, err) if assert.Len(t, hooks, 2) { @@ -139,7 +140,7 @@ func TestGetWebhooksByRepoID(t *testing.T) { } func TestGetActiveWebhooksByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hooks, err := ListWebhooksByOpts(&ListWebhookOptions{OrgID: 3, IsActive: util.OptionalBoolTrue}) assert.NoError(t, err) if assert.Len(t, hooks, 1) { @@ -149,7 +150,7 @@ func TestGetActiveWebhooksByOrgID(t *testing.T) { } func TestGetWebhooksByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hooks, err := ListWebhooksByOpts(&ListWebhookOptions{OrgID: 3}) assert.NoError(t, err) if assert.Len(t, hooks, 1) { @@ -159,76 +160,76 @@ func TestGetWebhooksByOrgID(t *testing.T) { } func TestUpdateWebhook(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - hook := db.AssertExistsAndLoadBean(t, &Webhook{ID: 2}).(*Webhook) + assert.NoError(t, unittest.PrepareTestDatabase()) + hook := unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 2}).(*Webhook) hook.IsActive = true hook.ContentType = ContentTypeForm - db.AssertNotExistsBean(t, hook) + unittest.AssertNotExistsBean(t, hook) assert.NoError(t, UpdateWebhook(hook)) - db.AssertExistsAndLoadBean(t, hook) + unittest.AssertExistsAndLoadBean(t, hook) } func TestDeleteWebhookByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - db.AssertExistsAndLoadBean(t, &Webhook{ID: 2, RepoID: 1}) + assert.NoError(t, unittest.PrepareTestDatabase()) + unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 2, RepoID: 1}) assert.NoError(t, DeleteWebhookByRepoID(1, 2)) - db.AssertNotExistsBean(t, &Webhook{ID: 2, RepoID: 1}) + unittest.AssertNotExistsBean(t, &Webhook{ID: 2, RepoID: 1}) - err := DeleteWebhookByRepoID(db.NonexistentID, db.NonexistentID) + err := DeleteWebhookByRepoID(unittest.NonexistentID, unittest.NonexistentID) assert.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } func TestDeleteWebhookByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - db.AssertExistsAndLoadBean(t, &Webhook{ID: 3, OrgID: 3}) + assert.NoError(t, unittest.PrepareTestDatabase()) + unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 3, OrgID: 3}) assert.NoError(t, DeleteWebhookByOrgID(3, 3)) - db.AssertNotExistsBean(t, &Webhook{ID: 3, OrgID: 3}) + unittest.AssertNotExistsBean(t, &Webhook{ID: 3, OrgID: 3}) - err := DeleteWebhookByOrgID(db.NonexistentID, db.NonexistentID) + err := DeleteWebhookByOrgID(unittest.NonexistentID, unittest.NonexistentID) assert.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } func TestHookTasks(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTasks, err := HookTasks(1, 1) assert.NoError(t, err) if assert.Len(t, hookTasks, 1) { assert.Equal(t, int64(1), hookTasks[0].ID) } - hookTasks, err = HookTasks(db.NonexistentID, 1) + hookTasks, err = HookTasks(unittest.NonexistentID, 1) assert.NoError(t, err) assert.Len(t, hookTasks, 0) } func TestCreateHookTask(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 3, HookID: 3, Payloader: &api.PushPayload{}, } - db.AssertNotExistsBean(t, hookTask) + unittest.AssertNotExistsBean(t, hookTask) assert.NoError(t, CreateHookTask(hookTask)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) } func TestUpdateHookTask(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - hook := db.AssertExistsAndLoadBean(t, &HookTask{ID: 1}).(*HookTask) + hook := unittest.AssertExistsAndLoadBean(t, &HookTask{ID: 1}).(*HookTask) hook.PayloadContent = "new payload content" hook.DeliveredString = "new delivered string" hook.IsDelivered = true - db.AssertNotExistsBean(t, hook) + unittest.AssertNotExistsBean(t, hook) assert.NoError(t, UpdateHookTask(hook)) - db.AssertExistsAndLoadBean(t, hook) + unittest.AssertExistsAndLoadBean(t, hook) } func TestCleanupHookTaskTable_PerWebhook_DeletesDelivered(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 3, HookID: 3, @@ -236,32 +237,32 @@ func TestCleanupHookTaskTable_PerWebhook_DeletesDelivered(t *testing.T) { IsDelivered: true, Delivered: time.Now().UnixNano(), } - db.AssertNotExistsBean(t, hookTask) + unittest.AssertNotExistsBean(t, hookTask) assert.NoError(t, CreateHookTask(hookTask)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) assert.NoError(t, CleanupHookTaskTable(context.Background(), PerWebhook, 168*time.Hour, 0)) - db.AssertNotExistsBean(t, hookTask) + unittest.AssertNotExistsBean(t, hookTask) } func TestCleanupHookTaskTable_PerWebhook_LeavesUndelivered(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 2, HookID: 4, Payloader: &api.PushPayload{}, IsDelivered: false, } - db.AssertNotExistsBean(t, hookTask) + unittest.AssertNotExistsBean(t, hookTask) assert.NoError(t, CreateHookTask(hookTask)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) assert.NoError(t, CleanupHookTaskTable(context.Background(), PerWebhook, 168*time.Hour, 0)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) } func TestCleanupHookTaskTable_PerWebhook_LeavesMostRecentTask(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 2, HookID: 4, @@ -269,16 +270,16 @@ func TestCleanupHookTaskTable_PerWebhook_LeavesMostRecentTask(t *testing.T) { IsDelivered: true, Delivered: time.Now().UnixNano(), } - db.AssertNotExistsBean(t, hookTask) + unittest.AssertNotExistsBean(t, hookTask) assert.NoError(t, CreateHookTask(hookTask)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) assert.NoError(t, CleanupHookTaskTable(context.Background(), PerWebhook, 168*time.Hour, 1)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) } func TestCleanupHookTaskTable_OlderThan_DeletesDelivered(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 3, HookID: 3, @@ -286,32 +287,32 @@ func TestCleanupHookTaskTable_OlderThan_DeletesDelivered(t *testing.T) { IsDelivered: true, Delivered: time.Now().AddDate(0, 0, -8).UnixNano(), } - db.AssertNotExistsBean(t, hookTask) + unittest.AssertNotExistsBean(t, hookTask) assert.NoError(t, CreateHookTask(hookTask)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) assert.NoError(t, CleanupHookTaskTable(context.Background(), OlderThan, 168*time.Hour, 0)) - db.AssertNotExistsBean(t, hookTask) + unittest.AssertNotExistsBean(t, hookTask) } func TestCleanupHookTaskTable_OlderThan_LeavesUndelivered(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 2, HookID: 4, Payloader: &api.PushPayload{}, IsDelivered: false, } - db.AssertNotExistsBean(t, hookTask) + unittest.AssertNotExistsBean(t, hookTask) assert.NoError(t, CreateHookTask(hookTask)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) assert.NoError(t, CleanupHookTaskTable(context.Background(), OlderThan, 168*time.Hour, 0)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) } func TestCleanupHookTaskTable_OlderThan_LeavesTaskEarlierThanAgeToDelete(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 2, HookID: 4, @@ -319,10 +320,10 @@ func TestCleanupHookTaskTable_OlderThan_LeavesTaskEarlierThanAgeToDelete(t *test IsDelivered: true, Delivered: time.Now().AddDate(0, 0, -6).UnixNano(), } - db.AssertNotExistsBean(t, hookTask) + unittest.AssertNotExistsBean(t, hookTask) assert.NoError(t, CreateHookTask(hookTask)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) assert.NoError(t, CleanupHookTaskTable(context.Background(), OlderThan, 168*time.Hour, 0)) - db.AssertExistsAndLoadBean(t, hookTask) + unittest.AssertExistsAndLoadBean(t, hookTask) } diff --git a/models/wiki_test.go b/models/wiki_test.go index f1435e8178a6..ae6b090db5ce 100644 --- a/models/wiki_test.go +++ b/models/wiki_test.go @@ -8,38 +8,38 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestRepository_WikiCloneLink(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) cloneLink := repo.WikiCloneLink() assert.Equal(t, "ssh://runuser@try.gitea.io:3000/user2/repo1.wiki.git", cloneLink.SSH) assert.Equal(t, "https://try.gitea.io/user2/repo1.wiki.git", cloneLink.HTTPS) } func TestWikiPath(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) expected := filepath.Join(setting.RepoRootPath, "user2/repo1.wiki.git") assert.Equal(t, expected, WikiPath("user2", "repo1")) } func TestRepository_WikiPath(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) expected := filepath.Join(setting.RepoRootPath, "user2/repo1.wiki.git") assert.Equal(t, expected, repo.WikiPath()) } func TestRepository_HasWiki(t *testing.T) { - db.PrepareTestEnv(t) - repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) + unittest.PrepareTestEnv(t) + repo1 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.True(t, repo1.HasWiki()) - repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) + repo2 := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) assert.False(t, repo2.HasWiki()) } diff --git a/modules/appstate/appstate_test.go b/modules/appstate/appstate_test.go index d8ab0a45fd80..15fbc829bae4 100644 --- a/modules/appstate/appstate_test.go +++ b/modules/appstate/appstate_test.go @@ -8,13 +8,13 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", ".."), "") + unittest.MainTest(m, filepath.Join("..", ".."), "") } type testItem1 struct { @@ -35,7 +35,7 @@ func (*testItem2) Name() string { } func TestAppStateDB(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) as := &DBStore{} diff --git a/modules/convert/git_commit_test.go b/modules/convert/git_commit_test.go index 298a006cb19e..aacdb1ad7c0a 100644 --- a/modules/convert/git_commit_test.go +++ b/modules/convert/git_commit_test.go @@ -9,7 +9,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" @@ -18,8 +18,8 @@ import ( ) func TestToCommitMeta(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - headRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + headRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) sha1, _ := git.NewIDFromString("0000000000000000000000000000000000000000") signature := &git.Signature{Name: "Test Signature", Email: "test@email.com", When: time.Unix(0, 0)} tag := &git.Tag{ diff --git a/modules/convert/issue_test.go b/modules/convert/issue_test.go index 7c6b05e816a5..21ca7469e1b3 100644 --- a/modules/convert/issue_test.go +++ b/modules/convert/issue_test.go @@ -10,7 +10,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/timeutil" @@ -19,9 +19,9 @@ import ( ) func TestLabel_ToLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - label := db.AssertExistsAndLoadBean(t, &models.Label{ID: 1}).(*models.Label) - repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: label.RepoID}).(*models.Repository) + assert.NoError(t, unittest.PrepareTestDatabase()) + label := unittest.AssertExistsAndLoadBean(t, &models.Label{ID: 1}).(*models.Label) + repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: label.RepoID}).(*models.Repository) assert.Equal(t, &api.Label{ ID: label.ID, Name: label.Name, diff --git a/modules/convert/main_test.go b/modules/convert/main_test.go index acb9802f97a0..307fd06197ce 100644 --- a/modules/convert/main_test.go +++ b/modules/convert/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } diff --git a/modules/convert/pull_test.go b/modules/convert/pull_test.go index a2b1e12a3718..844011b8ccbc 100644 --- a/modules/convert/pull_test.go +++ b/modules/convert/pull_test.go @@ -8,7 +8,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -16,9 +16,9 @@ import ( func TestPullRequest_APIFormat(t *testing.T) { //with HeadRepo - assert.NoError(t, db.PrepareTestDatabase()) - headRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) - pr := db.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) + assert.NoError(t, unittest.PrepareTestDatabase()) + headRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) + pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) assert.NoError(t, pr.LoadAttributes()) assert.NoError(t, pr.LoadIssue()) apiPullRequest := ToAPIPullRequest(pr, nil) @@ -32,7 +32,7 @@ func TestPullRequest_APIFormat(t *testing.T) { }, apiPullRequest.Head) //withOut HeadRepo - pr = db.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) + pr = unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) assert.NoError(t, pr.LoadIssue()) assert.NoError(t, pr.LoadAttributes()) // simulate fork deletion diff --git a/modules/convert/user_test.go b/modules/convert/user_test.go index acf918dd99cf..ce174e30766d 100644 --- a/modules/convert/user_test.go +++ b/modules/convert/user_test.go @@ -8,22 +8,22 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" ) func TestUser_ToUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) - user1 := db.AssertExistsAndLoadBean(t, &models.User{ID: 1, IsAdmin: true}).(*models.User) + user1 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1, IsAdmin: true}).(*models.User) apiUser := toUser(user1, true, true) assert.True(t, apiUser.IsAdmin) assert.Contains(t, apiUser.AvatarURL, "://") - user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2, IsAdmin: false}).(*models.User) + user2 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2, IsAdmin: false}).(*models.User) apiUser = toUser(user2, true, true) assert.False(t, apiUser.IsAdmin) @@ -32,7 +32,7 @@ func TestUser_ToUser(t *testing.T) { assert.False(t, apiUser.IsAdmin) assert.EqualValues(t, api.VisibleTypePublic.String(), apiUser.Visibility) - user31 := db.AssertExistsAndLoadBean(t, &models.User{ID: 31, IsAdmin: false, Visibility: api.VisibleTypePrivate}).(*models.User) + user31 := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 31, IsAdmin: false, Visibility: api.VisibleTypePrivate}).(*models.User) apiUser = toUser(user31, true, true) assert.False(t, apiUser.IsAdmin) diff --git a/modules/convert/utils.go b/modules/convert/utils.go index a0463d7b1006..52fbcf547f72 100644 --- a/modules/convert/utils.go +++ b/modules/convert/utils.go @@ -35,6 +35,8 @@ func ToGitServiceType(value string) structs.GitServiceType { return structs.GogsService case "onedev": return structs.OneDevService + case "gitbucket": + return structs.GitBucketService default: return structs.PlainGitService } diff --git a/modules/indexer/code/bleve.go b/modules/indexer/code/bleve.go index 8e5df34e60be..66b2602d3bf2 100644 --- a/modules/indexer/code/bleve.go +++ b/modules/indexer/code/bleve.go @@ -173,6 +173,10 @@ func NewBleveIndexer(indexDir string) (*BleveIndexer, bool, error) { indexDir: indexDir, } created, err := indexer.init() + if err != nil { + indexer.Close() + return nil, false, err + } return indexer, created, err } diff --git a/modules/indexer/code/bleve_test.go b/modules/indexer/code/bleve_test.go index 3d97e312f9aa..37ed2eb9f021 100644 --- a/modules/indexer/code/bleve_test.go +++ b/modules/indexer/code/bleve_test.go @@ -8,14 +8,14 @@ import ( "os" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" ) func TestBleveIndexAndSearch(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) dir, err := os.MkdirTemp("", "bleve.index") assert.NoError(t, err) diff --git a/modules/indexer/code/elastic_search.go b/modules/indexer/code/elastic_search.go index 49633c31916d..f76f316f6494 100644 --- a/modules/indexer/code/elastic_search.go +++ b/modules/indexer/code/elastic_search.go @@ -82,7 +82,10 @@ func NewElasticSearchIndexer(url, indexerName string) (*ElasticSearchIndexer, bo indexerAliasName: indexerName, } exists, err := indexer.init() - + if err != nil { + indexer.Close() + return nil, false, err + } return indexer, !exists, err } diff --git a/modules/indexer/code/elastic_search_test.go b/modules/indexer/code/elastic_search_test.go index c9d2c297bba4..fc58633f16e8 100644 --- a/modules/indexer/code/elastic_search_test.go +++ b/modules/indexer/code/elastic_search_test.go @@ -8,12 +8,13 @@ import ( "os" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestESIndexAndSearch(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) u := os.Getenv("TEST_INDEXER_CODE_ES_URL") if u == "" { diff --git a/modules/indexer/code/indexer.go b/modules/indexer/code/indexer.go index 981167a8254a..c56b1b2bb0c5 100644 --- a/modules/indexer/code/indexer.go +++ b/modules/indexer/code/indexer.go @@ -185,9 +185,6 @@ func Init() { rIndexer, populate, err = NewBleveIndexer(setting.Indexer.RepoPath) if err != nil { - if rIndexer != nil { - rIndexer.Close() - } cancel() indexer.Close() close(waitChannel) @@ -205,9 +202,6 @@ func Init() { rIndexer, populate, err = NewElasticSearchIndexer(setting.Indexer.RepoConnStr, setting.Indexer.RepoIndexerName) if err != nil { - if rIndexer != nil { - rIndexer.Close() - } cancel() indexer.Close() close(waitChannel) diff --git a/modules/indexer/code/indexer_test.go b/modules/indexer/code/indexer_test.go index 34930a84caff..b8fedcb3239e 100644 --- a/modules/indexer/code/indexer_test.go +++ b/modules/indexer/code/indexer_test.go @@ -8,12 +8,13 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } func testIndexer(name string, t *testing.T, indexer Indexer) { diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index 561f357f4da7..edfaddb648fe 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -11,7 +11,7 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" @@ -21,11 +21,11 @@ import ( ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } func TestBleveSearchIssues(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) setting.Cfg = ini.Empty() tmpIndexerDir, err := os.MkdirTemp("", "issues-indexer") @@ -74,7 +74,7 @@ func TestBleveSearchIssues(t *testing.T) { } func TestDBSearchIssues(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) setting.Indexer.IssueType = "db" InitIssueIndexer(true) diff --git a/modules/indexer/stats/indexer_test.go b/modules/indexer/stats/indexer_test.go index a4645b2083d9..c451e8023838 100644 --- a/modules/indexer/stats/indexer_test.go +++ b/modules/indexer/stats/indexer_test.go @@ -10,7 +10,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "gopkg.in/ini.v1" @@ -19,11 +19,11 @@ import ( ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } func TestRepoStatsIndex(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) setting.Cfg = ini.Empty() setting.NewQueueService() diff --git a/modules/markup/markdown/markdown.go b/modules/markup/markdown/markdown.go index 554ee0d4be8c..2574585573f4 100644 --- a/modules/markup/markdown/markdown.go +++ b/modules/markup/markdown/markdown.go @@ -107,25 +107,18 @@ func actualRender(ctx *markup.RenderContext, input io.Reader, output io.Writer) languageStr := string(language) - preClasses := []string{} + preClasses := []string{"code-block"} if languageStr == "mermaid" { preClasses = append(preClasses, "is-loading") } - if len(preClasses) > 0 { - _, err := w.WriteString(`
`)
-								if err != nil {
-									return
-								}
-							} else {
-								_, err := w.WriteString(`
`)
-								if err != nil {
-									return
-								}
+							_, err := w.WriteString(`
`)
+							if err != nil {
+								return
 							}
 
 							// include language-x class as part of commonmark spec
-							_, err := w.WriteString(``)
+							_, err = w.WriteString(``)
 							if err != nil {
 								return
 							}
diff --git a/modules/markup/sanitizer.go b/modules/markup/sanitizer.go
index c8f9de33b5fb..5ff26a310942 100644
--- a/modules/markup/sanitizer.go
+++ b/modules/markup/sanitizer.go
@@ -52,8 +52,11 @@ func InitializeSanitizer() {
 
 func createDefaultPolicy() *bluemonday.Policy {
 	policy := bluemonday.UGCPolicy()
+
+	// For JS code copy and Mermaid loading state
+	policy.AllowAttrs("class").Matching(regexp.MustCompile(`^code-block( is-loading)?$`)).OnElements("pre")
+
 	// For Chroma markdown plugin
-	policy.AllowAttrs("class").Matching(regexp.MustCompile(`^is-loading$`)).OnElements("pre")
 	policy.AllowAttrs("class").Matching(regexp.MustCompile(`^(chroma )?language-[\w-]+$`)).OnElements("code")
 
 	// Checkboxes
diff --git a/modules/migrations/base/comment.go b/modules/migration/comment.go
similarity index 96%
rename from modules/migrations/base/comment.go
rename to modules/migration/comment.go
index 3c32e63b8293..234fea3e82a7 100644
--- a/modules/migrations/base/comment.go
+++ b/modules/migration/comment.go
@@ -3,7 +3,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import "time"
 
diff --git a/modules/migrations/base/downloader.go b/modules/migration/downloader.go
similarity index 98%
rename from modules/migrations/base/downloader.go
rename to modules/migration/downloader.go
index 3c581b869900..90e149fb1a40 100644
--- a/modules/migrations/base/downloader.go
+++ b/modules/migration/downloader.go
@@ -3,7 +3,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import (
 	"context"
diff --git a/modules/migrations/base/error.go b/modules/migration/error.go
similarity index 97%
rename from modules/migrations/base/error.go
rename to modules/migration/error.go
index 40ddcf4b75e9..b2608aa09fea 100644
--- a/modules/migrations/base/error.go
+++ b/modules/migration/error.go
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import "fmt"
 
diff --git a/modules/migrations/base/issue.go b/modules/migration/issue.go
similarity index 98%
rename from modules/migrations/base/issue.go
rename to modules/migration/issue.go
index 7addd1336a28..26812633f9be 100644
--- a/modules/migrations/base/issue.go
+++ b/modules/migration/issue.go
@@ -3,7 +3,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import "time"
 
diff --git a/modules/migrations/base/label.go b/modules/migration/label.go
similarity index 95%
rename from modules/migrations/base/label.go
rename to modules/migration/label.go
index 5a66e7620f62..1a04a1dd3a57 100644
--- a/modules/migrations/base/label.go
+++ b/modules/migration/label.go
@@ -3,7 +3,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 // Label defines a standard label information
 type Label struct {
diff --git a/modules/migrations/base/messenger.go b/modules/migration/messenger.go
similarity index 95%
rename from modules/migrations/base/messenger.go
rename to modules/migration/messenger.go
index a92f59ef7fae..fa8218cf938e 100644
--- a/modules/migrations/base/messenger.go
+++ b/modules/migration/messenger.go
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 // Messenger is a formatting function similar to i18n.Tr
 type Messenger func(key string, args ...interface{})
diff --git a/modules/migrations/base/milestone.go b/modules/migration/milestone.go
similarity index 96%
rename from modules/migrations/base/milestone.go
rename to modules/migration/milestone.go
index 921968fcb5b9..209aafe6a732 100644
--- a/modules/migrations/base/milestone.go
+++ b/modules/migration/milestone.go
@@ -3,7 +3,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import "time"
 
diff --git a/modules/migrations/base/null_downloader.go b/modules/migration/null_downloader.go
similarity index 99%
rename from modules/migrations/base/null_downloader.go
rename to modules/migration/null_downloader.go
index c64d0e263379..05daf721089a 100644
--- a/modules/migrations/base/null_downloader.go
+++ b/modules/migration/null_downloader.go
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import (
 	"context"
diff --git a/modules/migrations/base/options.go b/modules/migration/options.go
similarity index 98%
rename from modules/migrations/base/options.go
rename to modules/migration/options.go
index b12e1f94aa4a..1e92a1b0b35f 100644
--- a/modules/migrations/base/options.go
+++ b/modules/migration/options.go
@@ -3,7 +3,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import "code.gitea.io/gitea/modules/structs"
 
diff --git a/modules/migrations/base/pullrequest.go b/modules/migration/pullrequest.go
similarity index 99%
rename from modules/migrations/base/pullrequest.go
rename to modules/migration/pullrequest.go
index b51a14e47c52..9ca9a70b7d88 100644
--- a/modules/migrations/base/pullrequest.go
+++ b/modules/migration/pullrequest.go
@@ -3,7 +3,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import (
 	"fmt"
diff --git a/modules/migrations/base/reaction.go b/modules/migration/reaction.go
similarity index 94%
rename from modules/migrations/base/reaction.go
rename to modules/migration/reaction.go
index 151949913475..004cff2f94f4 100644
--- a/modules/migrations/base/reaction.go
+++ b/modules/migration/reaction.go
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 // Reaction represents a reaction to an issue/pr/comment.
 type Reaction struct {
diff --git a/modules/migrations/base/release.go b/modules/migration/release.go
similarity index 98%
rename from modules/migrations/base/release.go
rename to modules/migration/release.go
index 8b4339928bf6..a83f5502cb95 100644
--- a/modules/migrations/base/release.go
+++ b/modules/migration/release.go
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import (
 	"io"
diff --git a/modules/migrations/base/repo.go b/modules/migration/repo.go
similarity index 96%
rename from modules/migrations/base/repo.go
rename to modules/migration/repo.go
index 693a96314dc1..d0d62de8da9c 100644
--- a/modules/migrations/base/repo.go
+++ b/modules/migration/repo.go
@@ -3,7 +3,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 // Repository defines a standard repository information
 type Repository struct {
diff --git a/modules/migrations/base/retry_downloader.go b/modules/migration/retry_downloader.go
similarity index 99%
rename from modules/migrations/base/retry_downloader.go
rename to modules/migration/retry_downloader.go
index 623bfc86b526..1f034ab0c765 100644
--- a/modules/migrations/base/retry_downloader.go
+++ b/modules/migration/retry_downloader.go
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import (
 	"context"
diff --git a/modules/migrations/base/review.go b/modules/migration/review.go
similarity index 98%
rename from modules/migrations/base/review.go
rename to modules/migration/review.go
index 6344f0384d64..d6d15002af36 100644
--- a/modules/migrations/base/review.go
+++ b/modules/migration/review.go
@@ -2,7 +2,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 import "time"
 
diff --git a/modules/migrations/base/uploader.go b/modules/migration/uploader.go
similarity index 97%
rename from modules/migrations/base/uploader.go
rename to modules/migration/uploader.go
index 4d0257df37b0..57571861aaad 100644
--- a/modules/migrations/base/uploader.go
+++ b/modules/migration/uploader.go
@@ -3,7 +3,7 @@
 // Use of this source code is governed by a MIT-style
 // license that can be found in the LICENSE file.
 
-package base
+package migration
 
 // Uploader uploads all the information of one repository
 type Uploader interface {
diff --git a/modules/notification/action/action_test.go b/modules/notification/action/action_test.go
index 705a4fb2f49a..3adcae83fdaa 100644
--- a/modules/notification/action/action_test.go
+++ b/modules/notification/action/action_test.go
@@ -10,19 +10,19 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"github.com/stretchr/testify/assert"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", "..", ".."))
+	unittest.MainTest(m, filepath.Join("..", "..", ".."))
 }
 
 func TestRenameRepoAction(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{OwnerID: user.ID}).(*models.Repository)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{OwnerID: user.ID}).(*models.Repository)
 	repo.Owner = user
 
 	oldRepoName := repo.Name
@@ -39,10 +39,10 @@ func TestRenameRepoAction(t *testing.T) {
 		IsPrivate: repo.IsPrivate,
 		Content:   oldRepoName,
 	}
-	db.AssertNotExistsBean(t, actionBean)
+	unittest.AssertNotExistsBean(t, actionBean)
 
 	NewNotifier().NotifyRenameRepository(user, repo, oldRepoName)
 
-	db.AssertExistsAndLoadBean(t, actionBean)
-	models.CheckConsistencyFor(t, &models.Action{})
+	unittest.AssertExistsAndLoadBean(t, actionBean)
+	unittest.CheckConsistencyFor(t, &models.Action{})
 }
diff --git a/modules/repofiles/action_test.go b/modules/repofiles/action_test.go
index c29cfd686d42..d320413dbbc4 100644
--- a/modules/repofiles/action_test.go
+++ b/modules/repofiles/action_test.go
@@ -8,7 +8,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/setting"
 
@@ -16,7 +16,7 @@ import (
 )
 
 func TestUpdateIssuesCommit(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 	pushCommits := []*repository.PushCommit{
 		{
 			Sha1:           "abcdef1",
@@ -44,8 +44,8 @@ func TestUpdateIssuesCommit(t *testing.T) {
 		},
 	}
 
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	repo.Owner = user
 
 	commentBean := &models.Comment{
@@ -56,12 +56,12 @@ func TestUpdateIssuesCommit(t *testing.T) {
 	}
 	issueBean := &models.Issue{RepoID: repo.ID, Index: 4}
 
-	db.AssertNotExistsBean(t, commentBean)
-	db.AssertNotExistsBean(t, &models.Issue{RepoID: repo.ID, Index: 2}, "is_closed=1")
+	unittest.AssertNotExistsBean(t, commentBean)
+	unittest.AssertNotExistsBean(t, &models.Issue{RepoID: repo.ID, Index: 2}, "is_closed=1")
 	assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch))
-	db.AssertExistsAndLoadBean(t, commentBean)
-	db.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
-	models.CheckConsistencyFor(t, &models.Action{})
+	unittest.AssertExistsAndLoadBean(t, commentBean)
+	unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
+	unittest.CheckConsistencyFor(t, &models.Action{})
 
 	// Test that push to a non-default branch closes no issue.
 	pushCommits = []*repository.PushCommit{
@@ -74,7 +74,7 @@ func TestUpdateIssuesCommit(t *testing.T) {
 			Message:        "close #1",
 		},
 	}
-	repo = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
+	repo = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
 	commentBean = &models.Comment{
 		Type:      models.CommentTypeCommitRef,
 		CommitSHA: "abcdef1",
@@ -83,12 +83,12 @@ func TestUpdateIssuesCommit(t *testing.T) {
 	}
 	issueBean = &models.Issue{RepoID: repo.ID, Index: 1}
 
-	db.AssertNotExistsBean(t, commentBean)
-	db.AssertNotExistsBean(t, &models.Issue{RepoID: repo.ID, Index: 1}, "is_closed=1")
+	unittest.AssertNotExistsBean(t, commentBean)
+	unittest.AssertNotExistsBean(t, &models.Issue{RepoID: repo.ID, Index: 1}, "is_closed=1")
 	assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, "non-existing-branch"))
-	db.AssertExistsAndLoadBean(t, commentBean)
-	db.AssertNotExistsBean(t, issueBean, "is_closed=1")
-	models.CheckConsistencyFor(t, &models.Action{})
+	unittest.AssertExistsAndLoadBean(t, commentBean)
+	unittest.AssertNotExistsBean(t, issueBean, "is_closed=1")
+	unittest.CheckConsistencyFor(t, &models.Action{})
 
 	pushCommits = []*repository.PushCommit{
 		{
@@ -100,7 +100,7 @@ func TestUpdateIssuesCommit(t *testing.T) {
 			Message:        "close " + setting.AppURL + repo.FullName() + "/pulls/1",
 		},
 	}
-	repo = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
+	repo = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
 	commentBean = &models.Comment{
 		Type:      models.CommentTypeCommitRef,
 		CommitSHA: "abcdef3",
@@ -109,16 +109,16 @@ func TestUpdateIssuesCommit(t *testing.T) {
 	}
 	issueBean = &models.Issue{RepoID: repo.ID, Index: 1}
 
-	db.AssertNotExistsBean(t, commentBean)
-	db.AssertNotExistsBean(t, &models.Issue{RepoID: repo.ID, Index: 1}, "is_closed=1")
+	unittest.AssertNotExistsBean(t, commentBean)
+	unittest.AssertNotExistsBean(t, &models.Issue{RepoID: repo.ID, Index: 1}, "is_closed=1")
 	assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch))
-	db.AssertExistsAndLoadBean(t, commentBean)
-	db.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
-	models.CheckConsistencyFor(t, &models.Action{})
+	unittest.AssertExistsAndLoadBean(t, commentBean)
+	unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
+	unittest.CheckConsistencyFor(t, &models.Action{})
 }
 
 func TestUpdateIssuesCommit_Colon(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 	pushCommits := []*repository.PushCommit{
 		{
 			Sha1:           "abcdef2",
@@ -130,21 +130,21 @@ func TestUpdateIssuesCommit_Colon(t *testing.T) {
 		},
 	}
 
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	repo.Owner = user
 
 	issueBean := &models.Issue{RepoID: repo.ID, Index: 4}
 
-	db.AssertNotExistsBean(t, &models.Issue{RepoID: repo.ID, Index: 2}, "is_closed=1")
+	unittest.AssertNotExistsBean(t, &models.Issue{RepoID: repo.ID, Index: 2}, "is_closed=1")
 	assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch))
-	db.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
-	models.CheckConsistencyFor(t, &models.Action{})
+	unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
+	unittest.CheckConsistencyFor(t, &models.Action{})
 }
 
 func TestUpdateIssuesCommit_Issue5957(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	assert.NoError(t, unittest.PrepareTestDatabase())
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 
 	// Test that push to a non-default branch closes an issue.
 	pushCommits := []*repository.PushCommit{
@@ -158,7 +158,7 @@ func TestUpdateIssuesCommit_Issue5957(t *testing.T) {
 		},
 	}
 
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
 	commentBean := &models.Comment{
 		Type:      models.CommentTypeCommitRef,
 		CommitSHA: "abcdef1",
@@ -168,17 +168,17 @@ func TestUpdateIssuesCommit_Issue5957(t *testing.T) {
 
 	issueBean := &models.Issue{RepoID: repo.ID, Index: 2, ID: 7}
 
-	db.AssertNotExistsBean(t, commentBean)
-	db.AssertNotExistsBean(t, issueBean, "is_closed=1")
+	unittest.AssertNotExistsBean(t, commentBean)
+	unittest.AssertNotExistsBean(t, issueBean, "is_closed=1")
 	assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, "non-existing-branch"))
-	db.AssertExistsAndLoadBean(t, commentBean)
-	db.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
-	models.CheckConsistencyFor(t, &models.Action{})
+	unittest.AssertExistsAndLoadBean(t, commentBean)
+	unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
+	unittest.CheckConsistencyFor(t, &models.Action{})
 }
 
 func TestUpdateIssuesCommit_AnotherRepo(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	assert.NoError(t, unittest.PrepareTestDatabase())
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 
 	// Test that a push to default branch closes issue in another repo
 	// If the user also has push permissions to that repo
@@ -193,7 +193,7 @@ func TestUpdateIssuesCommit_AnotherRepo(t *testing.T) {
 		},
 	}
 
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
 	commentBean := &models.Comment{
 		Type:      models.CommentTypeCommitRef,
 		CommitSHA: "abcdef1",
@@ -203,17 +203,17 @@ func TestUpdateIssuesCommit_AnotherRepo(t *testing.T) {
 
 	issueBean := &models.Issue{RepoID: 1, Index: 1, ID: 1}
 
-	db.AssertNotExistsBean(t, commentBean)
-	db.AssertNotExistsBean(t, issueBean, "is_closed=1")
+	unittest.AssertNotExistsBean(t, commentBean)
+	unittest.AssertNotExistsBean(t, issueBean, "is_closed=1")
 	assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch))
-	db.AssertExistsAndLoadBean(t, commentBean)
-	db.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
-	models.CheckConsistencyFor(t, &models.Action{})
+	unittest.AssertExistsAndLoadBean(t, commentBean)
+	unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
+	unittest.CheckConsistencyFor(t, &models.Action{})
 }
 
 func TestUpdateIssuesCommit_AnotherRepo_FullAddress(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	assert.NoError(t, unittest.PrepareTestDatabase())
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 
 	// Test that a push to default branch closes issue in another repo
 	// If the user also has push permissions to that repo
@@ -228,7 +228,7 @@ func TestUpdateIssuesCommit_AnotherRepo_FullAddress(t *testing.T) {
 		},
 	}
 
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
 	commentBean := &models.Comment{
 		Type:      models.CommentTypeCommitRef,
 		CommitSHA: "abcdef1",
@@ -238,17 +238,17 @@ func TestUpdateIssuesCommit_AnotherRepo_FullAddress(t *testing.T) {
 
 	issueBean := &models.Issue{RepoID: 1, Index: 1, ID: 1}
 
-	db.AssertNotExistsBean(t, commentBean)
-	db.AssertNotExistsBean(t, issueBean, "is_closed=1")
+	unittest.AssertNotExistsBean(t, commentBean)
+	unittest.AssertNotExistsBean(t, issueBean, "is_closed=1")
 	assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch))
-	db.AssertExistsAndLoadBean(t, commentBean)
-	db.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
-	models.CheckConsistencyFor(t, &models.Action{})
+	unittest.AssertExistsAndLoadBean(t, commentBean)
+	unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1")
+	unittest.CheckConsistencyFor(t, &models.Action{})
 }
 
 func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 10}).(*models.User)
+	assert.NoError(t, unittest.PrepareTestDatabase())
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 10}).(*models.User)
 
 	// Test that a push with close reference *can not* close issue
 	// If the committer doesn't have push rights in that repo
@@ -271,7 +271,7 @@ func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) {
 		},
 	}
 
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 6}).(*models.Repository)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 6}).(*models.Repository)
 	commentBean := &models.Comment{
 		Type:      models.CommentTypeCommitRef,
 		CommitSHA: "abcdef3",
@@ -287,12 +287,12 @@ func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) {
 
 	issueBean := &models.Issue{RepoID: 3, Index: 1, ID: 6}
 
-	db.AssertNotExistsBean(t, commentBean)
-	db.AssertNotExistsBean(t, commentBean2)
-	db.AssertNotExistsBean(t, issueBean, "is_closed=1")
+	unittest.AssertNotExistsBean(t, commentBean)
+	unittest.AssertNotExistsBean(t, commentBean2)
+	unittest.AssertNotExistsBean(t, issueBean, "is_closed=1")
 	assert.NoError(t, UpdateIssuesCommit(user, repo, pushCommits, repo.DefaultBranch))
-	db.AssertNotExistsBean(t, commentBean)
-	db.AssertNotExistsBean(t, commentBean2)
-	db.AssertNotExistsBean(t, issueBean, "is_closed=1")
-	models.CheckConsistencyFor(t, &models.Action{})
+	unittest.AssertNotExistsBean(t, commentBean)
+	unittest.AssertNotExistsBean(t, commentBean2)
+	unittest.AssertNotExistsBean(t, issueBean, "is_closed=1")
+	unittest.CheckConsistencyFor(t, &models.Action{})
 }
diff --git a/modules/repofiles/blob_test.go b/modules/repofiles/blob_test.go
index 5238dd6e74f4..c219892aec8e 100644
--- a/modules/repofiles/blob_test.go
+++ b/modules/repofiles/blob_test.go
@@ -7,7 +7,8 @@ package repofiles
 import (
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
+
 	api "code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/modules/test"
 
@@ -15,7 +16,7 @@ import (
 )
 
 func TestGetBlobBySHA(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	test.LoadRepo(t, ctx, 1)
 	test.LoadRepoCommit(t, ctx)
diff --git a/modules/repofiles/content_test.go b/modules/repofiles/content_test.go
index f68460d7ec3f..e3230698bcec 100644
--- a/modules/repofiles/content_test.go
+++ b/modules/repofiles/content_test.go
@@ -8,7 +8,8 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
+
 	api "code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/modules/test"
 
@@ -16,7 +17,7 @@ import (
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
 
 func getExpectedReadmeContentsResponse() *api.ContentsResponse {
@@ -49,7 +50,7 @@ func getExpectedReadmeContentsResponse() *api.ContentsResponse {
 }
 
 func TestGetContents(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	ctx.SetParams(":id", "1")
 	test.LoadRepo(t, ctx, 1)
@@ -77,7 +78,7 @@ func TestGetContents(t *testing.T) {
 }
 
 func TestGetContentsOrListForDir(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	ctx.SetParams(":id", "1")
 	test.LoadRepo(t, ctx, 1)
@@ -112,7 +113,7 @@ func TestGetContentsOrListForDir(t *testing.T) {
 }
 
 func TestGetContentsOrListForFile(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	ctx.SetParams(":id", "1")
 	test.LoadRepo(t, ctx, 1)
@@ -140,7 +141,7 @@ func TestGetContentsOrListForFile(t *testing.T) {
 }
 
 func TestGetContentsErrors(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	ctx.SetParams(":id", "1")
 	test.LoadRepo(t, ctx, 1)
@@ -171,7 +172,7 @@ func TestGetContentsErrors(t *testing.T) {
 }
 
 func TestGetContentsOrListErrors(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	ctx.SetParams(":id", "1")
 	test.LoadRepo(t, ctx, 1)
@@ -202,7 +203,7 @@ func TestGetContentsOrListErrors(t *testing.T) {
 }
 
 func TestGetContentsOrListOfEmptyRepos(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo15")
 	ctx.SetParams(":id", "15")
 	test.LoadRepo(t, ctx, 15)
diff --git a/modules/repofiles/diff_test.go b/modules/repofiles/diff_test.go
index aeb4f76a4576..463ce4ec6744 100644
--- a/modules/repofiles/diff_test.go
+++ b/modules/repofiles/diff_test.go
@@ -8,7 +8,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/test"
 	"code.gitea.io/gitea/services/gitdiff"
 
@@ -16,7 +16,7 @@ import (
 )
 
 func TestGetDiffPreview(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	ctx.SetParams(":id", "1")
 	test.LoadRepo(t, ctx, 1)
@@ -129,7 +129,7 @@ func TestGetDiffPreview(t *testing.T) {
 }
 
 func TestGetDiffPreviewErrors(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	ctx.SetParams(":id", "1")
 	test.LoadRepo(t, ctx, 1)
diff --git a/modules/repofiles/file_test.go b/modules/repofiles/file_test.go
index 2974056549e3..54205a89c7e6 100644
--- a/modules/repofiles/file_test.go
+++ b/modules/repofiles/file_test.go
@@ -7,7 +7,7 @@ package repofiles
 import (
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/setting"
 	api "code.gitea.io/gitea/modules/structs"
@@ -81,7 +81,7 @@ func getExpectedFileResponse() *api.FileResponse {
 }
 
 func TestGetFileResponseFromCommit(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	ctx.SetParams(":id", "1")
 	test.LoadRepo(t, ctx, 1)
diff --git a/modules/repofiles/tree_test.go b/modules/repofiles/tree_test.go
index 9e2efa4216fa..512313c43b36 100644
--- a/modules/repofiles/tree_test.go
+++ b/modules/repofiles/tree_test.go
@@ -7,7 +7,8 @@ package repofiles
 import (
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
+
 	api "code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/modules/test"
 
@@ -15,7 +16,7 @@ import (
 )
 
 func TestGetTreeBySHA(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	test.LoadRepo(t, ctx, 1)
 	test.LoadRepoCommit(t, ctx)
diff --git a/modules/repository/commits_test.go b/modules/repository/commits_test.go
index c62ad584496d..0d6c2e4c5ce6 100644
--- a/modules/repository/commits_test.go
+++ b/modules/repository/commits_test.go
@@ -11,13 +11,13 @@ import (
 	"time"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/git"
 	"github.com/stretchr/testify/assert"
 )
 
 func TestPushCommits_ToAPIPayloadCommits(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
 	pushCommits := NewPushCommits()
 	pushCommits.Commits = []*PushCommit{
@@ -48,7 +48,7 @@ func TestPushCommits_ToAPIPayloadCommits(t *testing.T) {
 	}
 	pushCommits.HeadCommit = &PushCommit{Sha1: "69554a6"}
 
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository)
 	payloadCommits, headCommit, err := pushCommits.ToAPIPayloadCommits(repo.RepoPath(), "/user2/repo16")
 	assert.NoError(t, err)
 	assert.Len(t, payloadCommits, 3)
@@ -100,7 +100,7 @@ func TestPushCommits_ToAPIPayloadCommits(t *testing.T) {
 }
 
 func TestPushCommits_AvatarLink(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
 	pushCommits := NewPushCommits()
 	pushCommits.Commits = []*PushCommit{
diff --git a/modules/repository/create_test.go b/modules/repository/create_test.go
index 040c061d9209..2e27ab0d7d71 100644
--- a/modules/repository/create_test.go
+++ b/modules/repository/create_test.go
@@ -9,17 +9,17 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/structs"
 
 	"github.com/stretchr/testify/assert"
 )
 
 func TestIncludesAllRepositoriesTeams(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
 	testTeamRepositories := func(teamID int64, repoIds []int64) {
-		team := db.AssertExistsAndLoadBean(t, &models.Team{ID: teamID}).(*models.Team)
+		team := unittest.AssertExistsAndLoadBean(t, &models.Team{ID: teamID}).(*models.Team)
 		assert.NoError(t, team.GetRepositories(&models.SearchTeamOptions{}), "%s: GetRepositories", team.Name)
 		assert.Len(t, team.Repos, team.NumRepos, "%s: len repo", team.Name)
 		assert.Len(t, team.Repos, len(repoIds), "%s: repo count", team.Name)
diff --git a/modules/repository/init.go b/modules/repository/init.go
index 5a1ff7e98bc6..076dbf748e68 100644
--- a/modules/repository/init.go
+++ b/modules/repository/init.go
@@ -196,92 +196,6 @@ func checkInitRepository(owner, name string) (err error) {
 	return nil
 }
 
-func adoptRepository(ctx context.Context, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) {
-	isExist, err := util.IsExist(repoPath)
-	if err != nil {
-		log.Error("Unable to check if %s exists. Error: %v", repoPath, err)
-		return err
-	}
-	if !isExist {
-		return fmt.Errorf("adoptRepository: path does not already exist: %s", repoPath)
-	}
-
-	if err := createDelegateHooks(repoPath); err != nil {
-		return fmt.Errorf("createDelegateHooks: %v", err)
-	}
-
-	// Re-fetch the repository from database before updating it (else it would
-	// override changes that were done earlier with sql)
-	if repo, err = models.GetRepositoryByIDCtx(ctx, repo.ID); err != nil {
-		return fmt.Errorf("getRepositoryByID: %v", err)
-	}
-
-	repo.IsEmpty = false
-	gitRepo, err := git.OpenRepository(repo.RepoPath())
-	if err != nil {
-		return fmt.Errorf("openRepository: %v", err)
-	}
-	defer gitRepo.Close()
-	if len(opts.DefaultBranch) > 0 {
-		repo.DefaultBranch = opts.DefaultBranch
-
-		if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
-			return fmt.Errorf("setDefaultBranch: %v", err)
-		}
-	} else {
-		repo.DefaultBranch, err = gitRepo.GetDefaultBranch()
-		if err != nil {
-			repo.DefaultBranch = setting.Repository.DefaultBranch
-			if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
-				return fmt.Errorf("setDefaultBranch: %v", err)
-			}
-		}
-
-		repo.DefaultBranch = strings.TrimPrefix(repo.DefaultBranch, git.BranchPrefix)
-	}
-	branches, _, _ := gitRepo.GetBranches(0, 0)
-	found := false
-	hasDefault := false
-	hasMaster := false
-	hasMain := false
-	for _, branch := range branches {
-		if branch == repo.DefaultBranch {
-			found = true
-			break
-		} else if branch == setting.Repository.DefaultBranch {
-			hasDefault = true
-		} else if branch == "master" {
-			hasMaster = true
-		} else if branch == "main" {
-			hasMain = true
-		}
-	}
-	if !found {
-		if hasDefault {
-			repo.DefaultBranch = setting.Repository.DefaultBranch
-		} else if hasMaster {
-			repo.DefaultBranch = "master"
-		} else if hasMain {
-			repo.DefaultBranch = "main"
-		} else if len(branches) > 0 {
-			repo.DefaultBranch = branches[0]
-		} else {
-			repo.IsEmpty = true
-			repo.DefaultBranch = setting.Repository.DefaultBranch
-		}
-
-		if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
-			return fmt.Errorf("setDefaultBranch: %v", err)
-		}
-	}
-
-	if err = models.UpdateRepositoryCtx(ctx, repo, false); err != nil {
-		return fmt.Errorf("updateRepository: %v", err)
-	}
-
-	return nil
-}
-
 // InitRepository initializes README and .gitignore if needed.
 func initRepository(ctx context.Context, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) {
 	if err = checkInitRepository(repo.OwnerName, repo.Name); err != nil {
diff --git a/modules/repository/main_test.go b/modules/repository/main_test.go
index 91d0d36ca026..262d3394818b 100644
--- a/modules/repository/main_test.go
+++ b/modules/repository/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
diff --git a/modules/repository/repo.go b/modules/repository/repo.go
index 05306218de8b..871ba617ad20 100644
--- a/modules/repository/repo.go
+++ b/modules/repository/repo.go
@@ -18,7 +18,7 @@ import (
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/lfs"
 	"code.gitea.io/gitea/modules/log"
-	migration "code.gitea.io/gitea/modules/migrations/base"
+	"code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/timeutil"
 	"code.gitea.io/gitea/modules/util"
diff --git a/modules/structs/repo.go b/modules/structs/repo.go
index 313a982f43d6..8482a2128d7f 100644
--- a/modules/structs/repo.go
+++ b/modules/structs/repo.go
@@ -242,13 +242,14 @@ type GitServiceType int
 
 // enumerate all GitServiceType
 const (
-	NotMigrated     GitServiceType = iota // 0 not migrated from external sites
-	PlainGitService                       // 1 plain git service
-	GithubService                         // 2 github.com
-	GiteaService                          // 3 gitea service
-	GitlabService                         // 4 gitlab service
-	GogsService                           // 5 gogs service
-	OneDevService                         // 6 onedev service
+	NotMigrated      GitServiceType = iota // 0 not migrated from external sites
+	PlainGitService                        // 1 plain git service
+	GithubService                          // 2 github.com
+	GiteaService                           // 3 gitea service
+	GitlabService                          // 4 gitlab service
+	GogsService                            // 5 gogs service
+	OneDevService                          // 6 onedev service
+	GitBucketService                       // 7 gitbucket service
 )
 
 // Name represents the service type's name
@@ -270,6 +271,8 @@ func (gt GitServiceType) Title() string {
 		return "Gogs"
 	case OneDevService:
 		return "OneDev"
+	case GitBucketService:
+		return "GitBucket"
 	case PlainGitService:
 		return "Git"
 	}
@@ -326,5 +329,6 @@ var (
 		GiteaService,
 		GogsService,
 		OneDevService,
+		GitBucketService,
 	}
 )
diff --git a/modules/task/migrate.go b/modules/task/migrate.go
index 52f4bb91cf72..100aac1967e3 100644
--- a/modules/task/migrate.go
+++ b/modules/task/migrate.go
@@ -14,13 +14,13 @@ import (
 	"code.gitea.io/gitea/modules/graceful"
 	"code.gitea.io/gitea/modules/json"
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations"
-	migration "code.gitea.io/gitea/modules/migrations/base"
+	"code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/notification"
 	"code.gitea.io/gitea/modules/process"
 	"code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/modules/timeutil"
 	"code.gitea.io/gitea/modules/util"
+	"code.gitea.io/gitea/services/migrations"
 )
 
 func handleCreateError(owner *models.User, err error) error {
@@ -58,6 +58,9 @@ func runMigrateTask(t *models.Task) (err error) {
 		t.EndTime = timeutil.TimeStampNow()
 		t.Status = structs.TaskStatusFailed
 		t.Message = err.Error()
+		// Ensure that the repo loaded before we zero out the repo ID from the task - thus ensuring that we can delete it
+		_ = t.LoadRepo()
+
 		t.RepoID = 0
 		if err := t.UpdateCols("status", "errors", "repo_id", "end_time"); err != nil {
 			log.Error("Task UpdateCols failed: %v", err)
diff --git a/modules/task/task.go b/modules/task/task.go
index 4e782869f93f..f538b36efc06 100644
--- a/modules/task/task.go
+++ b/modules/task/task.go
@@ -11,7 +11,7 @@ import (
 	"code.gitea.io/gitea/modules/graceful"
 	"code.gitea.io/gitea/modules/json"
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/queue"
 	repo_module "code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/secret"
@@ -90,7 +90,7 @@ func CreateMigrateTask(doer, u *models.User, opts base.MigrateOptions) (*models.
 		return nil, err
 	}
 
-	var task = models.Task{
+	var task = &models.Task{
 		DoerID:         doer.ID,
 		OwnerID:        u.ID,
 		Type:           structs.TaskTypeMigrateRepo,
@@ -98,7 +98,7 @@ func CreateMigrateTask(doer, u *models.User, opts base.MigrateOptions) (*models.
 		PayloadContent: string(bs),
 	}
 
-	if err := models.CreateTask(&task); err != nil {
+	if err := models.CreateTask(task); err != nil {
 		return nil, err
 	}
 
@@ -126,5 +126,5 @@ func CreateMigrateTask(doer, u *models.User, opts base.MigrateOptions) (*models.
 		return nil, err
 	}
 
-	return &task, nil
+	return task, nil
 }
diff --git a/modules/test/context_tests.go b/modules/test/context_tests.go
index 02723d8c3814..eb1a54d86f88 100644
--- a/modules/test/context_tests.go
+++ b/modules/test/context_tests.go
@@ -14,7 +14,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/context"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/web/middleware"
@@ -53,7 +53,7 @@ func MockContext(t *testing.T, path string) *context.Context {
 // LoadRepo load a repo into a test context.
 func LoadRepo(t *testing.T, ctx *context.Context, repoID int64) {
 	ctx.Repo = &context.Repository{}
-	ctx.Repo.Repository = db.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.Repository)
+	ctx.Repo.Repository = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.Repository)
 	var err error
 	ctx.Repo.Owner, err = models.GetUserByID(ctx.Repo.Repository.OwnerID)
 	assert.NoError(t, err)
@@ -78,7 +78,7 @@ func LoadRepoCommit(t *testing.T, ctx *context.Context) {
 
 // LoadUser load a user into a test context.
 func LoadUser(t *testing.T, ctx *context.Context, userID int64) {
-	ctx.User = db.AssertExistsAndLoadBean(t, &models.User{ID: userID}).(*models.User)
+	ctx.User = unittest.AssertExistsAndLoadBean(t, &models.User{ID: userID}).(*models.User)
 }
 
 // LoadGitRepo load a git repo into a test context. Requires that ctx.Repo has
diff --git a/options/license/BSD-1-Clause b/options/license/BSD-1-Clause
index 8f8d606c656f..4005b63def76 100644
--- a/options/license/BSD-1-Clause
+++ b/options/license/BSD-1-Clause
@@ -1,20 +1,7 @@
-Copyright (c) [Year]
-[Name of Organization]. All rights reserved.
+Copyright (c)  . All rights reserved.
 
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions
-are met:
-1. Redistributions of source code must retain the above copyright
-   notice, this list of conditions and the following disclaimer.
+Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 
-THIS SOFTWARE IS PROVIDED BY [Name of Organization] ``AS IS'' AND
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-ARE DISCLAIMED.  IN NO EVENT SHALL [Name of Organization] BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
-OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
-HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
-LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
-OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGE.
+1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/options/license/COIL-1.0 b/options/license/COIL-1.0
new file mode 100644
index 000000000000..c24c539e3184
--- /dev/null
+++ b/options/license/COIL-1.0
@@ -0,0 +1,30 @@
+# Copyfree Open Innovation License
+
+This is version 1.0 of the Copyfree Open Innovation License.
+
+## Terms and Conditions
+
+Redistributions, modified or unmodified, in whole or in part, must retain
+applicable notices of copyright or other legal privilege, these conditions, and
+the following license terms and disclaimer.  Subject to these conditions, each
+holder of copyright or other legal privileges, author or assembler, and
+contributor of this work, henceforth "licensor", hereby grants to any person
+who obtains a copy of this work in any form:
+
+1. Permission to reproduce, modify, distribute, publish, sell, sublicense, use,
+and/or otherwise deal in the licensed material without restriction.
+
+2. A perpetual, worldwide, non-exclusive, royalty-free, gratis, irrevocable
+patent license to make, have made, provide, transfer, import, use, and/or
+otherwise deal in the licensed material without restriction, for any and all
+patents held by such licensor and necessarily infringed by the form of the work
+upon distribution of that licensor's contribution to the work under the terms
+of this license.
+
+NO WARRANTY OF ANY KIND IS IMPLIED BY, OR SHOULD BE INFERRED FROM, THIS LICENSE
+OR THE ACT OF DISTRIBUTION UNDER THE TERMS OF THIS LICENSE, INCLUDING BUT NOT
+LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
+AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS, ASSEMBLERS, OR HOLDERS OF
+COPYRIGHT OR OTHER LEGAL PRIVILEGE BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER
+LIABILITY, WHETHER IN ACTION OF CONTRACT, TORT, OR OTHERWISE ARISING FROM, OUT
+OF, OR IN CONNECTION WITH THE WORK OR THE USE OF OR OTHER DEALINGS IN THE WORK.
diff --git a/options/license/Community-Spec-1.0 b/options/license/Community-Spec-1.0
new file mode 100644
index 000000000000..cdf7c64c07cd
--- /dev/null
+++ b/options/license/Community-Spec-1.0
@@ -0,0 +1,293 @@
+Community Specification License 1.0
+
+The Purpose of this License. This License sets forth the terms under which
+1) Contributor will participate in and contribute to the development
+of specifications, standards, best practices, guidelines, and other
+similar materials under this Working Group, and 2) how the materials
+developed under this License may be used. It is not intended for source
+code. Capitalized terms are defined in the License’s last section.
+
+1. Copyright.
+
+1.1. Copyright License. Contributor grants everyone a non-sublicensable,
+perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+(except as expressly stated in this License) copyright license, without
+any obligation for accounting, to reproduce, prepare derivative works
+of, publicly display, publicly perform, and distribute any materials
+it submits to the full extent of its copyright interest in those
+materials. Contributor also acknowledges that the Working Group may
+exercise copyright rights in the Specification, including the rights to
+submit the Specification to another standards organization.
+
+1.2. Copyright Attribution. As a condition, anyone exercising this
+copyright license must include attribution to the Working Group in any
+derivative work based on materials developed by the Working Group.
+That attribution must include, at minimum, the material’s name,
+version number, and source from where the materials were retrieved.
+Attribution is not required for implementations of the Specification.
+
+2. Patents.
+
+2.1. Patent License.
+
+2.1.1. As a Result of Contributions.
+
+2.1.1.1. As a Result of Contributions to Draft Specifications.
+Contributor grants Licensee a non-sublicensable, perpetual, worldwide,
+non-exclusive, no-charge, royalty-free, irrevocable (except as
+expressly stated in this License) license to its Necessary Claims in 1)
+Contributor’s Contributions and 2) to the Draft Specification that
+is within Scope as of the date of that Contribution, in both cases for
+Licensee’s Implementation of the Draft Specification, except for those
+patent claims excluded by Contributor under Section 3.
+
+2.1.1.2. For Approved Specifications. Contributor grants Licensee a
+non-sublicensable, perpetual, worldwide, non-exclusive, no-charge,
+royalty-free, irrevocable (except as expressly stated in this License)
+license to its Necessary Claims included the Approved Specification
+that are within Scope for Licensee’s Implementation of the Approved
+Specification, except for those patent claims excluded by Contributor
+under Section 3.
+
+2.1.2. Patent Grant from Licensee. Licensee grants each other Licensee
+a non-sublicensable, perpetual, worldwide, non-exclusive, no-charge,
+royalty-free, irrevocable (except as expressly stated in this License)
+license to its Necessary Claims for its Implementation, except for those
+patent claims excluded under Section 3.
+
+2.1.3. Licensee Acceptance. The patent grants set forth in Section 2.1
+extend only to Licensees that have indicated their agreement to this
+License as follows:
+
+2.1.3.1. Source Code Distributions. For distribution in source code,
+by including this License in the root directory of the source code with
+the Implementation;
+
+2.1.3.2. Non-Source Code Distributions. For distribution in any form
+other than source code, by including this License in the documentation,
+legal notices, via notice in the software, and/or other written materials
+provided with the Implementation; or
+
+2.1.3.3. Via Notices.md. By issuing pull request or commit to the
+Specification’s repository’s Notices.md file by the Implementer’s
+authorized representative, including the Implementer’s name, authorized
+individual and system identifier, and Specification version.
+
+2.1.4. Defensive Termination. If any Licensee files or maintains a
+claim in a court asserting that a Necessary Claim is infringed by an
+Implementation, any licenses granted under this License to the Licensee
+are immediately terminated unless 1) that claim is directly in response
+to a claim against Licensee regarding an Implementation, or 2) that claim
+was brought to enforce the terms of this License, including intervention
+in a third-party action by a Licensee.
+
+2.1.5. Additional Conditions. This License is not an assurance (i)
+that any of Contributor’s copyrights or issued patent claims cover
+an Implementation of the Specification or are enforceable or (ii) that
+an Implementation of the Specification would not infringe intellectual
+property rights of any third party.
+
+2.2. Patent Licensing Commitment. In addition to the rights granted
+in Section 2.1, Contributor agrees to grant everyone a no charge,
+royalty-free license on reasonable and non-discriminatory terms
+to Contributor’s Necessary Claims that are within Scope for:
+1) Implementations of a Draft Specification, where such license
+applies only to those Necessary Claims infringed by implementing
+Contributor's Contribution(s) included in that Draft Specification,
+and 2) Implementations of the Approved Specification.
+
+This patent licensing commitment does not apply to those claims subject
+to Contributor’s Exclusion Notice under Section 3.
+
+2.3. Effect of Withdrawal. Contributor may withdraw from the Working Group
+by issuing a pull request or commit providing notice of withdrawal to
+the Working Group repository’s Notices.md file. All of Contributor’s
+existing commitments and obligations with respect to the Working Group
+up to the date of that withdrawal notice will remain in effect, but no
+new obligations will be incurred.
+
+2.4. Binding Encumbrance. This License is binding on any future owner,
+assignee, or party who has been given the right to enforce any Necessary
+Claims against third parties.
+
+3. Patent Exclusion.
+
+3.1. As a Result of Contributions. Contributor may exclude Necessary
+Claims from its licensing commitments incurred under Section 2.1.1
+by issuing an Exclusion Notice within 45 days of the date of that
+Contribution. Contributor may not issue an Exclusion Notice for any
+material that has been included in a Draft Deliverable for more than 45
+days prior to the date of that Contribution.
+
+3.2. As a Result of a Draft Specification Becoming an Approved
+Specification. Prior to the adoption of a Draft Specification as an
+Approved Specification, Contributor may exclude Necessary Claims from
+its licensing commitments under this Agreement by issuing an Exclusion
+Notice. Contributor may not issue an Exclusion Notice for patents that
+were eligible to have been excluded pursuant to Section 3.1.
+
+4. Source Code License. Any source code developed by the Working Group is
+solely subject the source code license included in the Working Group’s
+repository for that code. If no source code license is included, the
+source code will be subject to the MIT License.
+
+5. No Other Rights. Except as specifically set forth in this License, no
+other express or implied patent, trademark, copyright, or other rights are
+granted under this License, including by implication, waiver, or estoppel.
+
+6. Antitrust Compliance. Contributor acknowledge that it may compete
+with other participants in various lines of business and that it is
+therefore imperative that they and their respective representatives
+act in a manner that does not violate any applicable antitrust laws and
+regulations. This License does not restrict any Contributor from engaging
+in similar specification development projects. Each Contributor may
+design, develop, manufacture, acquire or market competitive deliverables,
+products, and services, and conduct its business, in whatever way it
+chooses. No Contributor is obligated to announce or market any products
+or services. Without limiting the generality of the foregoing, the
+Contributors agree not to have any discussion relating to any product
+pricing, methods or channels of product distribution, division of markets,
+allocation of customers or any other topic that should not be discussed
+among competitors under the auspices of the Working Group.
+
+7. Non-Circumvention. Contributor agrees that it will not intentionally
+take or willfully assist any third party to take any action for the
+purpose of circumventing any obligations under this License.
+
+8. Representations, Warranties and Disclaimers.
+
+8.1. Representations, Warranties and Disclaimers. Contributor and Licensee
+represents and warrants that 1) it is legally entitled to grant the
+rights set forth in this License and 2) it will not intentionally include
+any third party materials in any Contribution unless those materials are
+available under terms that do not conflict with this License. IN ALL OTHER
+RESPECTS ITS CONTRIBUTIONS ARE PROVIDED "AS IS." The entire risk as to
+implementing or otherwise using the Contribution or the Specification
+is assumed by the implementer and user. Except as stated herein,
+CONTRIBUTOR AND LICENSEE EXPRESSLY DISCLAIM ANY WARRANTIES (EXPRESS,
+IMPLIED, OR OTHERWISE), INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY,
+NON-INFRINGEMENT, FITNESS FOR A PARTICULAR PURPOSE, CONDITIONS OF QUALITY,
+OR TITLE, RELATED TO THE CONTRIBUTION OR THE SPECIFICATION. IN NO EVENT
+WILL ANY PARTY BE LIABLE TO ANY OTHER PARTY FOR LOST PROFITS OR ANY
+FORM OF INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF
+ANY CHARACTER FROM ANY CAUSES OF ACTION OF ANY KIND WITH RESPECT TO
+THIS AGREEMENT, WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING
+NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT THE OTHER PARTY HAS BEEN
+ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Any obligations regarding
+the transfer, successors in interest, or assignment of Necessary Claims
+will be satisfied if Contributor or Licensee notifies the transferee
+or assignee of any patent that it knows contains Necessary Claims or
+necessary claims under this License. Nothing in this License requires
+Contributor to undertake a patent search. If Contributor is 1) employed by
+or acting on behalf of an employer, 2) is making a Contribution under the
+direction or control of a third party, or 3) is making the Contribution
+as a consultant, contractor, or under another similar relationship with
+a third party, Contributor represents that they have been authorized by
+that party to enter into this License on its behalf.
+
+8.2. Distribution Disclaimer. Any distributions of technical
+information to third parties must include a notice materially similar
+to the following: “THESE MATERIALS ARE PROVIDED “AS IS.” The
+Contributors and Licensees expressly disclaim any warranties (express,
+implied, or otherwise), including implied warranties of merchantability,
+non-infringement, fitness for a particular purpose, or title, related to
+the materials. The entire risk as to implementing or otherwise using the
+materials is assumed by the implementer and user. IN NO EVENT WILL THE
+CONTRIBUTORS OR LICENSEES BE LIABLE TO ANY OTHER PARTY FOR LOST PROFITS
+OR ANY FORM OF INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
+OF ANY CHARACTER FROM ANY CAUSES OF ACTION OF ANY KIND WITH RESPECT TO
+THIS DELIVERABLE OR ITS GOVERNING AGREEMENT, WHETHER BASED ON BREACH OF
+CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT
+THE OTHER MEMBER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.”
+
+9. Definitions.
+
+9.1. Affiliate. “Affiliate” means an entity that directly or
+indirectly Controls, is Controlled by, or is under common Control of
+that party.
+
+9.2. Approved Specification. “Approved Specification” means the final
+version and contents of any Draft Specification designated as an Approved
+Specification as set forth in the accompanying Governance.md file.
+
+9.3. Contribution. “Contribution” means any original work of
+authorship, including any modifications or additions to an existing
+work, that Contributor submits for inclusion in a Draft Specification,
+which is included in a Draft Specification or Approved Specification.
+
+9.4. Contributor. “Contributor” means any person or entity that has
+indicated its acceptance of the License 1) by making a Contribution to
+the Specification, or 2) by entering into the Community Specification
+Contributor License Agreement for the Specification. Contributor includes
+its Affiliates, assigns, agents, and successors in interest.
+
+9.5. Control. “Control” means direct or indirect control of more
+than 50% of the voting power to elect directors of that corporation,
+or for any other entity, the power to direct management of such entity.
+
+9.6. Draft Specification. “Draft Specification” means all versions
+of the material (except an Approved Specification) developed by this
+Working Group for the purpose of creating, commenting on, revising,
+updating, modifying, or adding to any document that is to be considered
+for inclusion in the Approved Specification.
+
+9.7. Exclusion Notice. “Exclusion Notice” means a written notice
+made by making a pull request or commit to the repository’s Notices.md
+file that identifies patents that Contributor is excluding from its
+patent licensing commitments under this License. The Exclusion Notice
+for issued patents and published applications must include the Draft
+Specification’s name, patent number(s) or title and application
+number(s), as the case may be, for each of the issued patent(s) or
+pending patent application(s) that the Contributor is excluding from the
+royalty-free licensing commitment set forth in this License. If an issued
+patent or pending patent application that may contain Necessary Claims
+is not set forth in the Exclusion Notice, those Necessary Claims shall
+continue to be subject to the licensing commitments under this License.
+The Exclusion Notice for unpublished patent applications must provide
+either: (i) the text of the filed application; or (ii) identification
+of the specific part(s) of the Draft Specification whose implementation
+makes the excluded claim a Necessary Claim. If (ii) is chosen, the
+effect of the exclusion will be limited to the identified part(s) of
+the Draft Specification.
+
+9.8. Implementation. “Implementation” means making, using, selling,
+offering for sale, importing or distributing any implementation of the
+Specification 1) only to the extent it implements the Specification and 2)
+so long as all required portions of the Specification are implemented.
+
+9.9. License. “License” means this Community Specification License.
+
+9.10. Licensee. “Licensee” means any person or entity that has
+indicated its acceptance of the License as set forth in Section 2.1.3.
+Licensee includes its Affiliates, assigns, agents, and successors in
+interest.
+
+9.11. Necessary Claims. “Necessary Claims” are those patent claims, if
+any, that a party owns or controls, including those claims later acquired,
+that are necessary to implement the required portions (including the
+required elements of optional portions) of the Specification that are
+described in detail and not merely referenced in the Specification.
+
+9.12. Specification. “Specification” means a Draft Specification
+or Approved Specification included in the Working Group’s repository
+subject to this License, and the version of the Specification implemented
+by the Licensee.
+
+9.13. Scope. “Scope” has the meaning as set forth in the accompanying
+Scope.md file included in this Specification’s repository. Changes
+to Scope do not apply retroactively. If no Scope is provided, each
+Contributor’s Necessary Claims are limited to that Contributor’s
+Contributions.
+
+9.14. Working Group. “Working Group” means this project to develop
+specifications, standards, best practices, guidelines, and other similar
+materials under this License.
+
+
+
+The text of this Community Specification License is Copyright 2020
+Joint Development Foundation and is licensed under the Creative
+Commons Attribution 4.0 International License available at
+https://creativecommons.org/licenses/by/4.0/.
+
+SPDX-License-Identifier: CC-BY-4.0
diff --git a/options/license/FDK-AAC b/options/license/FDK-AAC
new file mode 100644
index 000000000000..e506d69d5eea
--- /dev/null
+++ b/options/license/FDK-AAC
@@ -0,0 +1,79 @@
+Software License for The Fraunhofer FDK AAC Codec Library for Android
+
+© Copyright  1995 - 2012 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V.
+  All rights reserved.
+
+1.    INTRODUCTION
+The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements
+the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio.
+This FDK AAC Codec software is intended to be used on a wide variety of Android devices.
+
+AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual
+audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by
+independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part
+of the MPEG specifications.
+
+Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer)
+may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners
+individually for the purpose of encoding or decoding bit streams in products that are compliant with
+the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license
+these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec
+software may already be covered under those patent licenses when it is used for those licensed purposes only.
+
+Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality,
+are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional
+applications information and documentation.
+
+2.    COPYRIGHT LICENSE
+
+Redistribution and use in source and binary forms, with or without modification, are permitted without
+payment of copyright license fees provided that you satisfy the following conditions:
+
+You must retain the complete text of this software license in redistributions of the FDK AAC Codec or
+your modifications thereto in source code form.
+
+You must retain the complete text of this software license in the documentation and/or other materials
+provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form.
+You must make available free of charge copies of the complete source code of the FDK AAC Codec and your
+modifications thereto to recipients of copies in binary form.
+
+The name of Fraunhofer may not be used to endorse or promote products derived from this library without
+prior written permission.
+
+You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec
+software or your modifications thereto.
+
+Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software
+and the date of any change. For modified versions of the FDK AAC Codec, the term
+"Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term
+"Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android."
+
+3.    NO PATENT LICENSE
+
+NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer,
+ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with
+respect to this software.
+
+You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized
+by appropriate patent licenses.
+
+4.    DISCLAIMER
+
+This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors
+"AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties
+of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
+CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages,
+including but not limited to procurement of substitute goods or services; loss of use, data, or profits,
+or business interruption, however caused and on any theory of liability, whether in contract, strict
+liability, or tort (including negligence), arising in any way out of the use of this software, even if
+advised of the possibility of such damage.
+
+5.    CONTACT INFORMATION
+
+Fraunhofer Institute for Integrated Circuits IIS
+Attention: Audio and Multimedia Departments - FDK AAC LL
+Am Wolfsmantel 33
+91058 Erlangen, Germany
+
+www.iis.fraunhofer.de/amm
+amm-info@iis.fraunhofer.de
diff --git a/options/license/Linux-man-pages-copyleft b/options/license/Linux-man-pages-copyleft
index 8a10d8e6840d..764635ae5c8d 100644
--- a/options/license/Linux-man-pages-copyleft
+++ b/options/license/Linux-man-pages-copyleft
@@ -1,4 +1,4 @@
-Copyright (c) 0000, Obelix the Gaul .
+Copyright (c)   All rights reserved.
 
 Permission is granted to make and distribute verbatim copies of this
 manual provided the copyright notice and this permission notice are
diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini
index cb343e46d27c..c39063e46e75 100644
--- a/options/locale/locale_en-US.ini
+++ b/options/locale/locale_en-US.ini
@@ -85,6 +85,12 @@ remove = Remove
 remove_all = Remove All
 edit = Edit
 
+copy = Copy
+copy_url = Copy URL
+copy_branch = Copy branch name
+copy_success = Copied!
+copy_error = Copy failed
+
 write = Write
 preview = Preview
 loading = Loading…
@@ -904,12 +910,14 @@ migrate.migrate = Migrate From %s
 migrate.migrating = Migrating from %s ...
 migrate.migrating_failed = Migrating from %s failed.
 migrate.migrating_failed.error = Error: %s
+migrate.migrating_failed_no_addr = Migration failed.
 migrate.github.description = Migrate data from github.com or other Github instances.
 migrate.git.description = Migrate a repository only from any Git service.
 migrate.gitlab.description = Migrate data from gitlab.com or other GitLab instances.
 migrate.gitea.description = Migrate data from gitea.com or other Gitea instances.
 migrate.gogs.description = Migrate data from notabug.org or other Gogs instances.
 migrate.onedev.description = Migrate data from code.onedev.io or other OneDev instances.
+migrate.gitbucket.description = Migrate data from GitBucket instances.
 migrate.migrating_git = Migrating Git Data
 migrate.migrating_topics = Migrating Topics
 migrate.migrating_milestones = Migrating Milestones
@@ -925,13 +933,6 @@ fork_from_self = You cannot fork a repository you own.
 fork_guest_user = Sign in to fork this repository.
 watch_guest_user = Sign in to watch this repository.
 star_guest_user = Sign in to star this repository.
-copy_link = Copy
-copy_link_success = Link has been copied
-copy_link_error = Use ⌘C or Ctrl-C to copy
-copy_branch = Copy
-copy_branch_success = Branch name has been copied
-copy_branch_error = Use ⌘C or Ctrl-C to copy
-copied = Copied OK
 unwatch = Unwatch
 watch = Watch
 unstar = Unstar
@@ -987,6 +988,7 @@ commit_graph.hide_pr_refs = Hide Pull Requests
 commit_graph.monochrome = Mono
 commit_graph.color = Color
 blame = Blame
+download_file = Download file
 normal_view = Normal View
 line = line
 lines = lines
diff --git a/options/locale/locale_fi-FI.ini b/options/locale/locale_fi-FI.ini
index a44d99a9bf21..4065b4acf7b0 100644
--- a/options/locale/locale_fi-FI.ini
+++ b/options/locale/locale_fi-FI.ini
@@ -494,7 +494,6 @@ delete_prompt=Tämä toiminto poistaa käyttäjätilisi pysyvästi. Toimintoa %s 遷移...
 migrate.migrating_failed=從 %s 遷移失敗
 migrate.migrating_failed.error=錯誤:%s
+migrate.migrating_failed_no_addr=遷移失敗。
 migrate.github.description=從 github.com 或其他 Github 實例遷移資料。
 migrate.git.description=從任何 Git 服務遷移儲存庫。
 migrate.gitlab.description=從 gitlab.com 或其他 GitLab 實例遷移資料。
 migrate.gitea.description=從 gitea.com 或其他 Gitea 實例遷移資料。
 migrate.gogs.description=從 notabug.org 或其他 Gogs 實例遷移資料。
 migrate.onedev.description=從 code.onedev.io 或其他 OneDev 實例遷移資料。
+migrate.gitbucket.description=從 GitBucket 實例遷移資料。
 migrate.migrating_git=正在遷移 Git 資料
 migrate.migrating_topics=正在遷移主題
 migrate.migrating_milestones=正在遷移里程碑
diff --git a/package-lock.json b/package-lock.json
index df4c575469fa..2ebeff0f305d 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -51,6 +51,7 @@
         "eslint-plugin-vue": "8.0.3",
         "jest": "27.3.1",
         "jest-extended": "1.1.0",
+        "jest-raw-loader": "1.0.1",
         "postcss-less": "5.0.0",
         "stylelint": "14.0.1",
         "stylelint-config-standard": "23.0.0",
@@ -6221,6 +6222,12 @@
         }
       }
     },
+    "node_modules/jest-raw-loader": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/jest-raw-loader/-/jest-raw-loader-1.0.1.tgz",
+      "integrity": "sha1-zp9W1UZQ8VfEp9FtIkul1hO81iY=",
+      "dev": true
+    },
     "node_modules/jest-regex-util": {
       "version": "27.0.6",
       "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-27.0.6.tgz",
@@ -14693,6 +14700,12 @@
       "dev": true,
       "requires": {}
     },
+    "jest-raw-loader": {
+      "version": "1.0.1",
+      "resolved": "https://registry.npmjs.org/jest-raw-loader/-/jest-raw-loader-1.0.1.tgz",
+      "integrity": "sha1-zp9W1UZQ8VfEp9FtIkul1hO81iY=",
+      "dev": true
+    },
     "jest-regex-util": {
       "version": "27.0.6",
       "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-27.0.6.tgz",
diff --git a/package.json b/package.json
index 71c9ab40fd4f..3c63141922f0 100644
--- a/package.json
+++ b/package.json
@@ -51,6 +51,7 @@
     "eslint-plugin-vue": "8.0.3",
     "jest": "27.3.1",
     "jest-extended": "1.1.0",
+    "jest-raw-loader": "1.0.1",
     "postcss-less": "5.0.0",
     "stylelint": "14.0.1",
     "stylelint-config-standard": "23.0.0",
diff --git a/public/img/svg/gitea-gitbucket.svg b/public/img/svg/gitea-gitbucket.svg
new file mode 100644
index 000000000000..3d07adebdd00
--- /dev/null
+++ b/public/img/svg/gitea-gitbucket.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/public/img/svg/gitea-vscode.svg b/public/img/svg/gitea-vscode.svg
new file mode 100644
index 000000000000..4ef94dec3b63
--- /dev/null
+++ b/public/img/svg/gitea-vscode.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/routers/api/v1/admin/adopt.go b/routers/api/v1/admin/adopt.go
index 9c1b9fc0f864..184a2941a871 100644
--- a/routers/api/v1/admin/adopt.go
+++ b/routers/api/v1/admin/adopt.go
@@ -9,9 +9,9 @@ import (
 
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/modules/context"
-	"code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/util"
 	"code.gitea.io/gitea/routers/api/v1/utils"
+	repo_service "code.gitea.io/gitea/services/repository"
 )
 
 // ListUnadoptedRepositories lists the unadopted repositories that match the provided names
@@ -41,7 +41,7 @@ func ListUnadoptedRepositories(ctx *context.APIContext) {
 	//     "$ref": "#/responses/forbidden"
 
 	listOptions := utils.GetListOptions(ctx)
-	repoNames, count, err := repository.ListUnadoptedRepositories(ctx.FormString("query"), &listOptions)
+	repoNames, count, err := repo_service.ListUnadoptedRepositories(ctx.FormString("query"), &listOptions)
 	if err != nil {
 		ctx.InternalServerError(err)
 	}
@@ -104,7 +104,7 @@ func AdoptRepository(ctx *context.APIContext) {
 		ctx.NotFound()
 		return
 	}
-	if _, err := repository.AdoptRepository(ctx.User, ctxUser, models.CreateRepoOptions{
+	if _, err := repo_service.AdoptRepository(ctx.User, ctxUser, models.CreateRepoOptions{
 		Name:      repoName,
 		IsPrivate: true,
 	}); err != nil {
@@ -167,7 +167,7 @@ func DeleteUnadoptedRepository(ctx *context.APIContext) {
 		return
 	}
 
-	if err := repository.DeleteUnadoptedRepository(ctx.User, ctxUser, repoName); err != nil {
+	if err := repo_service.DeleteUnadoptedRepository(ctx.User, ctxUser, repoName); err != nil {
 		ctx.InternalServerError(err)
 		return
 	}
diff --git a/routers/api/v1/admin/cron.go b/routers/api/v1/admin/cron.go
index 970fad83880c..1476872a905a 100644
--- a/routers/api/v1/admin/cron.go
+++ b/routers/api/v1/admin/cron.go
@@ -8,11 +8,11 @@ import (
 	"net/http"
 
 	"code.gitea.io/gitea/modules/context"
-	"code.gitea.io/gitea/modules/cron"
 	"code.gitea.io/gitea/modules/log"
 	"code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/modules/util"
 	"code.gitea.io/gitea/routers/api/v1/utils"
+	"code.gitea.io/gitea/services/cron"
 )
 
 // ListCronTasks api for getting cron tasks
diff --git a/routers/api/v1/repo/hook_test.go b/routers/api/v1/repo/hook_test.go
index 60fa6cead31c..07f1532f82d6 100644
--- a/routers/api/v1/repo/hook_test.go
+++ b/routers/api/v1/repo/hook_test.go
@@ -8,7 +8,7 @@ import (
 	"net/http"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/models/webhook"
 	"code.gitea.io/gitea/modules/context"
 	"code.gitea.io/gitea/modules/test"
@@ -17,7 +17,7 @@ import (
 )
 
 func TestTestHook(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1/wiki/_pages")
 	ctx.SetParams(":id", "1")
@@ -27,8 +27,8 @@ func TestTestHook(t *testing.T) {
 	TestHook(&context.APIContext{Context: ctx, Org: nil})
 	assert.EqualValues(t, http.StatusNoContent, ctx.Resp.Status())
 
-	db.AssertExistsAndLoadBean(t, &webhook.HookTask{
+	unittest.AssertExistsAndLoadBean(t, &webhook.HookTask{
 		RepoID: 1,
 		HookID: 1,
-	}, db.Cond("is_delivered=?", false))
+	}, unittest.Cond("is_delivered=?", false))
 }
diff --git a/routers/api/v1/repo/main_test.go b/routers/api/v1/repo/main_test.go
index 7a66370e05b2..f9ed886999c9 100644
--- a/routers/api/v1/repo/main_test.go
+++ b/routers/api/v1/repo/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", "..", "..", ".."))
+	unittest.MainTest(m, filepath.Join("..", "..", "..", ".."))
 }
diff --git a/routers/api/v1/repo/migrate.go b/routers/api/v1/repo/migrate.go
index 87ceb547c60b..00390dfb5f54 100644
--- a/routers/api/v1/repo/migrate.go
+++ b/routers/api/v1/repo/migrate.go
@@ -17,8 +17,7 @@ import (
 	"code.gitea.io/gitea/modules/graceful"
 	"code.gitea.io/gitea/modules/lfs"
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/notification"
 	repo_module "code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/setting"
@@ -26,6 +25,7 @@ import (
 	"code.gitea.io/gitea/modules/util"
 	"code.gitea.io/gitea/modules/web"
 	"code.gitea.io/gitea/services/forms"
+	"code.gitea.io/gitea/services/migrations"
 )
 
 // Migrate migrate remote git repository to gitea
diff --git a/routers/api/v1/repo/repo_test.go b/routers/api/v1/repo/repo_test.go
index e4fd4f94240e..4d4093582b08 100644
--- a/routers/api/v1/repo/repo_test.go
+++ b/routers/api/v1/repo/repo_test.go
@@ -9,7 +9,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/context"
 	api "code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/modules/test"
@@ -19,7 +19,7 @@ import (
 )
 
 func TestRepoEdit(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1")
 	test.LoadRepo(t, ctx, 1)
@@ -60,13 +60,13 @@ func TestRepoEdit(t *testing.T) {
 	Edit(apiCtx)
 
 	assert.EqualValues(t, http.StatusOK, ctx.Resp.Status())
-	db.AssertExistsAndLoadBean(t, &models.Repository{
+	unittest.AssertExistsAndLoadBean(t, &models.Repository{
 		ID: 1,
-	}, db.Cond("name = ? AND is_archived = 1", *opts.Name))
+	}, unittest.Cond("name = ? AND is_archived = 1", *opts.Name))
 }
 
 func TestRepoEditNameChange(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1")
 	test.LoadRepo(t, ctx, 1)
@@ -82,7 +82,7 @@ func TestRepoEditNameChange(t *testing.T) {
 	Edit(apiCtx)
 	assert.EqualValues(t, http.StatusOK, ctx.Resp.Status())
 
-	db.AssertExistsAndLoadBean(t, &models.Repository{
+	unittest.AssertExistsAndLoadBean(t, &models.Repository{
 		ID: 1,
-	}, db.Cond("name = ?", opts.Name))
+	}, unittest.Cond("name = ?", opts.Name))
 }
diff --git a/routers/init.go b/routers/init.go
index 80e2fec09592..0f19e7f732d8 100644
--- a/routers/init.go
+++ b/routers/init.go
@@ -15,7 +15,6 @@ import (
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/modules/appstate"
 	"code.gitea.io/gitea/modules/cache"
-	"code.gitea.io/gitea/modules/cron"
 	"code.gitea.io/gitea/modules/eventsource"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/highlight"
@@ -25,7 +24,6 @@ import (
 	"code.gitea.io/gitea/modules/log"
 	"code.gitea.io/gitea/modules/markup"
 	"code.gitea.io/gitea/modules/markup/external"
-	repo_migrations "code.gitea.io/gitea/modules/migrations"
 	"code.gitea.io/gitea/modules/notification"
 	repo_module "code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/setting"
@@ -42,7 +40,9 @@ import (
 	"code.gitea.io/gitea/services/archiver"
 	"code.gitea.io/gitea/services/auth"
 	"code.gitea.io/gitea/services/auth/source/oauth2"
+	"code.gitea.io/gitea/services/cron"
 	"code.gitea.io/gitea/services/mailer"
+	repo_migrations "code.gitea.io/gitea/services/migrations"
 	mirror_service "code.gitea.io/gitea/services/mirror"
 	pull_service "code.gitea.io/gitea/services/pull"
 	"code.gitea.io/gitea/services/repository"
diff --git a/routers/private/restore_repo.go b/routers/private/restore_repo.go
index b7f7ed176f7c..85aada192f40 100644
--- a/routers/private/restore_repo.go
+++ b/routers/private/restore_repo.go
@@ -10,8 +10,8 @@ import (
 
 	myCtx "code.gitea.io/gitea/modules/context"
 	"code.gitea.io/gitea/modules/json"
-	"code.gitea.io/gitea/modules/migrations"
 	"code.gitea.io/gitea/modules/private"
+	"code.gitea.io/gitea/services/migrations"
 )
 
 // RestoreRepo restore a repository from data
diff --git a/routers/web/admin/admin.go b/routers/web/admin/admin.go
index 223114dae1cc..8cbe85271852 100644
--- a/routers/web/admin/admin.go
+++ b/routers/web/admin/admin.go
@@ -18,7 +18,6 @@ import (
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/modules/base"
 	"code.gitea.io/gitea/modules/context"
-	"code.gitea.io/gitea/modules/cron"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/json"
 	"code.gitea.io/gitea/modules/log"
@@ -28,6 +27,7 @@ import (
 	"code.gitea.io/gitea/modules/timeutil"
 	"code.gitea.io/gitea/modules/updatechecker"
 	"code.gitea.io/gitea/modules/web"
+	"code.gitea.io/gitea/services/cron"
 	"code.gitea.io/gitea/services/forms"
 	"code.gitea.io/gitea/services/mailer"
 
diff --git a/routers/web/admin/main_test.go b/routers/web/admin/main_test.go
index cfdefdb1b4af..e41d8fea75c3 100644
--- a/routers/web/admin/main_test.go
+++ b/routers/web/admin/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", "..", ".."))
+	unittest.MainTest(m, filepath.Join("..", "..", ".."))
 }
diff --git a/routers/web/admin/repos.go b/routers/web/admin/repos.go
index 19f111165ac9..432dd2f6ae60 100644
--- a/routers/web/admin/repos.go
+++ b/routers/web/admin/repos.go
@@ -14,7 +14,6 @@ import (
 	"code.gitea.io/gitea/modules/base"
 	"code.gitea.io/gitea/modules/context"
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/util"
 	"code.gitea.io/gitea/routers/web/explore"
@@ -95,7 +94,7 @@ func UnadoptedRepos(ctx *context.Context) {
 	}
 
 	ctx.Data["Keyword"] = q
-	repoNames, count, err := repository.ListUnadoptedRepositories(q, &opts)
+	repoNames, count, err := repo_service.ListUnadoptedRepositories(q, &opts)
 	if err != nil {
 		ctx.ServerError("ListUnadoptedRepositories", err)
 	}
@@ -147,7 +146,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) {
 	if has || !isDir {
 		// Fallthrough to failure mode
 	} else if action == "adopt" {
-		if _, err := repository.AdoptRepository(ctx.User, ctxUser, models.CreateRepoOptions{
+		if _, err := repo_service.AdoptRepository(ctx.User, ctxUser, models.CreateRepoOptions{
 			Name:      dirSplit[1],
 			IsPrivate: true,
 		}); err != nil {
@@ -156,7 +155,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) {
 		}
 		ctx.Flash.Success(ctx.Tr("repo.adopt_preexisting_success", dir))
 	} else if action == "delete" {
-		if err := repository.DeleteUnadoptedRepository(ctx.User, ctxUser, dirSplit[1]); err != nil {
+		if err := repo_service.DeleteUnadoptedRepository(ctx.User, ctxUser, dirSplit[1]); err != nil {
 			ctx.ServerError("repository.AdoptRepository", err)
 			return
 		}
diff --git a/routers/web/admin/users_test.go b/routers/web/admin/users_test.go
index 022d8f662c8f..607ef2ea6634 100644
--- a/routers/web/admin/users_test.go
+++ b/routers/web/admin/users_test.go
@@ -8,7 +8,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/setting"
 	api "code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/modules/test"
@@ -20,10 +20,10 @@ import (
 
 func TestNewUserPost_MustChangePassword(t *testing.T) {
 
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "admin/users/new")
 
-	u := db.AssertExistsAndLoadBean(t, &models.User{
+	u := unittest.AssertExistsAndLoadBean(t, &models.User{
 		IsAdmin: true,
 		ID:      2,
 	}).(*models.User)
@@ -57,10 +57,10 @@ func TestNewUserPost_MustChangePassword(t *testing.T) {
 }
 
 func TestNewUserPost_MustChangePasswordFalse(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "admin/users/new")
 
-	u := db.AssertExistsAndLoadBean(t, &models.User{
+	u := unittest.AssertExistsAndLoadBean(t, &models.User{
 		IsAdmin: true,
 		ID:      2,
 	}).(*models.User)
@@ -94,10 +94,10 @@ func TestNewUserPost_MustChangePasswordFalse(t *testing.T) {
 }
 
 func TestNewUserPost_InvalidEmail(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "admin/users/new")
 
-	u := db.AssertExistsAndLoadBean(t, &models.User{
+	u := unittest.AssertExistsAndLoadBean(t, &models.User{
 		IsAdmin: true,
 		ID:      2,
 	}).(*models.User)
@@ -124,10 +124,10 @@ func TestNewUserPost_InvalidEmail(t *testing.T) {
 }
 
 func TestNewUserPost_VisibilityDefaultPublic(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "admin/users/new")
 
-	u := db.AssertExistsAndLoadBean(t, &models.User{
+	u := unittest.AssertExistsAndLoadBean(t, &models.User{
 		IsAdmin: true,
 		ID:      2,
 	}).(*models.User)
@@ -162,10 +162,10 @@ func TestNewUserPost_VisibilityDefaultPublic(t *testing.T) {
 }
 
 func TestNewUserPost_VisibilityPrivate(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "admin/users/new")
 
-	u := db.AssertExistsAndLoadBean(t, &models.User{
+	u := unittest.AssertExistsAndLoadBean(t, &models.User{
 		IsAdmin: true,
 		ID:      2,
 	}).(*models.User)
diff --git a/routers/web/base.go b/routers/web/base.go
index 16d3192da21d..98713bc8818f 100644
--- a/routers/web/base.go
+++ b/routers/web/base.go
@@ -130,14 +130,6 @@ func Recovery() func(next http.Handler) http.Handler {
 					log.Error("%v", combinedErr)
 
 					sessionStore := session.GetSession(req)
-					if sessionStore == nil {
-						if setting.IsProd {
-							http.Error(w, http.StatusText(500), 500)
-						} else {
-							http.Error(w, combinedErr, 500)
-						}
-						return
-					}
 
 					var lc = middleware.Locale(w, req)
 					var store = dataStore{
diff --git a/routers/web/repo/editor_test.go b/routers/web/repo/editor_test.go
index 8ab1fe1ee892..77f94ff5501e 100644
--- a/routers/web/repo/editor_test.go
+++ b/routers/web/repo/editor_test.go
@@ -7,7 +7,7 @@ package repo
 import (
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/test"
 
@@ -15,7 +15,7 @@ import (
 )
 
 func TestCleanUploadName(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	var kases = map[string]string{
 		".git/refs/master":               "",
@@ -41,7 +41,7 @@ func TestCleanUploadName(t *testing.T) {
 }
 
 func TestGetUniquePatchBranchName(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	ctx.SetParams(":id", "1")
 	test.LoadRepo(t, ctx, 1)
@@ -56,7 +56,7 @@ func TestGetUniquePatchBranchName(t *testing.T) {
 }
 
 func TestGetClosestParentWithFiles(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1")
 	ctx.SetParams(":id", "1")
 	test.LoadRepo(t, ctx, 1)
diff --git a/routers/web/repo/issue_label_test.go b/routers/web/repo/issue_label_test.go
index 8c3caabe17cf..baa34530fabd 100644
--- a/routers/web/repo/issue_label_test.go
+++ b/routers/web/repo/issue_label_test.go
@@ -10,7 +10,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/test"
 	"code.gitea.io/gitea/modules/web"
 	"code.gitea.io/gitea/services/forms"
@@ -30,14 +30,14 @@ func int64SliceToCommaSeparated(a []int64) string {
 }
 
 func TestInitializeLabels(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1/labels/initialize")
 	test.LoadUser(t, ctx, 2)
 	test.LoadRepo(t, ctx, 2)
 	web.SetForm(ctx, &forms.InitializeLabelsForm{TemplateName: "Default"})
 	InitializeLabels(ctx)
 	assert.EqualValues(t, http.StatusFound, ctx.Resp.Status())
-	db.AssertExistsAndLoadBean(t, &models.Label{
+	unittest.AssertExistsAndLoadBean(t, &models.Label{
 		RepoID: 2,
 		Name:   "enhancement",
 		Color:  "#84b6eb",
@@ -46,7 +46,7 @@ func TestInitializeLabels(t *testing.T) {
 }
 
 func TestRetrieveLabels(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	for _, testCase := range []struct {
 		RepoID           int64
 		Sort             string
@@ -73,7 +73,7 @@ func TestRetrieveLabels(t *testing.T) {
 }
 
 func TestNewLabel(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1/labels/edit")
 	test.LoadUser(t, ctx, 2)
 	test.LoadRepo(t, ctx, 1)
@@ -83,7 +83,7 @@ func TestNewLabel(t *testing.T) {
 	})
 	NewLabel(ctx)
 	assert.EqualValues(t, http.StatusFound, ctx.Resp.Status())
-	db.AssertExistsAndLoadBean(t, &models.Label{
+	unittest.AssertExistsAndLoadBean(t, &models.Label{
 		Name:  "newlabel",
 		Color: "#abcdef",
 	})
@@ -91,7 +91,7 @@ func TestNewLabel(t *testing.T) {
 }
 
 func TestUpdateLabel(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1/labels/edit")
 	test.LoadUser(t, ctx, 2)
 	test.LoadRepo(t, ctx, 1)
@@ -102,7 +102,7 @@ func TestUpdateLabel(t *testing.T) {
 	})
 	UpdateLabel(ctx)
 	assert.EqualValues(t, http.StatusFound, ctx.Resp.Status())
-	db.AssertExistsAndLoadBean(t, &models.Label{
+	unittest.AssertExistsAndLoadBean(t, &models.Label{
 		ID:    2,
 		Name:  "newnameforlabel",
 		Color: "#abcdef",
@@ -111,20 +111,20 @@ func TestUpdateLabel(t *testing.T) {
 }
 
 func TestDeleteLabel(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1/labels/delete")
 	test.LoadUser(t, ctx, 2)
 	test.LoadRepo(t, ctx, 1)
 	ctx.Req.Form.Set("id", "2")
 	DeleteLabel(ctx)
 	assert.EqualValues(t, http.StatusOK, ctx.Resp.Status())
-	db.AssertNotExistsBean(t, &models.Label{ID: 2})
-	db.AssertNotExistsBean(t, &models.IssueLabel{LabelID: 2})
+	unittest.AssertNotExistsBean(t, &models.Label{ID: 2})
+	unittest.AssertNotExistsBean(t, &models.IssueLabel{LabelID: 2})
 	assert.Equal(t, ctx.Tr("repo.issues.label_deletion_success"), ctx.Flash.SuccessMsg)
 }
 
 func TestUpdateIssueLabel_Clear(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1/issues/labels")
 	test.LoadUser(t, ctx, 2)
 	test.LoadRepo(t, ctx, 1)
@@ -132,9 +132,9 @@ func TestUpdateIssueLabel_Clear(t *testing.T) {
 	ctx.Req.Form.Set("action", "clear")
 	UpdateIssueLabel(ctx)
 	assert.EqualValues(t, http.StatusOK, ctx.Resp.Status())
-	db.AssertNotExistsBean(t, &models.IssueLabel{IssueID: 1})
-	db.AssertNotExistsBean(t, &models.IssueLabel{IssueID: 3})
-	models.CheckConsistencyFor(t, &models.Label{})
+	unittest.AssertNotExistsBean(t, &models.IssueLabel{IssueID: 1})
+	unittest.AssertNotExistsBean(t, &models.IssueLabel{IssueID: 3})
+	unittest.CheckConsistencyFor(t, &models.Label{})
 }
 
 func TestUpdateIssueLabel_Toggle(t *testing.T) {
@@ -149,7 +149,7 @@ func TestUpdateIssueLabel_Toggle(t *testing.T) {
 		{"toggle", []int64{1, 3}, 1, false},
 		{"toggle", []int64{1, 2}, 2, true},
 	} {
-		db.PrepareTestEnv(t)
+		unittest.PrepareTestEnv(t)
 		ctx := test.MockContext(t, "user2/repo1/issues/labels")
 		test.LoadUser(t, ctx, 2)
 		test.LoadRepo(t, ctx, 1)
@@ -159,11 +159,11 @@ func TestUpdateIssueLabel_Toggle(t *testing.T) {
 		UpdateIssueLabel(ctx)
 		assert.EqualValues(t, http.StatusOK, ctx.Resp.Status())
 		for _, issueID := range testCase.IssueIDs {
-			db.AssertExistsIf(t, testCase.ExpectedAdd, &models.IssueLabel{
+			unittest.AssertExistsIf(t, testCase.ExpectedAdd, &models.IssueLabel{
 				IssueID: issueID,
 				LabelID: testCase.LabelID,
 			})
 		}
-		models.CheckConsistencyFor(t, &models.Label{})
+		unittest.CheckConsistencyFor(t, &models.Label{})
 	}
 }
diff --git a/routers/web/repo/main_test.go b/routers/web/repo/main_test.go
index 832256724987..81e3a8e28135 100644
--- a/routers/web/repo/main_test.go
+++ b/routers/web/repo/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", "..", ".."))
+	unittest.MainTest(m, filepath.Join("..", "..", ".."))
 }
diff --git a/routers/web/repo/migrate.go b/routers/web/repo/migrate.go
index f62f396239d0..f91c344e94b8 100644
--- a/routers/web/repo/migrate.go
+++ b/routers/web/repo/migrate.go
@@ -15,13 +15,13 @@ import (
 	"code.gitea.io/gitea/modules/context"
 	"code.gitea.io/gitea/modules/lfs"
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/modules/task"
 	"code.gitea.io/gitea/modules/util"
 	"code.gitea.io/gitea/modules/web"
 	"code.gitea.io/gitea/services/forms"
+	"code.gitea.io/gitea/services/migrations"
 )
 
 const (
diff --git a/routers/web/repo/projects_test.go b/routers/web/repo/projects_test.go
index d3b78cc77587..62fb0457400b 100644
--- a/routers/web/repo/projects_test.go
+++ b/routers/web/repo/projects_test.go
@@ -7,14 +7,14 @@ package repo
 import (
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/test"
 
 	"github.com/stretchr/testify/assert"
 )
 
 func TestCheckProjectBoardChangePermissions(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1/projects/1/2")
 	test.LoadUser(t, ctx, 2)
 	test.LoadRepo(t, ctx, 1)
diff --git a/routers/web/repo/release_test.go b/routers/web/repo/release_test.go
index 7ac49c012fef..33cf54cdc96e 100644
--- a/routers/web/repo/release_test.go
+++ b/routers/web/repo/release_test.go
@@ -8,7 +8,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/test"
 	"code.gitea.io/gitea/modules/web"
 	"code.gitea.io/gitea/services/forms"
@@ -44,7 +44,7 @@ func TestNewReleasePost(t *testing.T) {
 			},
 		},
 	} {
-		db.PrepareTestEnv(t)
+		unittest.PrepareTestEnv(t)
 
 		ctx := test.MockContext(t, "user2/repo1/releases/new")
 		test.LoadUser(t, ctx, 2)
@@ -52,14 +52,14 @@ func TestNewReleasePost(t *testing.T) {
 		test.LoadGitRepo(t, ctx)
 		web.SetForm(ctx, &testCase.Form)
 		NewReleasePost(ctx)
-		db.AssertExistsAndLoadBean(t, &models.Release{
+		unittest.AssertExistsAndLoadBean(t, &models.Release{
 			RepoID:      1,
 			PublisherID: 2,
 			TagName:     testCase.Form.TagName,
 			Target:      testCase.Form.Target,
 			Title:       testCase.Form.Title,
 			Note:        testCase.Form.Content,
-		}, db.Cond("is_draft=?", len(testCase.Form.Draft) > 0))
+		}, unittest.Cond("is_draft=?", len(testCase.Form.Draft) > 0))
 		ctx.Repo.GitRepo.Close()
 	}
 }
diff --git a/routers/web/repo/setting.go b/routers/web/repo/setting.go
index cad5536e70cd..641052316c26 100644
--- a/routers/web/repo/setting.go
+++ b/routers/web/repo/setting.go
@@ -22,7 +22,6 @@ import (
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/lfs"
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations"
 	"code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/structs"
@@ -34,6 +33,7 @@ import (
 	"code.gitea.io/gitea/routers/utils"
 	"code.gitea.io/gitea/services/forms"
 	"code.gitea.io/gitea/services/mailer"
+	"code.gitea.io/gitea/services/migrations"
 	mirror_service "code.gitea.io/gitea/services/mirror"
 	repo_service "code.gitea.io/gitea/services/repository"
 	wiki_service "code.gitea.io/gitea/services/wiki"
@@ -557,7 +557,7 @@ func SettingsPost(ctx *context.Context) {
 			return
 		}
 
-		if err := repository.ConvertForkToNormalRepository(repo); err != nil {
+		if err := repo_service.ConvertForkToNormalRepository(repo); err != nil {
 			log.Error("Unable to convert repository %-v from fork. Error: %v", repo, err)
 			ctx.ServerError("Convert Fork", err)
 			return
diff --git a/routers/web/repo/settings_test.go b/routers/web/repo/settings_test.go
index a3ed271cce6c..3e8ae2b07e92 100644
--- a/routers/web/repo/settings_test.go
+++ b/routers/web/repo/settings_test.go
@@ -10,7 +10,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/context"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/test"
@@ -43,7 +43,7 @@ func TestAddReadOnlyDeployKey(t *testing.T) {
 	} else {
 		return
 	}
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1/settings/keys")
 
@@ -58,7 +58,7 @@ func TestAddReadOnlyDeployKey(t *testing.T) {
 	DeployKeysPost(ctx)
 	assert.EqualValues(t, http.StatusFound, ctx.Resp.Status())
 
-	db.AssertExistsAndLoadBean(t, &models.DeployKey{
+	unittest.AssertExistsAndLoadBean(t, &models.DeployKey{
 		Name:    addKeyForm.Title,
 		Content: addKeyForm.Content,
 		Mode:    models.AccessModeRead,
@@ -72,7 +72,7 @@ func TestAddReadWriteOnlyDeployKey(t *testing.T) {
 		return
 	}
 
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1/settings/keys")
 
@@ -88,7 +88,7 @@ func TestAddReadWriteOnlyDeployKey(t *testing.T) {
 	DeployKeysPost(ctx)
 	assert.EqualValues(t, http.StatusFound, ctx.Resp.Status())
 
-	db.AssertExistsAndLoadBean(t, &models.DeployKey{
+	unittest.AssertExistsAndLoadBean(t, &models.DeployKey{
 		Name:    addKeyForm.Title,
 		Content: addKeyForm.Content,
 		Mode:    models.AccessModeWrite,
@@ -97,7 +97,7 @@ func TestAddReadWriteOnlyDeployKey(t *testing.T) {
 
 func TestCollaborationPost(t *testing.T) {
 
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1/issues/labels")
 	test.LoadUser(t, ctx, 2)
 	test.LoadUser(t, ctx, 4)
@@ -133,7 +133,7 @@ func TestCollaborationPost(t *testing.T) {
 
 func TestCollaborationPost_InactiveUser(t *testing.T) {
 
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1/issues/labels")
 	test.LoadUser(t, ctx, 2)
 	test.LoadUser(t, ctx, 9)
@@ -157,7 +157,7 @@ func TestCollaborationPost_InactiveUser(t *testing.T) {
 
 func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) {
 
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1/issues/labels")
 	test.LoadUser(t, ctx, 2)
 	test.LoadUser(t, ctx, 4)
@@ -199,7 +199,7 @@ func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) {
 
 func TestCollaborationPost_NonExistentUser(t *testing.T) {
 
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "user2/repo1/issues/labels")
 	test.LoadUser(t, ctx, 2)
 	test.LoadRepo(t, ctx, 1)
@@ -221,7 +221,7 @@ func TestCollaborationPost_NonExistentUser(t *testing.T) {
 }
 
 func TestAddTeamPost(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "org26/repo43")
 
 	ctx.Req.Form.Set("team", "team11")
@@ -261,7 +261,7 @@ func TestAddTeamPost(t *testing.T) {
 }
 
 func TestAddTeamPost_NotAllowed(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "org26/repo43")
 
 	ctx.Req.Form.Set("team", "team11")
@@ -302,7 +302,7 @@ func TestAddTeamPost_NotAllowed(t *testing.T) {
 }
 
 func TestAddTeamPost_AddTeamTwice(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "org26/repo43")
 
 	ctx.Req.Form.Set("team", "team11")
@@ -343,7 +343,7 @@ func TestAddTeamPost_AddTeamTwice(t *testing.T) {
 }
 
 func TestAddTeamPost_NonExistentTeam(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "org26/repo43")
 
 	ctx.Req.Form.Set("team", "team-non-existent")
@@ -376,7 +376,7 @@ func TestAddTeamPost_NonExistentTeam(t *testing.T) {
 }
 
 func TestDeleteTeam(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	ctx := test.MockContext(t, "org3/team1/repo3")
 
 	ctx.Req.Form.Set("id", "2")
diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go
index d463bb601555..12b3aef505ea 100644
--- a/routers/web/repo/view.go
+++ b/routers/web/repo/view.go
@@ -583,6 +583,13 @@ func checkHomeCodeViewable(ctx *context.Context) {
 		if ctx.Repo.Repository.IsBeingCreated() {
 			task, err := models.GetMigratingTask(ctx.Repo.Repository.ID)
 			if err != nil {
+				if models.IsErrTaskDoesNotExist(err) {
+					ctx.Data["Repo"] = ctx.Repo
+					ctx.Data["CloneAddr"] = ""
+					ctx.Data["Failed"] = true
+					ctx.HTML(http.StatusOK, tplMigrating)
+					return
+				}
 				ctx.ServerError("models.GetMigratingTask", err)
 				return
 			}
diff --git a/routers/web/repo/wiki_test.go b/routers/web/repo/wiki_test.go
index 436cb2cf046f..87f2779c1a84 100644
--- a/routers/web/repo/wiki_test.go
+++ b/routers/web/repo/wiki_test.go
@@ -10,7 +10,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/test"
 	"code.gitea.io/gitea/modules/web"
@@ -74,7 +74,7 @@ func assertPagesMetas(t *testing.T, expectedNames []string, metas interface{}) {
 }
 
 func TestWiki(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1/wiki/?action=_pages")
 	ctx.SetParams("*", "Home")
@@ -86,7 +86,7 @@ func TestWiki(t *testing.T) {
 }
 
 func TestWikiPages(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1/wiki/?action=_pages")
 	test.LoadRepo(t, ctx, 1)
@@ -96,7 +96,7 @@ func TestWikiPages(t *testing.T) {
 }
 
 func TestNewWiki(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1/wiki/?action=_new")
 	test.LoadUser(t, ctx, 2)
@@ -111,7 +111,7 @@ func TestNewWikiPost(t *testing.T) {
 		"New page",
 		"&&&&",
 	} {
-		db.PrepareTestEnv(t)
+		unittest.PrepareTestEnv(t)
 
 		ctx := test.MockContext(t, "user2/repo1/wiki/?action=_new")
 		test.LoadUser(t, ctx, 2)
@@ -129,7 +129,7 @@ func TestNewWikiPost(t *testing.T) {
 }
 
 func TestNewWikiPost_ReservedName(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1/wiki/?action=_new")
 	test.LoadUser(t, ctx, 2)
@@ -146,7 +146,7 @@ func TestNewWikiPost_ReservedName(t *testing.T) {
 }
 
 func TestEditWiki(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1/wiki/Home?action=_edit")
 	ctx.SetParams("*", "Home")
@@ -163,7 +163,7 @@ func TestEditWikiPost(t *testing.T) {
 		"Home",
 		"New/",
 	} {
-		db.PrepareTestEnv(t)
+		unittest.PrepareTestEnv(t)
 		ctx := test.MockContext(t, "user2/repo1/wiki/Home?action=_new")
 		ctx.SetParams("*", "Home")
 		test.LoadUser(t, ctx, 2)
@@ -184,7 +184,7 @@ func TestEditWikiPost(t *testing.T) {
 }
 
 func TestDeleteWikiPagePost(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	ctx := test.MockContext(t, "user2/repo1/wiki/Home?action=_delete")
 	test.LoadUser(t, ctx, 2)
@@ -203,7 +203,7 @@ func TestWikiRaw(t *testing.T) {
 		"Page With Spaced Name.md": "text/plain; charset=utf-8",
 		"Page-With-Spaced-Name.md": "text/plain; charset=utf-8",
 	} {
-		db.PrepareTestEnv(t)
+		unittest.PrepareTestEnv(t)
 
 		ctx := test.MockContext(t, "user2/repo1/wiki/raw/"+filepath)
 		ctx.SetParams("*", filepath)
diff --git a/routers/web/user/home_test.go b/routers/web/user/home_test.go
index daf473b270c0..cd599abd047e 100644
--- a/routers/web/user/home_test.go
+++ b/routers/web/user/home_test.go
@@ -9,7 +9,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/test"
 
@@ -19,7 +19,7 @@ import (
 func TestArchivedIssues(t *testing.T) {
 	// Arrange
 	setting.UI.IssuePagingNum = 1
-	assert.NoError(t, db.LoadFixtures())
+	assert.NoError(t, unittest.LoadFixtures())
 
 	ctx := test.MockContext(t, "issues")
 	test.LoadUser(t, ctx, 30)
@@ -52,7 +52,7 @@ func TestArchivedIssues(t *testing.T) {
 
 func TestIssues(t *testing.T) {
 	setting.UI.IssuePagingNum = 1
-	assert.NoError(t, db.LoadFixtures())
+	assert.NoError(t, unittest.LoadFixtures())
 
 	ctx := test.MockContext(t, "issues")
 	test.LoadUser(t, ctx, 2)
@@ -68,7 +68,7 @@ func TestIssues(t *testing.T) {
 
 func TestPulls(t *testing.T) {
 	setting.UI.IssuePagingNum = 20
-	assert.NoError(t, db.LoadFixtures())
+	assert.NoError(t, unittest.LoadFixtures())
 
 	ctx := test.MockContext(t, "pulls")
 	test.LoadUser(t, ctx, 2)
@@ -81,7 +81,7 @@ func TestPulls(t *testing.T) {
 
 func TestMilestones(t *testing.T) {
 	setting.UI.IssuePagingNum = 1
-	assert.NoError(t, db.LoadFixtures())
+	assert.NoError(t, unittest.LoadFixtures())
 
 	ctx := test.MockContext(t, "milestones")
 	test.LoadUser(t, ctx, 2)
@@ -100,7 +100,7 @@ func TestMilestones(t *testing.T) {
 
 func TestMilestonesForSpecificRepo(t *testing.T) {
 	setting.UI.IssuePagingNum = 1
-	assert.NoError(t, db.LoadFixtures())
+	assert.NoError(t, unittest.LoadFixtures())
 
 	ctx := test.MockContext(t, "milestones")
 	test.LoadUser(t, ctx, 2)
diff --git a/routers/web/user/main_test.go b/routers/web/user/main_test.go
index 272e4b8b2111..77b48d89fb86 100644
--- a/routers/web/user/main_test.go
+++ b/routers/web/user/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", "..", ".."))
+	unittest.MainTest(m, filepath.Join("..", "..", ".."))
 }
diff --git a/routers/web/user/oauth_test.go b/routers/web/user/oauth_test.go
index 27d339b778ea..dfdaa9a1ed0e 100644
--- a/routers/web/user/oauth_test.go
+++ b/routers/web/user/oauth_test.go
@@ -8,8 +8,8 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
 	"code.gitea.io/gitea/models/login"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/services/auth/source/oauth2"
 
 	"github.com/golang-jwt/jwt"
@@ -41,7 +41,7 @@ func createAndParseToken(t *testing.T, grant *login.OAuth2Grant) *oauth2.OIDCTok
 }
 
 func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
 	grants, err := login.GetOAuth2GrantsByUserID(3)
 	assert.NoError(t, err)
@@ -58,7 +58,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) {
 	assert.Empty(t, oidcToken.Email)
 	assert.False(t, oidcToken.EmailVerified)
 
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User)
 	grants, err = login.GetOAuth2GrantsByUserID(user.ID)
 	assert.NoError(t, err)
 	assert.Len(t, grants, 1)
diff --git a/routers/web/user/setting/account_test.go b/routers/web/user/setting/account_test.go
index bfb7ac48726f..cd5c77795ea9 100644
--- a/routers/web/user/setting/account_test.go
+++ b/routers/web/user/setting/account_test.go
@@ -8,7 +8,7 @@ import (
 	"net/http"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/test"
 	"code.gitea.io/gitea/modules/web"
@@ -81,7 +81,7 @@ func TestChangePassword(t *testing.T) {
 			PasswordComplexity: pcLU,
 		},
 	} {
-		db.PrepareTestEnv(t)
+		unittest.PrepareTestEnv(t)
 		ctx := test.MockContext(t, "user/settings/security")
 		test.LoadUser(t, ctx, 2)
 		test.LoadRepo(t, ctx, 1)
diff --git a/routers/web/user/setting/adopt.go b/routers/web/user/setting/adopt.go
index e45a8a132465..948cc1e9366c 100644
--- a/routers/web/user/setting/adopt.go
+++ b/routers/web/user/setting/adopt.go
@@ -9,9 +9,9 @@ import (
 
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/modules/context"
-	"code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/util"
+	repo_service "code.gitea.io/gitea/services/repository"
 )
 
 // AdoptOrDeleteRepository adopts or deletes a repository
@@ -27,7 +27,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) {
 	action := ctx.FormString("action")
 
 	ctxUser := ctx.User
-	root := filepath.Join(models.UserPath(ctxUser.LowerName))
+	root := models.UserPath(ctxUser.LowerName)
 
 	// check not a repo
 	has, err := models.IsRepositoryExist(ctxUser, dir)
@@ -44,7 +44,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) {
 	if has || !isDir {
 		// Fallthrough to failure mode
 	} else if action == "adopt" && allowAdopt {
-		if _, err := repository.AdoptRepository(ctxUser, ctxUser, models.CreateRepoOptions{
+		if _, err := repo_service.AdoptRepository(ctxUser, ctxUser, models.CreateRepoOptions{
 			Name:      dir,
 			IsPrivate: true,
 		}); err != nil {
@@ -53,7 +53,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) {
 		}
 		ctx.Flash.Success(ctx.Tr("repo.adopt_preexisting_success", dir))
 	} else if action == "delete" && allowDelete {
-		if err := repository.DeleteUnadoptedRepository(ctxUser, ctxUser, dir); err != nil {
+		if err := repo_service.DeleteUnadoptedRepository(ctxUser, ctxUser, dir); err != nil {
 			ctx.ServerError("repository.AdoptRepository", err)
 			return
 		}
diff --git a/routers/web/user/setting/main_test.go b/routers/web/user/setting/main_test.go
index a0fbe55ee17e..b6ed7f5b1803 100644
--- a/routers/web/user/setting/main_test.go
+++ b/routers/web/user/setting/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", "..", "..", ".."))
+	unittest.MainTest(m, filepath.Join("..", "..", "..", ".."))
 }
diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go
index 4a0900615099..d7aa3264c58a 100644
--- a/routers/web/user/setting/profile.go
+++ b/routers/web/user/setting/profile.go
@@ -250,7 +250,7 @@ func Repos(ctx *context.Context) {
 		repoNames := make([]string, 0, setting.UI.Admin.UserPagingNum)
 		repos := map[string]*models.Repository{}
 		// We're going to iterate by pagesize.
-		root := filepath.Join(models.UserPath(ctxUser.Name))
+		root := models.UserPath(ctxUser.Name)
 		if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
 			if err != nil {
 				if os.IsNotExist(err) {
diff --git a/routers/web/user/task.go b/routers/web/user/task.go
index c71d43523393..4dbd1b8537bf 100644
--- a/routers/web/user/task.go
+++ b/routers/web/user/task.go
@@ -6,6 +6,7 @@ package user
 
 import (
 	"net/http"
+	"strconv"
 
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/modules/context"
@@ -16,6 +17,12 @@ import (
 func TaskStatus(ctx *context.Context) {
 	task, opts, err := models.GetMigratingTaskByID(ctx.ParamsInt64("task"), ctx.User.ID)
 	if err != nil {
+		if models.IsErrTaskDoesNotExist(err) {
+			ctx.JSON(http.StatusNotFound, map[string]interface{}{
+				"error": "task `" + strconv.FormatInt(ctx.ParamsInt64("task"), 10) + "` does not exist",
+			})
+			return
+		}
 		ctx.JSON(http.StatusInternalServerError, map[string]interface{}{
 			"err": err,
 		})
diff --git a/services/archiver/archiver_test.go b/services/archiver/archiver_test.go
index 94b0423d9bae..67484fdc786a 100644
--- a/services/archiver/archiver_test.go
+++ b/services/archiver/archiver_test.go
@@ -9,14 +9,14 @@ import (
 	"testing"
 	"time"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/test"
 
 	"github.com/stretchr/testify/assert"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
 
 func waitForCount(t *testing.T, num int) {
@@ -24,7 +24,7 @@ func waitForCount(t *testing.T, num int) {
 }
 
 func TestArchive_Basic(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
 	ctx := test.MockContext(t, "user27/repo49")
 	firstCommit, secondCommit := "51f84af23134", "aacbdfe9e1c4"
diff --git a/services/attachment/attachment_test.go b/services/attachment/attachment_test.go
index 3e9e55a8f2fe..5bb5db11ec66 100644
--- a/services/attachment/attachment_test.go
+++ b/services/attachment/attachment_test.go
@@ -10,19 +10,19 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 
 	"github.com/stretchr/testify/assert"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
 
 func TestUploadAttachment(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
 
 	fPath := "./attachment_test.go"
 	f, err := os.Open(fPath)
diff --git a/services/auth/basic.go b/services/auth/basic.go
index 0c400b6b5329..d7f889cbdc8e 100644
--- a/services/auth/basic.go
+++ b/services/auth/basic.go
@@ -50,7 +50,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore
 	}
 
 	auths := strings.SplitN(baHead, " ", 2)
-	if len(auths) != 2 || (auths[0] != "Basic" && auths[0] != "basic") {
+	if len(auths) != 2 || (strings.ToLower(auths[0]) != "basic") {
 		return nil
 	}
 
diff --git a/modules/cron/cron.go b/services/cron/cron.go
similarity index 100%
rename from modules/cron/cron.go
rename to services/cron/cron.go
diff --git a/modules/cron/setting.go b/services/cron/setting.go
similarity index 100%
rename from modules/cron/setting.go
rename to services/cron/setting.go
diff --git a/modules/cron/tasks.go b/services/cron/tasks.go
similarity index 100%
rename from modules/cron/tasks.go
rename to services/cron/tasks.go
diff --git a/modules/cron/tasks_basic.go b/services/cron/tasks_basic.go
similarity index 98%
rename from modules/cron/tasks_basic.go
rename to services/cron/tasks_basic.go
index a42c031b361f..57fb399d4e19 100644
--- a/modules/cron/tasks_basic.go
+++ b/services/cron/tasks_basic.go
@@ -10,10 +10,10 @@ import (
 
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/models/webhook"
-	"code.gitea.io/gitea/modules/migrations"
 	repository_service "code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/services/auth"
+	"code.gitea.io/gitea/services/migrations"
 	mirror_service "code.gitea.io/gitea/services/mirror"
 )
 
diff --git a/modules/cron/tasks_extended.go b/services/cron/tasks_extended.go
similarity index 97%
rename from modules/cron/tasks_extended.go
rename to services/cron/tasks_extended.go
index 9a37c40fafe7..4ddcd44537ed 100644
--- a/modules/cron/tasks_extended.go
+++ b/services/cron/tasks_extended.go
@@ -12,6 +12,7 @@ import (
 	repo_module "code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/updatechecker"
+	repo_service "code.gitea.io/gitea/services/repository"
 )
 
 func registerDeleteInactiveUsers() {
@@ -34,7 +35,7 @@ func registerDeleteRepositoryArchives() {
 		RunAtStart: false,
 		Schedule:   "@annually",
 	}, func(ctx context.Context, _ *models.User, _ Config) error {
-		return repo_module.DeleteRepositoryArchives(ctx)
+		return repo_service.DeleteRepositoryArchives(ctx)
 	})
 }
 
diff --git a/services/gitdiff/gitdiff_test.go b/services/gitdiff/gitdiff_test.go
index 6decb59b64b5..aefd396ebbae 100644
--- a/services/gitdiff/gitdiff_test.go
+++ b/services/gitdiff/gitdiff_test.go
@@ -13,7 +13,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/highlight"
 	"code.gitea.io/gitea/modules/json"
@@ -493,10 +493,10 @@ func setupDefaultDiff() *Diff {
 	}
 }
 func TestDiff_LoadComments(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
+	issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
 	diff := setupDefaultDiff()
 	assert.NoError(t, diff.LoadComments(issue, user))
 	assert.Len(t, diff.Files[0].Sections[0].Lines[0].Comments, 2)
diff --git a/services/gitdiff/main_test.go b/services/gitdiff/main_test.go
index 1b83cbd684a0..8c76e7e1530f 100644
--- a/services/gitdiff/main_test.go
+++ b/services/gitdiff/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
diff --git a/services/issue/assignee_test.go b/services/issue/assignee_test.go
index 5684ed6d8997..b0bbe42273d1 100644
--- a/services/issue/assignee_test.go
+++ b/services/issue/assignee_test.go
@@ -8,12 +8,12 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"github.com/stretchr/testify/assert"
 )
 
 func TestDeleteNotPassedAssignee(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
 	// Fake issue with assignees
 	issue, err := models.GetIssueWithAttrsByID(1)
diff --git a/services/issue/label_test.go b/services/issue/label_test.go
index 8a3a77ecb0a6..fa6ad613b694 100644
--- a/services/issue/label_test.go
+++ b/services/issue/label_test.go
@@ -8,7 +8,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"github.com/stretchr/testify/assert"
 )
 
@@ -24,16 +24,16 @@ func TestIssue_AddLabels(t *testing.T) {
 		{2, []int64{}, 1},     // pull-request, empty
 	}
 	for _, test := range tests {
-		assert.NoError(t, db.PrepareTestDatabase())
-		issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: test.issueID}).(*models.Issue)
+		assert.NoError(t, unittest.PrepareTestDatabase())
+		issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: test.issueID}).(*models.Issue)
 		labels := make([]*models.Label, len(test.labelIDs))
 		for i, labelID := range test.labelIDs {
-			labels[i] = db.AssertExistsAndLoadBean(t, &models.Label{ID: labelID}).(*models.Label)
+			labels[i] = unittest.AssertExistsAndLoadBean(t, &models.Label{ID: labelID}).(*models.Label)
 		}
-		doer := db.AssertExistsAndLoadBean(t, &models.User{ID: test.doerID}).(*models.User)
+		doer := unittest.AssertExistsAndLoadBean(t, &models.User{ID: test.doerID}).(*models.User)
 		assert.NoError(t, AddLabels(issue, doer, labels))
 		for _, labelID := range test.labelIDs {
-			db.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: test.issueID, LabelID: labelID})
+			unittest.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: test.issueID, LabelID: labelID})
 		}
 	}
 }
@@ -50,11 +50,11 @@ func TestIssue_AddLabel(t *testing.T) {
 		{2, 1, 2}, // pull-request, already-added label
 	}
 	for _, test := range tests {
-		assert.NoError(t, db.PrepareTestDatabase())
-		issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: test.issueID}).(*models.Issue)
-		label := db.AssertExistsAndLoadBean(t, &models.Label{ID: test.labelID}).(*models.Label)
-		doer := db.AssertExistsAndLoadBean(t, &models.User{ID: test.doerID}).(*models.User)
+		assert.NoError(t, unittest.PrepareTestDatabase())
+		issue := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: test.issueID}).(*models.Issue)
+		label := unittest.AssertExistsAndLoadBean(t, &models.Label{ID: test.labelID}).(*models.Label)
+		doer := unittest.AssertExistsAndLoadBean(t, &models.User{ID: test.doerID}).(*models.User)
 		assert.NoError(t, AddLabel(issue, doer, label))
-		db.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: test.issueID, LabelID: test.labelID})
+		unittest.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: test.issueID, LabelID: test.labelID})
 	}
 }
diff --git a/services/issue/main_test.go b/services/issue/main_test.go
index 1349837949d0..cbcfd08a4979 100644
--- a/services/issue/main_test.go
+++ b/services/issue/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
diff --git a/services/mailer/mail_test.go b/services/mailer/mail_test.go
index cd730a13a445..94ff5a65ae90 100644
--- a/services/mailer/mail_test.go
+++ b/services/mailer/mail_test.go
@@ -11,7 +11,7 @@ import (
 	texttmpl "text/template"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/setting"
 
 	"github.com/stretchr/testify/assert"
@@ -41,7 +41,7 @@ const bodyTpl = `
 `
 
 func prepareMailerTest(t *testing.T) (doer *models.User, repo *models.Repository, issue *models.Issue, comment *models.Comment) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 	var mailService = setting.Mailer{
 		From: "test@gitea.com",
 	}
@@ -49,11 +49,11 @@ func prepareMailerTest(t *testing.T) (doer *models.User, repo *models.Repository
 	setting.MailService = &mailService
 	setting.Domain = "localhost"
 
-	doer = db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
-	repo = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1, Owner: doer}).(*models.Repository)
-	issue = db.AssertExistsAndLoadBean(t, &models.Issue{ID: 1, Repo: repo, Poster: doer}).(*models.Issue)
+	doer = unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo = unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1, Owner: doer}).(*models.Repository)
+	issue = unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 1, Repo: repo, Poster: doer}).(*models.Issue)
 	assert.NoError(t, issue.LoadRepo())
-	comment = db.AssertExistsAndLoadBean(t, &models.Comment{ID: 2, Issue: issue}).(*models.Comment)
+	comment = unittest.AssertExistsAndLoadBean(t, &models.Comment{ID: 2, Issue: issue}).(*models.Comment)
 	return
 }
 
@@ -144,8 +144,8 @@ func TestTemplateSelection(t *testing.T) {
 		Content: "test body", Comment: comment}, recipients, false, "TestTemplateSelection")
 	expect(t, msg, "issue/default/subject", "issue/default/body")
 
-	pull := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2, Repo: repo, Poster: doer}).(*models.Issue)
-	comment = db.AssertExistsAndLoadBean(t, &models.Comment{ID: 4, Issue: pull}).(*models.Comment)
+	pull := unittest.AssertExistsAndLoadBean(t, &models.Issue{ID: 2, Repo: repo, Poster: doer}).(*models.Issue)
+	comment = unittest.AssertExistsAndLoadBean(t, &models.Comment{ID: 4, Issue: pull}).(*models.Comment)
 	msg = testComposeIssueCommentMessage(t, &mailCommentContext{Issue: pull, Doer: doer, ActionType: models.ActionCommentPull,
 		Content: "test body", Comment: comment}, recipients, false, "TestTemplateSelection")
 	expect(t, msg, "pull/comment/subject", "pull/comment/body")
diff --git a/services/mailer/main_test.go b/services/mailer/main_test.go
index 2fbe9c54a93c..ae3b2c12b4ca 100644
--- a/services/mailer/main_test.go
+++ b/services/mailer/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
diff --git a/modules/migrations/dump.go b/services/migrations/dump.go
similarity index 99%
rename from modules/migrations/dump.go
rename to services/migrations/dump.go
index 6b995c0dea8c..6e3596230fda 100644
--- a/modules/migrations/dump.go
+++ b/services/migrations/dump.go
@@ -20,7 +20,7 @@ import (
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/structs"
 
diff --git a/modules/migrations/error.go b/services/migrations/error.go
similarity index 100%
rename from modules/migrations/error.go
rename to services/migrations/error.go
diff --git a/modules/migrations/git.go b/services/migrations/git.go
similarity index 96%
rename from modules/migrations/git.go
rename to services/migrations/git.go
index 7e4194547499..37ffb674c5c8 100644
--- a/modules/migrations/git.go
+++ b/services/migrations/git.go
@@ -7,7 +7,7 @@ package migrations
 import (
 	"context"
 
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 )
 
 var (
diff --git a/services/migrations/gitbucket.go b/services/migrations/gitbucket.go
new file mode 100644
index 000000000000..27ed584aa239
--- /dev/null
+++ b/services/migrations/gitbucket.go
@@ -0,0 +1,72 @@
+// Copyright 2021 The Gitea Authors. All rights reserved.
+// Use of this source code is governed by a MIT-style
+// license that can be found in the LICENSE file.
+
+package migrations
+
+import (
+	"context"
+	"net/url"
+	"strings"
+
+	base "code.gitea.io/gitea/modules/migration"
+	"code.gitea.io/gitea/modules/structs"
+)
+
+var (
+	_ base.Downloader        = &GitBucketDownloader{}
+	_ base.DownloaderFactory = &GitBucketDownloaderFactory{}
+)
+
+func init() {
+	RegisterDownloaderFactory(&GitBucketDownloaderFactory{})
+}
+
+// GitBucketDownloaderFactory defines a GitBucket downloader factory
+type GitBucketDownloaderFactory struct {
+}
+
+// New returns a Downloader related to this factory according MigrateOptions
+func (f *GitBucketDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) {
+	u, err := url.Parse(opts.CloneAddr)
+	if err != nil {
+		return nil, err
+	}
+
+	baseURL := u.Scheme + "://" + u.Host
+	fields := strings.Split(u.Path, "/")
+	oldOwner := fields[1]
+	oldName := strings.TrimSuffix(fields[2], ".git")
+
+	return NewGitBucketDownloader(ctx, baseURL, opts.AuthUsername, opts.AuthPassword, opts.AuthToken, oldOwner, oldName), nil
+}
+
+// GitServiceType returns the type of git service
+func (f *GitBucketDownloaderFactory) GitServiceType() structs.GitServiceType {
+	return structs.GitBucketService
+}
+
+// GitBucketDownloader implements a Downloader interface to get repository information
+// from GitBucket via GithubDownloader
+type GitBucketDownloader struct {
+	*GithubDownloaderV3
+}
+
+// NewGitBucketDownloader creates a GitBucket downloader
+func NewGitBucketDownloader(ctx context.Context, baseURL, userName, password, token, repoOwner, repoName string) *GitBucketDownloader {
+	githubDownloader := NewGithubDownloaderV3(ctx, baseURL, userName, password, token, repoOwner, repoName)
+	githubDownloader.SkipReactions = true
+	return &GitBucketDownloader{
+		githubDownloader,
+	}
+}
+
+// SupportGetRepoComments return true if it supports get repo comments
+func (g *GitBucketDownloader) SupportGetRepoComments() bool {
+	return false
+}
+
+// GetReviews is not supported
+func (g *GitBucketDownloader) GetReviews(context base.IssueContext) ([]*base.Review, error) {
+	return nil, &base.ErrNotSupported{Entity: "Reviews"}
+}
diff --git a/modules/migrations/gitea_downloader.go b/services/migrations/gitea_downloader.go
similarity index 99%
rename from modules/migrations/gitea_downloader.go
rename to services/migrations/gitea_downloader.go
index d8a3c84678ef..51ef0292df7f 100644
--- a/modules/migrations/gitea_downloader.go
+++ b/services/migrations/gitea_downloader.go
@@ -17,7 +17,7 @@ import (
 
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/proxy"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/structs"
diff --git a/modules/migrations/gitea_downloader_test.go b/services/migrations/gitea_downloader_test.go
similarity index 99%
rename from modules/migrations/gitea_downloader_test.go
rename to services/migrations/gitea_downloader_test.go
index 71bdecaeaddd..2c70dc421356 100644
--- a/modules/migrations/gitea_downloader_test.go
+++ b/services/migrations/gitea_downloader_test.go
@@ -12,7 +12,7 @@ import (
 	"testing"
 	"time"
 
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 
 	"github.com/stretchr/testify/assert"
 )
diff --git a/modules/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go
similarity index 99%
rename from modules/migrations/gitea_uploader.go
rename to services/migrations/gitea_uploader.go
index d62ce80c77f3..5eecaf6c56e4 100644
--- a/modules/migrations/gitea_uploader.go
+++ b/services/migrations/gitea_uploader.go
@@ -19,7 +19,7 @@ import (
 	"code.gitea.io/gitea/models/db"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	repo_module "code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/storage"
diff --git a/modules/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go
similarity index 90%
rename from modules/migrations/gitea_uploader_test.go
rename to services/migrations/gitea_uploader_test.go
index b8b947961f4b..9b04004cd73b 100644
--- a/modules/migrations/gitea_uploader_test.go
+++ b/services/migrations/gitea_uploader_test.go
@@ -12,8 +12,9 @@ import (
 
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/graceful"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/modules/util"
 
@@ -24,9 +25,9 @@ func TestGiteaUploadRepo(t *testing.T) {
 	// FIXME: Since no accesskey or user/password will trigger rate limit of github, just skip
 	t.Skip()
 
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
 
 	var (
 		downloader = NewGithubDownloaderV3(context.Background(), "https://github.com", "", "", "", "go-xorm", "builder")
@@ -51,7 +52,7 @@ func TestGiteaUploadRepo(t *testing.T) {
 	}, nil)
 	assert.NoError(t, err)
 
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{OwnerID: user.ID, Name: repoName}).(*models.Repository)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{OwnerID: user.ID, Name: repoName}).(*models.Repository)
 	assert.True(t, repo.HasWiki())
 	assert.EqualValues(t, models.RepositoryReady, repo.Status)
 
diff --git a/modules/migrations/github.go b/services/migrations/github.go
similarity index 88%
rename from modules/migrations/github.go
rename to services/migrations/github.go
index 874cd054394f..3043d7cf75ad 100644
--- a/modules/migrations/github.go
+++ b/services/migrations/github.go
@@ -17,7 +17,7 @@ import (
 	"time"
 
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/proxy"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/structs"
@@ -68,15 +68,16 @@ func (f *GithubDownloaderV3Factory) GitServiceType() structs.GitServiceType {
 // from github via APIv3
 type GithubDownloaderV3 struct {
 	base.NullDownloader
-	ctx          context.Context
-	clients      []*github.Client
-	repoOwner    string
-	repoName     string
-	userName     string
-	password     string
-	rates        []*github.Rate
-	curClientIdx int
-	maxPerPage   int
+	ctx           context.Context
+	clients       []*github.Client
+	repoOwner     string
+	repoName      string
+	userName      string
+	password      string
+	rates         []*github.Rate
+	curClientIdx  int
+	maxPerPage    int
+	SkipReactions bool
 }
 
 // NewGithubDownloaderV3 creates a github Downloader via github v3 API
@@ -428,25 +429,27 @@ func (g *GithubDownloaderV3) GetIssues(page, perPage int) ([]*base.Issue, bool,
 
 		// get reactions
 		var reactions []*base.Reaction
-		for i := 1; ; i++ {
-			g.waitAndPickClient()
-			res, resp, err := g.getClient().Reactions.ListIssueReactions(g.ctx, g.repoOwner, g.repoName, issue.GetNumber(), &github.ListOptions{
-				Page:    i,
-				PerPage: perPage,
-			})
-			if err != nil {
-				return nil, false, err
-			}
-			g.setRate(&resp.Rate)
-			if len(res) == 0 {
-				break
-			}
-			for _, reaction := range res {
-				reactions = append(reactions, &base.Reaction{
-					UserID:   reaction.User.GetID(),
-					UserName: reaction.User.GetLogin(),
-					Content:  reaction.GetContent(),
+		if !g.SkipReactions {
+			for i := 1; ; i++ {
+				g.waitAndPickClient()
+				res, resp, err := g.getClient().Reactions.ListIssueReactions(g.ctx, g.repoOwner, g.repoName, issue.GetNumber(), &github.ListOptions{
+					Page:    i,
+					PerPage: perPage,
 				})
+				if err != nil {
+					return nil, false, err
+				}
+				g.setRate(&resp.Rate)
+				if len(res) == 0 {
+					break
+				}
+				for _, reaction := range res {
+					reactions = append(reactions, &base.Reaction{
+						UserID:   reaction.User.GetID(),
+						UserName: reaction.User.GetLogin(),
+						Content:  reaction.GetContent(),
+					})
+				}
 			}
 		}
 
@@ -516,25 +519,27 @@ func (g *GithubDownloaderV3) getComments(issueContext base.IssueContext) ([]*bas
 		for _, comment := range comments {
 			// get reactions
 			var reactions []*base.Reaction
-			for i := 1; ; i++ {
-				g.waitAndPickClient()
-				res, resp, err := g.getClient().Reactions.ListIssueCommentReactions(g.ctx, g.repoOwner, g.repoName, comment.GetID(), &github.ListOptions{
-					Page:    i,
-					PerPage: g.maxPerPage,
-				})
-				if err != nil {
-					return nil, err
-				}
-				g.setRate(&resp.Rate)
-				if len(res) == 0 {
-					break
-				}
-				for _, reaction := range res {
-					reactions = append(reactions, &base.Reaction{
-						UserID:   reaction.User.GetID(),
-						UserName: reaction.User.GetLogin(),
-						Content:  reaction.GetContent(),
+			if !g.SkipReactions {
+				for i := 1; ; i++ {
+					g.waitAndPickClient()
+					res, resp, err := g.getClient().Reactions.ListIssueCommentReactions(g.ctx, g.repoOwner, g.repoName, comment.GetID(), &github.ListOptions{
+						Page:    i,
+						PerPage: g.maxPerPage,
 					})
+					if err != nil {
+						return nil, err
+					}
+					g.setRate(&resp.Rate)
+					if len(res) == 0 {
+						break
+					}
+					for _, reaction := range res {
+						reactions = append(reactions, &base.Reaction{
+							UserID:   reaction.User.GetID(),
+							UserName: reaction.User.GetLogin(),
+							Content:  reaction.GetContent(),
+						})
+					}
 				}
 			}
 
@@ -588,25 +593,27 @@ func (g *GithubDownloaderV3) GetAllComments(page, perPage int) ([]*base.Comment,
 	for _, comment := range comments {
 		// get reactions
 		var reactions []*base.Reaction
-		for i := 1; ; i++ {
-			g.waitAndPickClient()
-			res, resp, err := g.getClient().Reactions.ListIssueCommentReactions(g.ctx, g.repoOwner, g.repoName, comment.GetID(), &github.ListOptions{
-				Page:    i,
-				PerPage: g.maxPerPage,
-			})
-			if err != nil {
-				return nil, false, err
-			}
-			g.setRate(&resp.Rate)
-			if len(res) == 0 {
-				break
-			}
-			for _, reaction := range res {
-				reactions = append(reactions, &base.Reaction{
-					UserID:   reaction.User.GetID(),
-					UserName: reaction.User.GetLogin(),
-					Content:  reaction.GetContent(),
+		if !g.SkipReactions {
+			for i := 1; ; i++ {
+				g.waitAndPickClient()
+				res, resp, err := g.getClient().Reactions.ListIssueCommentReactions(g.ctx, g.repoOwner, g.repoName, comment.GetID(), &github.ListOptions{
+					Page:    i,
+					PerPage: g.maxPerPage,
 				})
+				if err != nil {
+					return nil, false, err
+				}
+				g.setRate(&resp.Rate)
+				if len(res) == 0 {
+					break
+				}
+				for _, reaction := range res {
+					reactions = append(reactions, &base.Reaction{
+						UserID:   reaction.User.GetID(),
+						UserName: reaction.User.GetLogin(),
+						Content:  reaction.GetContent(),
+					})
+				}
 			}
 		}
 		idx := strings.LastIndex(*comment.IssueURL, "/")
@@ -656,25 +663,27 @@ func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullReq
 
 		// get reactions
 		var reactions []*base.Reaction
-		for i := 1; ; i++ {
-			g.waitAndPickClient()
-			res, resp, err := g.getClient().Reactions.ListIssueReactions(g.ctx, g.repoOwner, g.repoName, pr.GetNumber(), &github.ListOptions{
-				Page:    i,
-				PerPage: perPage,
-			})
-			if err != nil {
-				return nil, false, err
-			}
-			g.setRate(&resp.Rate)
-			if len(res) == 0 {
-				break
-			}
-			for _, reaction := range res {
-				reactions = append(reactions, &base.Reaction{
-					UserID:   reaction.User.GetID(),
-					UserName: reaction.User.GetLogin(),
-					Content:  reaction.GetContent(),
+		if !g.SkipReactions {
+			for i := 1; ; i++ {
+				g.waitAndPickClient()
+				res, resp, err := g.getClient().Reactions.ListIssueReactions(g.ctx, g.repoOwner, g.repoName, pr.GetNumber(), &github.ListOptions{
+					Page:    i,
+					PerPage: perPage,
 				})
+				if err != nil {
+					return nil, false, err
+				}
+				g.setRate(&resp.Rate)
+				if len(res) == 0 {
+					break
+				}
+				for _, reaction := range res {
+					reactions = append(reactions, &base.Reaction{
+						UserID:   reaction.User.GetID(),
+						UserName: reaction.User.GetLogin(),
+						Content:  reaction.GetContent(),
+					})
+				}
 			}
 		}
 
@@ -737,25 +746,27 @@ func (g *GithubDownloaderV3) convertGithubReviewComments(cs []*github.PullReques
 	for _, c := range cs {
 		// get reactions
 		var reactions []*base.Reaction
-		for i := 1; ; i++ {
-			g.waitAndPickClient()
-			res, resp, err := g.getClient().Reactions.ListPullRequestCommentReactions(g.ctx, g.repoOwner, g.repoName, c.GetID(), &github.ListOptions{
-				Page:    i,
-				PerPage: g.maxPerPage,
-			})
-			if err != nil {
-				return nil, err
-			}
-			g.setRate(&resp.Rate)
-			if len(res) == 0 {
-				break
-			}
-			for _, reaction := range res {
-				reactions = append(reactions, &base.Reaction{
-					UserID:   reaction.User.GetID(),
-					UserName: reaction.User.GetLogin(),
-					Content:  reaction.GetContent(),
+		if !g.SkipReactions {
+			for i := 1; ; i++ {
+				g.waitAndPickClient()
+				res, resp, err := g.getClient().Reactions.ListPullRequestCommentReactions(g.ctx, g.repoOwner, g.repoName, c.GetID(), &github.ListOptions{
+					Page:    i,
+					PerPage: g.maxPerPage,
 				})
+				if err != nil {
+					return nil, err
+				}
+				g.setRate(&resp.Rate)
+				if len(res) == 0 {
+					break
+				}
+				for _, reaction := range res {
+					reactions = append(reactions, &base.Reaction{
+						UserID:   reaction.User.GetID(),
+						UserName: reaction.User.GetLogin(),
+						Content:  reaction.GetContent(),
+					})
+				}
 			}
 		}
 
diff --git a/modules/migrations/github_test.go b/services/migrations/github_test.go
similarity index 99%
rename from modules/migrations/github_test.go
rename to services/migrations/github_test.go
index 4a53f20a76dd..c8249dfdb2ba 100644
--- a/modules/migrations/github_test.go
+++ b/services/migrations/github_test.go
@@ -11,7 +11,7 @@ import (
 	"testing"
 	"time"
 
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 
 	"github.com/stretchr/testify/assert"
 )
diff --git a/modules/migrations/gitlab.go b/services/migrations/gitlab.go
similarity index 99%
rename from modules/migrations/gitlab.go
rename to services/migrations/gitlab.go
index 91ba073d18f4..e285519aa54b 100644
--- a/modules/migrations/gitlab.go
+++ b/services/migrations/gitlab.go
@@ -17,7 +17,7 @@ import (
 	"time"
 
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/proxy"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/structs"
diff --git a/modules/migrations/gitlab_test.go b/services/migrations/gitlab_test.go
similarity index 99%
rename from modules/migrations/gitlab_test.go
rename to services/migrations/gitlab_test.go
index c3ee8118c55d..f6dc7510cbed 100644
--- a/modules/migrations/gitlab_test.go
+++ b/services/migrations/gitlab_test.go
@@ -12,7 +12,7 @@ import (
 	"testing"
 	"time"
 
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 
 	"github.com/stretchr/testify/assert"
 )
diff --git a/modules/migrations/gogs.go b/services/migrations/gogs.go
similarity index 99%
rename from modules/migrations/gogs.go
rename to services/migrations/gogs.go
index 06c944278b43..9473bf8b4874 100644
--- a/modules/migrations/gogs.go
+++ b/services/migrations/gogs.go
@@ -14,7 +14,7 @@ import (
 	"time"
 
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/proxy"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/structs"
diff --git a/modules/migrations/gogs_test.go b/services/migrations/gogs_test.go
similarity index 98%
rename from modules/migrations/gogs_test.go
rename to services/migrations/gogs_test.go
index 8816fab44fbc..57eda59b928f 100644
--- a/modules/migrations/gogs_test.go
+++ b/services/migrations/gogs_test.go
@@ -11,7 +11,7 @@ import (
 	"testing"
 	"time"
 
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 
 	"github.com/stretchr/testify/assert"
 )
diff --git a/modules/migrations/main_test.go b/services/migrations/main_test.go
similarity index 98%
rename from modules/migrations/main_test.go
rename to services/migrations/main_test.go
index 5b29230659aa..660f6dd845ae 100644
--- a/modules/migrations/main_test.go
+++ b/services/migrations/main_test.go
@@ -10,14 +10,14 @@ import (
 	"testing"
 	"time"
 
-	"code.gitea.io/gitea/models/db"
-	"code.gitea.io/gitea/modules/migrations/base"
+	"code.gitea.io/gitea/models/unittest"
+	base "code.gitea.io/gitea/modules/migration"
 
 	"github.com/stretchr/testify/assert"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
 
 func timePtr(t time.Time) *time.Time {
diff --git a/modules/migrations/migrate.go b/services/migrations/migrate.go
similarity index 99%
rename from modules/migrations/migrate.go
rename to services/migrations/migrate.go
index dbe69259f4ec..21be2d3b0ddd 100644
--- a/modules/migrations/migrate.go
+++ b/services/migrations/migrate.go
@@ -16,7 +16,7 @@ import (
 	"code.gitea.io/gitea/models"
 	"code.gitea.io/gitea/modules/log"
 	"code.gitea.io/gitea/modules/matchlist"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/util"
 )
diff --git a/modules/migrations/migrate_test.go b/services/migrations/migrate_test.go
similarity index 87%
rename from modules/migrations/migrate_test.go
rename to services/migrations/migrate_test.go
index c050a9abc086..325064697ef8 100644
--- a/modules/migrations/migrate_test.go
+++ b/services/migrations/migrate_test.go
@@ -9,17 +9,17 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/setting"
 
 	"github.com/stretchr/testify/assert"
 )
 
 func TestMigrateWhiteBlocklist(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	adminUser := db.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User)
-	nonAdminUser := db.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User)
+	adminUser := unittest.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User)
+	nonAdminUser := unittest.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User)
 
 	setting.Migrations.AllowedDomains = []string{"github.com"}
 	assert.NoError(t, Init())
diff --git a/modules/migrations/onedev.go b/services/migrations/onedev.go
similarity index 99%
rename from modules/migrations/onedev.go
rename to services/migrations/onedev.go
index e60265895fbc..1159026892db 100644
--- a/modules/migrations/onedev.go
+++ b/services/migrations/onedev.go
@@ -15,7 +15,7 @@ import (
 
 	"code.gitea.io/gitea/modules/json"
 	"code.gitea.io/gitea/modules/log"
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 	"code.gitea.io/gitea/modules/structs"
 )
 
diff --git a/modules/migrations/onedev_test.go b/services/migrations/onedev_test.go
similarity index 98%
rename from modules/migrations/onedev_test.go
rename to services/migrations/onedev_test.go
index 5dabf66bdca2..59b7cae5feff 100644
--- a/modules/migrations/onedev_test.go
+++ b/services/migrations/onedev_test.go
@@ -12,7 +12,7 @@ import (
 	"testing"
 	"time"
 
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 
 	"github.com/stretchr/testify/assert"
 )
diff --git a/modules/migrations/restore.go b/services/migrations/restore.go
similarity index 99%
rename from modules/migrations/restore.go
rename to services/migrations/restore.go
index 5fddf7b50579..87e5316ef610 100644
--- a/modules/migrations/restore.go
+++ b/services/migrations/restore.go
@@ -11,7 +11,7 @@ import (
 	"path/filepath"
 	"strconv"
 
-	"code.gitea.io/gitea/modules/migrations/base"
+	base "code.gitea.io/gitea/modules/migration"
 
 	"gopkg.in/yaml.v2"
 )
diff --git a/modules/migrations/update.go b/services/migrations/update.go
similarity index 100%
rename from modules/migrations/update.go
rename to services/migrations/update.go
diff --git a/services/pull/check_test.go b/services/pull/check_test.go
index 8beea3d56d90..f0ec096ea945 100644
--- a/services/pull/check_test.go
+++ b/services/pull/check_test.go
@@ -11,14 +11,14 @@ import (
 	"time"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/queue"
 
 	"github.com/stretchr/testify/assert"
 )
 
 func TestPullRequest_AddToTaskQueue(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
 	idChan := make(chan int64, 10)
 
@@ -42,11 +42,11 @@ func TestPullRequest_AddToTaskQueue(t *testing.T) {
 
 	prQueue = q.(queue.UniqueQueue)
 
-	pr := db.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest)
+	pr := unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest)
 	AddToTaskQueue(pr)
 
 	assert.Eventually(t, func() bool {
-		pr = db.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest)
+		pr = unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest)
 		return pr.Status == models.PullRequestStatusChecking
 	}, 1*time.Second, 100*time.Millisecond)
 
@@ -71,7 +71,7 @@ func TestPullRequest_AddToTaskQueue(t *testing.T) {
 	assert.False(t, has)
 	assert.NoError(t, err)
 
-	pr = db.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest)
+	pr = unittest.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest)
 	assert.Equal(t, models.PullRequestStatusChecking, pr.Status)
 
 	for _, callback := range queueShutdown {
diff --git a/services/pull/main_test.go b/services/pull/main_test.go
index c8d3394e8e6a..6059a291addd 100644
--- a/services/pull/main_test.go
+++ b/services/pull/main_test.go
@@ -9,9 +9,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
diff --git a/services/pull/merge.go b/services/pull/merge.go
index f59931e1bfd3..e4ed4e38bd9c 100644
--- a/services/pull/merge.go
+++ b/services/pull/merge.go
@@ -275,8 +275,8 @@ func rawMerge(pr *models.PullRequest, doer *models.User, mergeStyle models.Merge
 					filepath.Join(tmpBasePath, ".git", "rebase-merge", "stopped-sha"),     // Git >= 2.26
 				}
 				for _, failingCommitPath := range failingCommitPaths {
-					if _, statErr := os.Stat(filepath.Join(failingCommitPath)); statErr == nil {
-						commitShaBytes, readErr := os.ReadFile(filepath.Join(failingCommitPath))
+					if _, statErr := os.Stat(failingCommitPath); statErr == nil {
+						commitShaBytes, readErr := os.ReadFile(failingCommitPath)
 						if readErr != nil {
 							// Abandon this attempt to handle the error
 							log.Error("git rebase staging on to base [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String())
diff --git a/services/release/release_test.go b/services/release/release_test.go
index e53e4c935b7c..d720bf996b07 100644
--- a/services/release/release_test.go
+++ b/services/release/release_test.go
@@ -11,7 +11,7 @@ import (
 	"time"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/services/attachment"
 
@@ -19,14 +19,14 @@ import (
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
 
 func TestRelease_Create(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	repoPath := models.RepoPath(user.Name, repo.Name)
 
 	gitRepo, err := git.OpenRepository(repoPath)
@@ -127,10 +127,10 @@ func TestRelease_Create(t *testing.T) {
 }
 
 func TestRelease_Update(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	repoPath := models.RepoPath(user.Name, repo.Name)
 
 	gitRepo, err := git.OpenRepository(repoPath)
@@ -269,10 +269,10 @@ func TestRelease_Update(t *testing.T) {
 }
 
 func TestRelease_createTag(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	repoPath := models.RepoPath(user.Name, repo.Name)
 
 	gitRepo, err := git.OpenRepository(repoPath)
@@ -352,9 +352,9 @@ func TestRelease_createTag(t *testing.T) {
 }
 
 func TestCreateNewTag(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	assert.NoError(t, unittest.PrepareTestDatabase())
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 
 	assert.NoError(t, CreateNewTag(user, repo, "master", "v2.0",
 		"v2.0 is released \n\n BUGFIX: .... \n\n 123"))
diff --git a/modules/repository/adopt.go b/services/repository/adopt.go
similarity index 73%
rename from modules/repository/adopt.go
rename to services/repository/adopt.go
index 21477ab7d771..d48411fbb427 100644
--- a/modules/repository/adopt.go
+++ b/services/repository/adopt.go
@@ -15,12 +15,15 @@ import (
 	"code.gitea.io/gitea/models/db"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/log"
+	"code.gitea.io/gitea/modules/notification"
+	repo_module "code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/setting"
 	"code.gitea.io/gitea/modules/util"
+
 	"github.com/gobwas/glob"
 )
 
-// AdoptRepository adopts a repository for the user/organization.
+// AdoptRepository adopts pre-existing repository files for the user/organization.
 func AdoptRepository(doer, u *models.User, opts models.CreateRepoOptions) (*models.Repository, error) {
 	if !doer.IsAdmin && !u.CanCreateRepo() {
 		return nil, models.ErrReachLimitOfRepo{
@@ -90,9 +93,97 @@ func AdoptRepository(doer, u *models.User, opts models.CreateRepoOptions) (*mode
 		return nil, err
 	}
 
+	notification.NotifyCreateRepository(doer, u, repo)
+
 	return repo, nil
 }
 
+func adoptRepository(ctx context.Context, repoPath string, u *models.User, repo *models.Repository, opts models.CreateRepoOptions) (err error) {
+	isExist, err := util.IsExist(repoPath)
+	if err != nil {
+		log.Error("Unable to check if %s exists. Error: %v", repoPath, err)
+		return err
+	}
+	if !isExist {
+		return fmt.Errorf("adoptRepository: path does not already exist: %s", repoPath)
+	}
+
+	if err := repo_module.CreateDelegateHooks(repoPath); err != nil {
+		return fmt.Errorf("createDelegateHooks: %v", err)
+	}
+
+	// Re-fetch the repository from database before updating it (else it would
+	// override changes that were done earlier with sql)
+	if repo, err = models.GetRepositoryByIDCtx(ctx, repo.ID); err != nil {
+		return fmt.Errorf("getRepositoryByID: %v", err)
+	}
+
+	repo.IsEmpty = false
+	gitRepo, err := git.OpenRepository(repo.RepoPath())
+	if err != nil {
+		return fmt.Errorf("openRepository: %v", err)
+	}
+	defer gitRepo.Close()
+	if len(opts.DefaultBranch) > 0 {
+		repo.DefaultBranch = opts.DefaultBranch
+
+		if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
+			return fmt.Errorf("setDefaultBranch: %v", err)
+		}
+	} else {
+		repo.DefaultBranch, err = gitRepo.GetDefaultBranch()
+		if err != nil {
+			repo.DefaultBranch = setting.Repository.DefaultBranch
+			if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
+				return fmt.Errorf("setDefaultBranch: %v", err)
+			}
+		}
+
+		repo.DefaultBranch = strings.TrimPrefix(repo.DefaultBranch, git.BranchPrefix)
+	}
+	branches, _, _ := gitRepo.GetBranches(0, 0)
+	found := false
+	hasDefault := false
+	hasMaster := false
+	hasMain := false
+	for _, branch := range branches {
+		if branch == repo.DefaultBranch {
+			found = true
+			break
+		} else if branch == setting.Repository.DefaultBranch {
+			hasDefault = true
+		} else if branch == "master" {
+			hasMaster = true
+		} else if branch == "main" {
+			hasMain = true
+		}
+	}
+	if !found {
+		if hasDefault {
+			repo.DefaultBranch = setting.Repository.DefaultBranch
+		} else if hasMaster {
+			repo.DefaultBranch = "master"
+		} else if hasMain {
+			repo.DefaultBranch = "main"
+		} else if len(branches) > 0 {
+			repo.DefaultBranch = branches[0]
+		} else {
+			repo.IsEmpty = true
+			repo.DefaultBranch = setting.Repository.DefaultBranch
+		}
+
+		if err = gitRepo.SetDefaultBranch(repo.DefaultBranch); err != nil {
+			return fmt.Errorf("setDefaultBranch: %v", err)
+		}
+	}
+
+	if err = models.UpdateRepositoryCtx(ctx, repo, false); err != nil {
+		return fmt.Errorf("updateRepository: %v", err)
+	}
+
+	return nil
+}
+
 // DeleteUnadoptedRepository deletes unadopted repository files from the filesystem
 func DeleteUnadoptedRepository(doer, u *models.User, repoName string) error {
 	if err := models.IsUsableRepoName(repoName); err != nil {
@@ -154,7 +245,7 @@ func ListUnadoptedRepositories(query string, opts *db.ListOptions) ([]string, in
 	count := 0
 
 	// We're going to iterate by pagesize.
-	root := filepath.Join(setting.RepoRootPath)
+	root := filepath.Clean(setting.RepoRootPath)
 	if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
 		if err != nil {
 			return err
diff --git a/modules/repository/archive.go b/services/repository/archive.go
similarity index 100%
rename from modules/repository/archive.go
rename to services/repository/archive.go
diff --git a/modules/repository/fork.go b/services/repository/fork.go
similarity index 95%
rename from modules/repository/fork.go
rename to services/repository/fork.go
index df1dccc596c5..f052d18a7591 100644
--- a/modules/repository/fork.go
+++ b/services/repository/fork.go
@@ -14,6 +14,8 @@ import (
 	"code.gitea.io/gitea/models/db"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/log"
+	"code.gitea.io/gitea/modules/notification"
+	repo_module "code.gitea.io/gitea/modules/repository"
 	"code.gitea.io/gitea/modules/structs"
 	"code.gitea.io/gitea/modules/util"
 )
@@ -116,7 +118,7 @@ func ForkRepository(doer, owner *models.User, opts models.ForkRepoOptions) (_ *m
 			return fmt.Errorf("git update-server-info: %v", err)
 		}
 
-		if err = createDelegateHooks(repoPath); err != nil {
+		if err = repo_module.CreateDelegateHooks(repoPath); err != nil {
 			return fmt.Errorf("createDelegateHooks: %v", err)
 		}
 		return nil
@@ -136,6 +138,8 @@ func ForkRepository(doer, owner *models.User, opts models.ForkRepoOptions) (_ *m
 		log.Error("Copy language stat from oldRepo failed")
 	}
 
+	notification.NotifyForkRepository(doer, opts.BaseRepo, repo)
+
 	return repo, nil
 }
 
diff --git a/modules/repository/fork_test.go b/services/repository/fork_test.go
similarity index 68%
rename from modules/repository/fork_test.go
rename to services/repository/fork_test.go
index 7a05f9dd97e3..197d76b0561a 100644
--- a/modules/repository/fork_test.go
+++ b/services/repository/fork_test.go
@@ -8,16 +8,16 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"github.com/stretchr/testify/assert"
 )
 
 func TestForkRepository(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
 	// user 13 has already forked repo10
-	user := db.AssertExistsAndLoadBean(t, &models.User{ID: 13}).(*models.User)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
+	user := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 13}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
 
 	fork, err := ForkRepository(user, user, models.ForkRepoOptions{
 		BaseRepo:    repo,
diff --git a/services/repository/main_test.go b/services/repository/main_test.go
index 91d0d36ca026..262d3394818b 100644
--- a/services/repository/main_test.go
+++ b/services/repository/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
diff --git a/services/repository/repository.go b/services/repository/repository.go
index cde4af2afa8a..98d160c22390 100644
--- a/services/repository/repository.go
+++ b/services/repository/repository.go
@@ -28,36 +28,6 @@ func CreateRepository(doer, owner *models.User, opts models.CreateRepoOptions) (
 	return repo, nil
 }
 
-// AdoptRepository adopts pre-existing repository files for the user/organization.
-func AdoptRepository(doer, owner *models.User, opts models.CreateRepoOptions) (*models.Repository, error) {
-	repo, err := repo_module.AdoptRepository(doer, owner, opts)
-	if err != nil {
-		// No need to rollback here we should do this in AdoptRepository...
-		return nil, err
-	}
-
-	notification.NotifyCreateRepository(doer, owner, repo)
-
-	return repo, nil
-}
-
-// DeleteUnadoptedRepository adopts pre-existing repository files for the user/organization.
-func DeleteUnadoptedRepository(doer, owner *models.User, name string) error {
-	return repo_module.DeleteUnadoptedRepository(doer, owner, name)
-}
-
-// ForkRepository forks a repository
-func ForkRepository(doer, u *models.User, opts models.ForkRepoOptions) (*models.Repository, error) {
-	repo, err := repo_module.ForkRepository(doer, u, opts)
-	if err != nil {
-		return nil, err
-	}
-
-	notification.NotifyForkRepository(doer, opts.BaseRepo, repo)
-
-	return repo, nil
-}
-
 // DeleteRepository deletes a repository for a user or organization.
 func DeleteRepository(doer *models.User, repo *models.Repository) error {
 	if err := pull_service.CloseRepoBranchesPulls(doer, repo); err != nil {
diff --git a/services/repository/transfer_test.go b/services/repository/transfer_test.go
index 40ccfdfb52fa..09c9829216a3 100644
--- a/services/repository/transfer_test.go
+++ b/services/repository/transfer_test.go
@@ -9,7 +9,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/notification"
 	"code.gitea.io/gitea/modules/notification/action"
 	"code.gitea.io/gitea/modules/util"
@@ -28,14 +28,14 @@ func registerNotifier() {
 func TestTransferOwnership(t *testing.T) {
 	registerNotifier()
 
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	doer := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
-	repo.Owner = db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
+	doer := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
+	repo.Owner = unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
 	assert.NoError(t, TransferOwnership(doer, doer, repo, nil))
 
-	transferredRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
+	transferredRepo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
 	assert.EqualValues(t, 2, transferredRepo.OwnerID)
 
 	exist, err := util.IsExist(models.RepoPath("user3", "repo3"))
@@ -44,23 +44,23 @@ func TestTransferOwnership(t *testing.T) {
 	exist, err = util.IsExist(models.RepoPath("user2", "repo3"))
 	assert.NoError(t, err)
 	assert.True(t, exist)
-	db.AssertExistsAndLoadBean(t, &models.Action{
+	unittest.AssertExistsAndLoadBean(t, &models.Action{
 		OpType:    models.ActionTransferRepo,
 		ActUserID: 2,
 		RepoID:    3,
 		Content:   "user3/repo3",
 	})
 
-	models.CheckConsistencyFor(t, &models.Repository{}, &models.User{}, &models.Team{})
+	unittest.CheckConsistencyFor(t, &models.Repository{}, &models.User{}, &models.Team{})
 }
 
 func TestStartRepositoryTransferSetPermission(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	doer := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)
-	recipient := db.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
-	repo.Owner = db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
+	doer := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)
+	recipient := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
+	repo.Owner = unittest.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
 
 	hasAccess, err := models.HasAccess(recipient.ID, repo)
 	assert.NoError(t, err)
@@ -72,5 +72,5 @@ func TestStartRepositoryTransferSetPermission(t *testing.T) {
 	assert.NoError(t, err)
 	assert.True(t, hasAccess)
 
-	models.CheckConsistencyFor(t, &models.Repository{}, &models.User{}, &models.Team{})
+	unittest.CheckConsistencyFor(t, &models.Repository{}, &models.User{}, &models.Team{})
 }
diff --git a/services/webhook/main_test.go b/services/webhook/main_test.go
index 7aef4b3a51ef..fc58f72565f9 100644
--- a/services/webhook/main_test.go
+++ b/services/webhook/main_test.go
@@ -8,9 +8,9 @@ import (
 	"path/filepath"
 	"testing"
 
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
diff --git a/services/webhook/webhook_test.go b/services/webhook/webhook_test.go
index 75f19e50ce98..0a649d36aed8 100644
--- a/services/webhook/webhook_test.go
+++ b/services/webhook/webhook_test.go
@@ -8,7 +8,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	webhook_model "code.gitea.io/gitea/models/webhook"
 	api "code.gitea.io/gitea/modules/structs"
 	"github.com/stretchr/testify/assert"
@@ -27,52 +27,52 @@ func TestWebhook_GetSlackHook(t *testing.T) {
 }
 
 func TestPrepareWebhooks(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	hookTasks := []*webhook_model.HookTask{
 		{RepoID: repo.ID, HookID: 1, EventType: webhook_model.HookEventPush},
 	}
 	for _, hookTask := range hookTasks {
-		db.AssertNotExistsBean(t, hookTask)
+		unittest.AssertNotExistsBean(t, hookTask)
 	}
 	assert.NoError(t, PrepareWebhooks(repo, webhook_model.HookEventPush, &api.PushPayload{Commits: []*api.PayloadCommit{{}}}))
 	for _, hookTask := range hookTasks {
-		db.AssertExistsAndLoadBean(t, hookTask)
+		unittest.AssertExistsAndLoadBean(t, hookTask)
 	}
 }
 
 func TestPrepareWebhooksBranchFilterMatch(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
 	hookTasks := []*webhook_model.HookTask{
 		{RepoID: repo.ID, HookID: 4, EventType: webhook_model.HookEventPush},
 	}
 	for _, hookTask := range hookTasks {
-		db.AssertNotExistsBean(t, hookTask)
+		unittest.AssertNotExistsBean(t, hookTask)
 	}
 	// this test also ensures that * doesn't handle / in any special way (like shell would)
 	assert.NoError(t, PrepareWebhooks(repo, webhook_model.HookEventPush, &api.PushPayload{Ref: "refs/heads/feature/7791", Commits: []*api.PayloadCommit{{}}}))
 	for _, hookTask := range hookTasks {
-		db.AssertExistsAndLoadBean(t, hookTask)
+		unittest.AssertExistsAndLoadBean(t, hookTask)
 	}
 }
 
 func TestPrepareWebhooksBranchFilterNoMatch(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
 	hookTasks := []*webhook_model.HookTask{
 		{RepoID: repo.ID, HookID: 4, EventType: webhook_model.HookEventPush},
 	}
 	for _, hookTask := range hookTasks {
-		db.AssertNotExistsBean(t, hookTask)
+		unittest.AssertNotExistsBean(t, hookTask)
 	}
 	assert.NoError(t, PrepareWebhooks(repo, webhook_model.HookEventPush, &api.PushPayload{Ref: "refs/heads/fix_weird_bug"}))
 
 	for _, hookTask := range hookTasks {
-		db.AssertNotExistsBean(t, hookTask)
+		unittest.AssertNotExistsBean(t, hookTask)
 	}
 }
 
diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go
index d6a65cc23a82..ee548d23158c 100644
--- a/services/wiki/wiki_test.go
+++ b/services/wiki/wiki_test.go
@@ -10,7 +10,7 @@ import (
 	"testing"
 
 	"code.gitea.io/gitea/models"
-	"code.gitea.io/gitea/models/db"
+	"code.gitea.io/gitea/models/unittest"
 	"code.gitea.io/gitea/modules/git"
 	"code.gitea.io/gitea/modules/util"
 
@@ -18,7 +18,7 @@ import (
 )
 
 func TestMain(m *testing.M) {
-	db.MainTest(m, filepath.Join("..", ".."))
+	unittest.MainTest(m, filepath.Join("..", ".."))
 }
 
 func TestWikiNameToSubURL(t *testing.T) {
@@ -110,23 +110,23 @@ func TestWikiNameToFilenameToName(t *testing.T) {
 }
 
 func TestRepository_InitWiki(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 	// repo1 already has a wiki
-	repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	repo1 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	assert.NoError(t, InitWiki(repo1))
 
 	// repo2 does not already have a wiki
-	repo2 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
+	repo2 := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
 	assert.NoError(t, InitWiki(repo2))
 	assert.True(t, repo2.HasWiki())
 }
 
 func TestRepository_AddWikiPage(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 	const wikiContent = "This is the wiki content"
 	const commitMsg = "Commit message"
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
-	doer := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	doer := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	for _, wikiName := range []string{
 		"Another page",
 		"Here's a  and a/slash",
@@ -166,18 +166,18 @@ func TestRepository_AddWikiPage(t *testing.T) {
 }
 
 func TestRepository_EditWikiPage(t *testing.T) {
-	assert.NoError(t, db.PrepareTestDatabase())
+	assert.NoError(t, unittest.PrepareTestDatabase())
 
 	const newWikiContent = "This is the new content"
 	const commitMsg = "Commit message"
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
-	doer := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	doer := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	for _, newWikiName := range []string{
 		"Home", // same name as before
 		"New home",
 		"New/name/with/slashes",
 	} {
-		db.PrepareTestEnv(t)
+		unittest.PrepareTestEnv(t)
 		assert.NoError(t, EditWikiPage(doer, repo, "Home", newWikiName, newWikiContent, commitMsg))
 
 		// Now need to show that the page has been added:
@@ -199,9 +199,9 @@ func TestRepository_EditWikiPage(t *testing.T) {
 }
 
 func TestRepository_DeleteWikiPage(t *testing.T) {
-	db.PrepareTestEnv(t)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
-	doer := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
+	unittest.PrepareTestEnv(t)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	doer := unittest.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
 	assert.NoError(t, DeleteWikiPage(doer, repo, "Home"))
 
 	// Now need to show that the page has been added:
@@ -216,8 +216,8 @@ func TestRepository_DeleteWikiPage(t *testing.T) {
 }
 
 func TestPrepareWikiFileName(t *testing.T) {
-	db.PrepareTestEnv(t)
-	repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
+	unittest.PrepareTestEnv(t)
+	repo := unittest.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
 	gitRepo, err := git.OpenRepository(repo.WikiPath())
 	defer gitRepo.Close()
 	assert.NoError(t, err)
@@ -267,7 +267,7 @@ func TestPrepareWikiFileName(t *testing.T) {
 }
 
 func TestPrepareWikiFileName_FirstPage(t *testing.T) {
-	db.PrepareTestEnv(t)
+	unittest.PrepareTestEnv(t)
 
 	// Now create a temporaryDirectory
 	tmpDir, err := os.MkdirTemp("", "empty-wiki")
diff --git a/templates/base/head.tmpl b/templates/base/head.tmpl
index f05daaa42120..d529e6bfda76 100644
--- a/templates/base/head.tmpl
+++ b/templates/base/head.tmpl
@@ -46,6 +46,10 @@
 			]).values()),
 			{{end}}
 			mermaidMaxSourceCharacters: {{MermaidMaxSourceCharacters}},
+			i18n: {
+				copy_success: '{{.i18n.Tr "copy_success"}}',
+				copy_error: '{{.i18n.Tr "copy_error"}}',
+			}
 		};
 	
 	
diff --git a/templates/repo/clone_buttons.tmpl b/templates/repo/clone_buttons.tmpl
index 0a86e586fc9f..37a88af945fc 100644
--- a/templates/repo/clone_buttons.tmpl
+++ b/templates/repo/clone_buttons.tmpl
@@ -14,7 +14,7 @@
 	
 {{end}}
 {{if or (not $.DisableHTTP) (and (not $.DisableSSH) (or $.IsSigned $.ExposeAnonSSH))}}
-	
 {{end}}
diff --git a/templates/repo/diff/box.tmpl b/templates/repo/diff/box.tmpl
index f5041d87e967..56d6942baab9 100644
--- a/templates/repo/diff/box.tmpl
+++ b/templates/repo/diff/box.tmpl
@@ -118,7 +118,7 @@
 									{{end}}
 								
 							{{else}}
-								
+								
{{if $.IsSplitStyle}} {{template "repo/diff/section_split" dict "file" . "root" $}} {{else}} diff --git a/templates/repo/diff/section_split.tmpl b/templates/repo/diff/section_split.tmpl index 1c7ae5a63fbc..fb6977e204e6 100644 --- a/templates/repo/diff/section_split.tmpl +++ b/templates/repo/diff/section_split.tmpl @@ -27,17 +27,17 @@ {{$match := index $section.Lines $line.Match}} - + - + {{else}} - + - + {{end}} {{if and (eq .GetType 3) $hasmatch}} diff --git a/templates/repo/diff/section_unified.tmpl b/templates/repo/diff/section_unified.tmpl index ac43dbe54ca2..57e8fb9a1603 100644 --- a/templates/repo/diff/section_unified.tmpl +++ b/templates/repo/diff/section_unified.tmpl @@ -29,7 +29,7 @@ {{if eq .GetType 4}} {{else}} - + {{end}} {{if gt (len $line.Comments) 0}} diff --git a/templates/repo/home.tmpl b/templates/repo/home.tmpl index df8991599a18..40e782a60566 100644 --- a/templates/repo/home.tmpl +++ b/templates/repo/home.tmpl @@ -113,12 +113,10 @@ diff --git a/templates/repo/issue/view_title.tmpl b/templates/repo/issue/view_title.tmpl index c3defa4cdba6..c4b391d97a0d 100644 --- a/templates/repo/issue/view_title.tmpl +++ b/templates/repo/issue/view_title.tmpl @@ -34,7 +34,7 @@ {{if .HeadBranchHTMLURL}} {{$headHref = printf "%s" (.HeadBranchHTMLURL | Escape) $headHref}} {{end}} - {{$headHref = printf "%s %s" $headHref (.i18n.Tr "repo.copy_branch") (.i18n.Tr "repo.copy_branch_success") (.i18n.Tr "repo.copy_branch_error") (.HeadTarget | Escape) (svg "octicon-copy" 14)}} + {{$headHref = printf "%s %s" $headHref (.i18n.Tr "copy_branch") (.HeadTarget | Escape) (svg "octicon-copy" 14)}} {{$baseHref := .BaseTarget|Escape}} {{if .BaseBranchHTMLURL}} {{$baseHref = printf "%s" (.BaseBranchHTMLURL | Escape) $baseHref}} diff --git a/templates/repo/migrate/gitbucket.tmpl b/templates/repo/migrate/gitbucket.tmpl new file mode 100644 index 000000000000..9c634dba347f --- /dev/null +++ b/templates/repo/migrate/gitbucket.tmpl @@ -0,0 +1,132 @@ +{{template "base/head" .}} +
+
+
+
+ {{.CsrfTokenHtml}} +

+ {{.i18n.Tr "repo.migrate.migrate" .service.Title}} + +

+
+ {{template "base/alert" .}} +
+ + + + {{.i18n.Tr "repo.migrate.clone_address_desc"}}{{if .ContextUser.CanImportLocal}} {{.i18n.Tr "repo.migrate.clone_local_path"}}{{end}} + +
+ +
+ + +
+
+ + +
+ + {{template "repo/migrate/options" .}} + +
+ +
+ + +
+
+ +
+ {{.i18n.Tr "repo.migrate.migrate_items_options"}} +
+ +
+ + +
+
+ + +
+
+
+ +
+ + +
+
+ + +
+
+
+ +
+ + +
+
+
+ +
+ +
+ + +
+ +
+ + +
+
+ +
+ {{if .IsForcedPrivate}} + + + {{else}} + + + {{end}} +
+
+
+ + +
+ +
+ + + {{.i18n.Tr "cancel"}} +
+
+ +
+
+
+{{template "base/footer" .}} diff --git a/templates/repo/migrate/gitea.tmpl b/templates/repo/migrate/gitea.tmpl index 901524d11227..d0532923e130 100644 --- a/templates/repo/migrate/gitea.tmpl +++ b/templates/repo/migrate/gitea.tmpl @@ -26,19 +26,16 @@ {{template "repo/migrate/options" .}} - {{.i18n.Tr "repo.migrate.migrate_items_options"}} -
-
- -
- - -
-
- - -
+
+ +
+ +
+
+ +
+ {{.i18n.Tr "repo.migrate.migrate_items_options"}}
@@ -61,6 +58,13 @@
+
+ +
+ + +
+
diff --git a/templates/repo/migrate/github.tmpl b/templates/repo/migrate/github.tmpl index 9bd7228a43b4..1dfd164c8553 100644 --- a/templates/repo/migrate/github.tmpl +++ b/templates/repo/migrate/github.tmpl @@ -29,19 +29,15 @@ {{template "repo/migrate/options" .}} - {{.i18n.Tr "repo.migrate.migrate_items_options"}} -
-
- -
- - -
-
- - -
+
+ +
+ +
+
+
+ {{.i18n.Tr "repo.migrate.migrate_items_options"}}
@@ -64,6 +60,13 @@
+
+ +
+ + +
+
diff --git a/templates/repo/migrate/gitlab.tmpl b/templates/repo/migrate/gitlab.tmpl index e1424c250fb0..b730164a8ff0 100644 --- a/templates/repo/migrate/gitlab.tmpl +++ b/templates/repo/migrate/gitlab.tmpl @@ -26,19 +26,15 @@ {{template "repo/migrate/options" .}} - {{.i18n.Tr "repo.migrate.migrate_items_options"}} -
-
- -
- - -
-
- - -
+
+ +
+ +
+
+
+ {{.i18n.Tr "repo.migrate.migrate_items_options"}}
@@ -61,6 +57,13 @@
+
+ +
+ + +
+
diff --git a/templates/repo/migrate/gogs.tmpl b/templates/repo/migrate/gogs.tmpl index b1900e83d101..c35ef017b335 100644 --- a/templates/repo/migrate/gogs.tmpl +++ b/templates/repo/migrate/gogs.tmpl @@ -26,19 +26,16 @@ {{template "repo/migrate/options" .}} - {{.i18n.Tr "repo.migrate.migrate_items_options"}} -
-
- -
- - -
-
- - -
+
+ +
+ +
+
+ +
+ {{.i18n.Tr "repo.migrate.migrate_items_options"}}
@@ -50,6 +47,13 @@
+
+ +
+ + +
+
{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{if $line.LeftIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{if $line.LeftIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}} {{if $match.RightIdx}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{if $match.RightIdx}}{{$section.GetComputedInlineDiffFor $match}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{if $match.RightIdx}}{{$section.GetComputedInlineDiffFor $match}}{{end}} {{if $line.LeftIdx}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles (not (eq .GetType 2))}}{{svg "octicon-plus"}}{{end}}{{if $line.LeftIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles (not (eq .GetType 2))}}{{svg "octicon-plus"}}{{end}}{{if $line.LeftIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}} {{if $line.RightIdx}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles (not (eq .GetType 3))}}{{svg "octicon-plus"}}{{end}}{{if $line.RightIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles (not (eq .GetType 3))}}{{svg "octicon-plus"}}{{end}}{{if $line.RightIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}}
{{$section.GetComputedInlineDiffFor $line}}{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{$section.GetComputedInlineDiffFor $line}}{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{$section.GetComputedInlineDiffFor $line}}