1
0
mirror of https://github.com/go-gitea/gitea.git synced 2024-12-22 17:34:03 +03:00

Move db related basic functions to models/db (#17075)

* Move db related basic functions to models/db

* Fix lint

* Fix lint

* Fix test

* Fix lint

* Fix lint

* revert unnecessary change

* Fix test

* Fix wrong replace string

* Use *Context

* Correct committer spelling and fix wrong replaced words

Co-authored-by: zeripath <art27@cantab.net>
This commit is contained in:
Lunny Xiao 2021-09-19 19:49:59 +08:00 committed by GitHub
parent 462306e263
commit a4bfef265d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
335 changed files with 4191 additions and 3654 deletions

View File

@ -15,7 +15,7 @@ import (
"strings"
"syscall"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/util"
@ -65,7 +65,7 @@ func initDBDisableConsole(disableConsole bool) error {
setting.InitDBConfig()
setting.NewXORMLogService(disableConsole)
if err := models.SetEngine(); err != nil {
if err := db.SetEngine(); err != nil {
return fmt.Errorf("models.SetEngine: %v", err)
}
return nil

View File

@ -7,7 +7,7 @@ package cmd
import (
"fmt"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
@ -39,7 +39,7 @@ func runConvert(ctx *cli.Context) error {
return nil
}
if err := models.ConvertUtf8ToUtf8mb4(); err != nil {
if err := db.ConvertUtf8ToUtf8mb4(); err != nil {
log.Fatal("Failed to convert database from utf8 to utf8mb4: %v", err)
return err
}

View File

@ -12,7 +12,7 @@ import (
"strings"
"text/tabwriter"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/migrations"
"code.gitea.io/gitea/modules/doctor"
"code.gitea.io/gitea/modules/log"
@ -96,7 +96,7 @@ func runRecreateTable(ctx *cli.Context) error {
setting.Cfg.Section("log").Key("XORM").SetValue(",")
setting.NewXORMLogService(!ctx.Bool("debug"))
if err := models.SetEngine(); err != nil {
if err := db.SetEngine(); err != nil {
fmt.Println(err)
fmt.Println("Check if you are using the right config file. You can use a --config directive to specify one.")
return nil
@ -108,13 +108,13 @@ func runRecreateTable(ctx *cli.Context) error {
names = append(names, args.Get(i))
}
beans, err := models.NamesToBean(names...)
beans, err := db.NamesToBean(names...)
if err != nil {
return err
}
recreateTables := migrations.RecreateTables(beans...)
return models.NewEngine(context.Background(), func(x *xorm.Engine) error {
return db.NewEngine(context.Background(), func(x *xorm.Engine) error {
if err := migrations.EnsureUpToDate(x); err != nil {
return err
}

View File

@ -14,7 +14,7 @@ import (
"strings"
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
@ -174,7 +174,7 @@ func runDump(ctx *cli.Context) error {
}
setting.NewServices() // cannot access session settings otherwise
err := models.SetEngine()
err := db.SetEngine()
if err != nil {
return err
}
@ -264,7 +264,7 @@ func runDump(ctx *cli.Context) error {
log.Info("Dumping database...")
}
if err := models.DumpDatabase(dbDump.Name(), targetDBType); err != nil {
if err := db.DumpDatabase(dbDump.Name(), targetDBType); err != nil {
fatal("Failed to dump database: %v", err)
}

View File

@ -7,7 +7,7 @@ package cmd
import (
"context"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/migrations"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
@ -35,7 +35,7 @@ func runMigrate(ctx *cli.Context) error {
log.Info("Configuration file: %s", setting.CustomConf)
setting.InitDBConfig()
if err := models.NewEngine(context.Background(), migrations.Migrate); err != nil {
if err := db.NewEngine(context.Background(), migrations.Migrate); err != nil {
log.Fatal("Failed to initialize ORM engine: %v", err)
return err
}

View File

@ -10,6 +10,7 @@ import (
"strings"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/migrations"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
@ -117,7 +118,7 @@ func runMigrateStorage(ctx *cli.Context) error {
log.Info("Configuration file: %s", setting.CustomConf)
setting.InitDBConfig()
if err := models.NewEngine(context.Background(), migrations.Migrate); err != nil {
if err := db.NewEngine(context.Background(), migrations.Migrate); err != nil {
log.Fatal("Failed to initialize ORM engine: %v", err)
return err
}

View File

@ -11,6 +11,7 @@ import (
"path/filepath"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
)
// To generate derivative fixtures, execute the following from Gitea's repository base dir:
@ -31,11 +32,11 @@ var (
func main() {
pathToGiteaRoot := "."
fixturesDir = filepath.Join(pathToGiteaRoot, "models", "fixtures")
if err := models.CreateTestEngine(fixturesDir); err != nil {
if err := db.CreateTestEngine(fixturesDir); err != nil {
fmt.Printf("CreateTestEngine: %+v", err)
os.Exit(1)
}
if err := models.PrepareTestDatabase(); err != nil {
if err := db.PrepareTestDatabase(); err != nil {
fmt.Printf("PrepareTestDatabase: %+v\n", err)
os.Exit(1)
}

View File

@ -26,6 +26,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
gitea_git "code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/markup/external"
@ -87,27 +88,27 @@ func runPR() {
setting.Database.Path = ":memory:"
setting.Database.Timeout = 500
*/
db := setting.Cfg.Section("database")
db.NewKey("DB_TYPE", "sqlite3")
db.NewKey("PATH", ":memory:")
dbCfg := setting.Cfg.Section("database")
dbCfg.NewKey("DB_TYPE", "sqlite3")
dbCfg.NewKey("PATH", ":memory:")
routers.NewServices()
setting.Database.LogSQL = true
//x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared")
models.NewEngine(context.Background(), func(_ *xorm.Engine) error {
db.NewEngine(context.Background(), func(_ *xorm.Engine) error {
return nil
})
models.HasEngine = true
db.HasEngine = true
//x.ShowSQL(true)
err = models.InitFixtures(
err = db.InitFixtures(
path.Join(curDir, "models/fixtures/"),
)
if err != nil {
fmt.Printf("Error initializing test database: %v\n", err)
os.Exit(1)
}
models.LoadFixtures()
db.LoadFixtures()
util.RemoveAll(setting.RepoRootPath)
util.RemoveAll(models.LocalCopyPath())
util.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
)
@ -60,7 +61,7 @@ func makeRequest(t *testing.T, formData models.User, headerCode int) {
})
session.MakeRequest(t, req, headerCode)
user := models.AssertExistsAndLoadBean(t, &models.User{ID: formData.ID}).(*models.User)
user := db.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)

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -42,7 +43,7 @@ func TestAPIAdminOrgCreate(t *testing.T) {
assert.Equal(t, org.Location, apiOrg.Location)
assert.Equal(t, org.Visibility, apiOrg.Visibility)
models.AssertExistsAndLoadBean(t, &models.User{
db.AssertExistsAndLoadBean(t, &models.User{
Name: org.UserName,
LowerName: strings.ToLower(org.UserName),
FullName: org.FullName,

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/json"
api "code.gitea.io/gitea/modules/structs"
@ -20,7 +21,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) {
defer prepareTestEnv(t)()
// user1 is an admin user
session := loginUser(t, "user1")
keyOwner := models.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User)
keyOwner := db.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)
@ -32,7 +33,7 @@ func TestAPIAdminCreateAndDeleteSSHKey(t *testing.T) {
var newPublicKey api.PublicKey
DecodeJSON(t, resp, &newPublicKey)
models.AssertExistsAndLoadBean(t, &models.PublicKey{
db.AssertExistsAndLoadBean(t, &models.PublicKey{
ID: newPublicKey.ID,
Name: newPublicKey.Title,
Content: newPublicKey.Key,
@ -43,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)
models.AssertNotExistsBean(t, &models.PublicKey{ID: newPublicKey.ID})
db.AssertNotExistsBean(t, &models.PublicKey{ID: newPublicKey.ID})
}
func TestAPIAdminDeleteMissingSSHKey(t *testing.T) {
@ -52,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", models.NonexistentID, token)
req := NewRequestf(t, "DELETE", "/api/v1/admin/users/user1/keys/%d?token=%s", db.NonexistentID, token)
session.MakeRequest(t, req, http.StatusNotFound)
}
@ -127,7 +128,7 @@ func TestAPIListUsers(t *testing.T) {
}
}
assert.True(t, found)
numberOfUsers := models.GetCount(t, &models.User{}, "type = 0")
numberOfUsers := db.GetCount(t, &models.User{}, "type = 0")
assert.Equal(t, numberOfUsers, len(users))
}
@ -193,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 := models.AssertExistsAndLoadBean(t, &models.User{LoginName: "user2"}).(*models.User)
user2 := db.AssertExistsAndLoadBean(t, &models.User{LoginName: "user2"}).(*models.User)
assert.False(t, user2.IsRestricted)
bTrue := true
req = NewRequestWithJSON(t, "PATCH", urlStr, api.EditUserOption{
@ -204,6 +205,6 @@ func TestAPIEditUser(t *testing.T) {
Restricted: &bTrue,
})
session.MakeRequest(t, req, http.StatusOK)
user2 = models.AssertExistsAndLoadBean(t, &models.User{LoginName: "user2"}).(*models.User)
user2 = db.AssertExistsAndLoadBean(t, &models.User{LoginName: "user2"}).(*models.User)
assert.True(t, user2.IsRestricted)
}

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/convert"
api "code.gitea.io/gitea/modules/structs"
@ -20,11 +21,11 @@ import (
func TestAPIListRepoComments(t *testing.T) {
defer prepareTestEnv(t)()
comment := models.AssertExistsAndLoadBean(t, &models.Comment{},
models.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
issue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
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)
session := loginUser(t, repoOwner.Name)
link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments", repoOwner.Name, repo.Name))
@ -36,9 +37,9 @@ func TestAPIListRepoComments(t *testing.T) {
assert.Len(t, apiComments, 2)
for _, apiComment := range apiComments {
c := &models.Comment{ID: apiComment.ID}
models.AssertExistsAndLoadBean(t, c,
models.Cond("type = ?", models.CommentTypeComment))
models.AssertExistsAndLoadBean(t, &models.Issue{ID: c.IssueID, RepoID: repo.ID})
db.AssertExistsAndLoadBean(t, c,
db.Cond("type = ?", models.CommentTypeComment))
db.AssertExistsAndLoadBean(t, &models.Issue{ID: c.IssueID, RepoID: repo.ID})
}
//test before and since filters
@ -66,11 +67,11 @@ func TestAPIListRepoComments(t *testing.T) {
func TestAPIListIssueComments(t *testing.T) {
defer prepareTestEnv(t)()
comment := models.AssertExistsAndLoadBean(t, &models.Comment{},
models.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
issue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
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)
session := loginUser(t, repoOwner.Name)
req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/%d/comments",
@ -79,8 +80,8 @@ func TestAPIListIssueComments(t *testing.T) {
var comments []*api.Comment
DecodeJSON(t, resp, &comments)
expectedCount := models.GetCount(t, &models.Comment{IssueID: issue.ID},
models.Cond("type = ?", models.CommentTypeComment))
expectedCount := db.GetCount(t, &models.Comment{IssueID: issue.ID},
db.Cond("type = ?", models.CommentTypeComment))
assert.EqualValues(t, expectedCount, len(comments))
}
@ -88,9 +89,9 @@ func TestAPICreateComment(t *testing.T) {
defer prepareTestEnv(t)()
const commentBody = "Comment body"
issue := models.AssertExistsAndLoadBean(t, &models.Issue{}).(*models.Issue)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
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)
session := loginUser(t, repoOwner.Name)
token := getTokenForLoggedInUser(t, session)
@ -104,16 +105,16 @@ func TestAPICreateComment(t *testing.T) {
var updatedComment api.Comment
DecodeJSON(t, resp, &updatedComment)
assert.EqualValues(t, commentBody, updatedComment.Body)
models.AssertExistsAndLoadBean(t, &models.Comment{ID: updatedComment.ID, IssueID: issue.ID, Content: commentBody})
db.AssertExistsAndLoadBean(t, &models.Comment{ID: updatedComment.ID, IssueID: issue.ID, Content: commentBody})
}
func TestAPIGetComment(t *testing.T) {
defer prepareTestEnv(t)()
comment := models.AssertExistsAndLoadBean(t, &models.Comment{ID: 2}).(*models.Comment)
comment := db.AssertExistsAndLoadBean(t, &models.Comment{ID: 2}).(*models.Comment)
assert.NoError(t, comment.LoadIssue())
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: comment.Issue.RepoID}).(*models.Repository)
repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: comment.Issue.RepoID}).(*models.Repository)
repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, repoOwner.Name)
token := getTokenForLoggedInUser(t, session)
@ -138,11 +139,11 @@ func TestAPIEditComment(t *testing.T) {
defer prepareTestEnv(t)()
const newCommentBody = "This is the new comment body"
comment := models.AssertExistsAndLoadBean(t, &models.Comment{},
models.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
issue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
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)
session := loginUser(t, repoOwner.Name)
token := getTokenForLoggedInUser(t, session)
@ -157,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)
models.AssertExistsAndLoadBean(t, &models.Comment{ID: comment.ID, IssueID: issue.ID, Content: newCommentBody})
db.AssertExistsAndLoadBean(t, &models.Comment{ID: comment.ID, IssueID: issue.ID, Content: newCommentBody})
}
func TestAPIDeleteComment(t *testing.T) {
defer prepareTestEnv(t)()
comment := models.AssertExistsAndLoadBean(t, &models.Comment{},
models.Cond("type = ?", models.CommentTypeComment)).(*models.Comment)
issue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: comment.IssueID}).(*models.Issue)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
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)
session := loginUser(t, repoOwner.Name)
token := getTokenForLoggedInUser(t, session)
@ -175,5 +176,5 @@ func TestAPIDeleteComment(t *testing.T) {
repoOwner.Name, repo.Name, comment.ID, token)
session.MakeRequest(t, req, http.StatusNoContent)
models.AssertNotExistsBean(t, &models.Comment{ID: comment.ID})
db.AssertNotExistsBean(t, &models.Comment{ID: comment.ID})
}

View File

@ -11,16 +11,17 @@ import (
"testing"
"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, models.LoadFixtures())
assert.NoError(t, db.LoadFixtures())
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
owner := db.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)
@ -34,7 +35,7 @@ func TestAPIModifyLabels(t *testing.T) {
resp := session.MakeRequest(t, req, http.StatusCreated)
apiLabel := new(api.Label)
DecodeJSON(t, resp, &apiLabel)
dbLabel := models.AssertExistsAndLoadBean(t, &models.Label{ID: apiLabel.ID, RepoID: repo.ID}).(*models.Label)
dbLabel := db.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)
@ -87,12 +88,12 @@ func TestAPIModifyLabels(t *testing.T) {
}
func TestAPIAddIssueLabels(t *testing.T) {
assert.NoError(t, models.LoadFixtures())
assert.NoError(t, db.LoadFixtures())
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
issue := models.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repo.ID}).(*models.Issue)
_ = models.AssertExistsAndLoadBean(t, &models.Label{RepoID: repo.ID, ID: 2}).(*models.Label)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
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)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
@ -104,18 +105,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, models.GetCount(t, &models.IssueLabel{IssueID: issue.ID}))
assert.Len(t, apiLabels, db.GetCount(t, &models.IssueLabel{IssueID: issue.ID}))
models.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: issue.ID, LabelID: 2})
db.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: issue.ID, LabelID: 2})
}
func TestAPIReplaceIssueLabels(t *testing.T) {
assert.NoError(t, models.LoadFixtures())
assert.NoError(t, db.LoadFixtures())
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
issue := models.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repo.ID}).(*models.Issue)
label := models.AssertExistsAndLoadBean(t, &models.Label{RepoID: repo.ID}).(*models.Label)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
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)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
@ -131,15 +132,15 @@ func TestAPIReplaceIssueLabels(t *testing.T) {
assert.EqualValues(t, label.ID, apiLabels[0].ID)
}
models.AssertCount(t, &models.IssueLabel{IssueID: issue.ID}, 1)
models.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: issue.ID, LabelID: label.ID})
db.AssertCount(t, &models.IssueLabel{IssueID: issue.ID}, 1)
db.AssertExistsAndLoadBean(t, &models.IssueLabel{IssueID: issue.ID, LabelID: label.ID})
}
func TestAPIModifyOrgLabels(t *testing.T) {
assert.NoError(t, models.LoadFixtures())
assert.NoError(t, db.LoadFixtures())
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
user := "user1"
session := loginUser(t, user)
token := getTokenForLoggedInUser(t, session)
@ -154,7 +155,7 @@ func TestAPIModifyOrgLabels(t *testing.T) {
resp := session.MakeRequest(t, req, http.StatusCreated)
apiLabel := new(api.Label)
DecodeJSON(t, resp, &apiLabel)
dbLabel := models.AssertExistsAndLoadBean(t, &models.Label{ID: apiLabel.ID, OrgID: owner.ID}).(*models.Label)
dbLabel := db.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)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -18,9 +19,9 @@ import (
func TestAPIIssuesMilestone(t *testing.T) {
defer prepareTestEnv(t)()
milestone := models.AssertExistsAndLoadBean(t, &models.Milestone{ID: 1}).(*models.Milestone)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: milestone.RepoID}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
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)
assert.Equal(t, int64(1), int64(milestone.NumIssues))
assert.Equal(t, structs.StateOpen, milestone.State())

View File

@ -11,6 +11,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/convert"
api "code.gitea.io/gitea/modules/structs"
@ -20,14 +21,14 @@ import (
func TestAPIIssuesReactions(t *testing.T) {
defer prepareTestEnv(t)()
issue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue)
issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue)
_ = issue.LoadRepo()
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user2 := db.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)
@ -77,17 +78,17 @@ func TestAPIIssuesReactions(t *testing.T) {
func TestAPICommentReactions(t *testing.T) {
defer prepareTestEnv(t)()
comment := models.AssertExistsAndLoadBean(t, &models.Comment{ID: 2}).(*models.Comment)
comment := db.AssertExistsAndLoadBean(t, &models.Comment{ID: 2}).(*models.Comment)
_ = comment.LoadIssue()
issue := comment.Issue
_ = issue.LoadRepo()
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
user1 := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user1 := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
user2 := db.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)

View File

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -17,8 +18,8 @@ import (
func TestAPIListStopWatches(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
@ -26,8 +27,8 @@ func TestAPIListStopWatches(t *testing.T) {
resp := session.MakeRequest(t, req, http.StatusOK)
var apiWatches []*api.StopWatch
DecodeJSON(t, resp, &apiWatches)
stopwatch := models.AssertExistsAndLoadBean(t, &models.Stopwatch{UserID: owner.ID}).(*models.Stopwatch)
issue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: stopwatch.IssueID}).(*models.Issue)
stopwatch := db.AssertExistsAndLoadBean(t, &models.Stopwatch{UserID: owner.ID}).(*models.Stopwatch)
issue := db.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)
@ -41,10 +42,10 @@ func TestAPIListStopWatches(t *testing.T) {
func TestAPIStopStopWatches(t *testing.T) {
defer prepareTestEnv(t)()
issue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
_ = issue.LoadRepo()
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User)
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
@ -57,10 +58,10 @@ func TestAPIStopStopWatches(t *testing.T) {
func TestAPICancelStopWatches(t *testing.T) {
defer prepareTestEnv(t)()
issue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue)
issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue)
_ = issue.LoadRepo()
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User)
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
@ -73,10 +74,10 @@ func TestAPICancelStopWatches(t *testing.T) {
func TestAPIStartStopWatches(t *testing.T) {
defer prepareTestEnv(t)()
issue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue)
issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue)
_ = issue.LoadRepo()
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User)
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: issue.Repo.OwnerID}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -18,20 +19,20 @@ import (
func TestAPIIssueSubscriptions(t *testing.T) {
defer prepareTestEnv(t)()
issue1 := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 1}).(*models.Issue)
issue2 := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
issue3 := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue)
issue4 := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 4}).(*models.Issue)
issue5 := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 8}).(*models.Issue)
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)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: issue1.PosterID}).(*models.User)
owner := db.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 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issue.RepoID}).(*models.Repository)
issueRepo := db.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)
@ -52,7 +53,7 @@ func TestAPIIssueSubscriptions(t *testing.T) {
testSubscription(issue4, false)
testSubscription(issue5, false)
issue1Repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issue1.RepoID}).(*models.Repository)
issue1Repo := db.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)
@ -62,7 +63,7 @@ func TestAPIIssueSubscriptions(t *testing.T) {
session.MakeRequest(t, req, http.StatusOK)
testSubscription(issue1, false)
issue5Repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issue5.RepoID}).(*models.Repository)
issue5Repo := db.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)

View File

@ -12,6 +12,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -20,8 +21,8 @@ import (
func TestAPIListIssues(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
@ -31,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, models.GetCount(t, &models.Issue{RepoID: repo.ID}))
assert.Len(t, apiIssues, db.GetCount(t, &models.Issue{RepoID: repo.ID}))
for _, apiIssue := range apiIssues {
models.AssertExistsAndLoadBean(t, &models.Issue{ID: apiIssue.ID, RepoID: repo.ID})
db.AssertExistsAndLoadBean(t, &models.Issue{ID: apiIssue.ID, RepoID: repo.ID})
}
// test milestone filter
@ -71,8 +72,8 @@ func TestAPICreateIssue(t *testing.T) {
defer prepareTestEnv(t)()
const body, title = "apiTestBody", "apiTestTitle"
repoBefore := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User)
repoBefore := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
@ -88,14 +89,14 @@ func TestAPICreateIssue(t *testing.T) {
assert.Equal(t, body, apiIssue.Body)
assert.Equal(t, title, apiIssue.Title)
models.AssertExistsAndLoadBean(t, &models.Issue{
db.AssertExistsAndLoadBean(t, &models.Issue{
RepoID: repoBefore.ID,
AssigneeID: owner.ID,
Content: body,
Title: title,
})
repoAfter := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repoAfter := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
assert.Equal(t, repoBefore.NumIssues+1, repoAfter.NumIssues)
assert.Equal(t, repoBefore.NumClosedIssues, repoAfter.NumClosedIssues)
}
@ -103,9 +104,9 @@ func TestAPICreateIssue(t *testing.T) {
func TestAPIEditIssue(t *testing.T) {
defer prepareTestEnv(t)()
issueBefore := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 10}).(*models.Issue)
repoBefore := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issueBefore.RepoID}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User)
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)
assert.NoError(t, issueBefore.LoadAttributes())
assert.Equal(t, int64(1019307200), int64(issueBefore.DeadlineUnix))
assert.Equal(t, api.StateOpen, issueBefore.State())
@ -134,8 +135,8 @@ func TestAPIEditIssue(t *testing.T) {
var apiIssue api.Issue
DecodeJSON(t, resp, &apiIssue)
issueAfter := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 10}).(*models.Issue)
repoAfter := models.AssertExistsAndLoadBean(t, &models.Repository{ID: issueBefore.RepoID}).(*models.Repository)
issueAfter := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 10}).(*models.Issue)
repoAfter := db.AssertExistsAndLoadBean(t, &models.Repository{ID: issueBefore.RepoID}).(*models.Repository)
// check deleted user
assert.Equal(t, int64(500), issueAfter.PosterID)

View File

@ -11,6 +11,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -19,8 +20,8 @@ import (
func TestAPIGetTrackedTimes(t *testing.T) {
defer prepareTestEnv(t)()
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
issue2 := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
issue2 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
assert.NoError(t, issue2.LoadRepo())
session := loginUser(t, user2.Name)
@ -61,10 +62,10 @@ func TestAPIGetTrackedTimes(t *testing.T) {
func TestAPIDeleteTrackedTime(t *testing.T) {
defer prepareTestEnv(t)()
time6 := models.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 6}).(*models.TrackedTime)
issue2 := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
time6 := db.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 6}).(*models.TrackedTime)
issue2 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
assert.NoError(t, issue2.LoadRepo())
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
session := loginUser(t, user2.Name)
token := getTokenForLoggedInUser(t, session)
@ -73,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 := models.AssertExistsAndLoadBean(t, &models.TrackedTime{ID: 3}).(*models.TrackedTime)
time3 := db.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
@ -96,10 +97,10 @@ func TestAPIDeleteTrackedTime(t *testing.T) {
func TestAPIAddTrackedTimes(t *testing.T) {
defer prepareTestEnv(t)()
issue2 := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
issue2 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue)
assert.NoError(t, issue2.LoadRepo())
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
admin := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
admin := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
session := loginUser(t, admin.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -45,8 +46,8 @@ func TestDeleteDeployKeyNoLogin(t *testing.T) {
func TestCreateReadOnlyDeployKey(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository)
repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository)
repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, repoOwner.Name)
token := getTokenForLoggedInUser(t, session)
@ -61,7 +62,7 @@ func TestCreateReadOnlyDeployKey(t *testing.T) {
var newDeployKey api.DeployKey
DecodeJSON(t, resp, &newDeployKey)
models.AssertExistsAndLoadBean(t, &models.DeployKey{
db.AssertExistsAndLoadBean(t, &models.DeployKey{
ID: newDeployKey.ID,
Name: rawKeyBody.Title,
Content: rawKeyBody.Key,
@ -71,8 +72,8 @@ func TestCreateReadOnlyDeployKey(t *testing.T) {
func TestCreateReadWriteDeployKey(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository)
repoOwner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{Name: "repo1"}).(*models.Repository)
repoOwner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, repoOwner.Name)
token := getTokenForLoggedInUser(t, session)
@ -86,7 +87,7 @@ func TestCreateReadWriteDeployKey(t *testing.T) {
var newDeployKey api.DeployKey
DecodeJSON(t, resp, &newDeployKey)
models.AssertExistsAndLoadBean(t, &models.DeployKey{
db.AssertExistsAndLoadBean(t, &models.DeployKey{
ID: newDeployKey.ID,
Name: rawKeyBody.Title,
Content: rawKeyBody.Key,
@ -96,7 +97,7 @@ func TestCreateReadWriteDeployKey(t *testing.T) {
func TestCreateUserKey(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User)
session := loginUser(t, "user1")
token := url.QueryEscape(getTokenForLoggedInUser(t, session))
@ -112,7 +113,7 @@ func TestCreateUserKey(t *testing.T) {
var newPublicKey api.PublicKey
DecodeJSON(t, resp, &newPublicKey)
models.AssertExistsAndLoadBean(t, &models.PublicKey{
db.AssertExistsAndLoadBean(t, &models.PublicKey{
ID: newPublicKey.ID,
OwnerID: user.ID,
Name: rawKeyBody.Title,

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -18,9 +19,9 @@ import (
func TestAPINotification(t *testing.T) {
defer prepareTestEnv(t)()
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
thread5 := models.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification)
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)
assert.NoError(t, thread5.LoadAttributes())
session := loginUser(t, user2.Name)
token := getTokenForLoggedInUser(t, session)
@ -111,7 +112,7 @@ func TestAPINotification(t *testing.T) {
resp = session.MakeRequest(t, req, http.StatusResetContent)
assert.Equal(t, models.NotificationStatusUnread, thread5.Status)
thread5 = models.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification)
thread5 = db.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification)
assert.Equal(t, models.NotificationStatusRead, thread5.Status)
// -- check notifications --

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -25,7 +26,7 @@ func TestOAuth2Application(t *testing.T) {
}
func testAPICreateOAuth2Application(t *testing.T) {
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
appBody := api.CreateOAuth2ApplicationOptions{
Name: "test-app-1",
RedirectURIs: []string{
@ -45,15 +46,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])
models.AssertExistsAndLoadBean(t, &models.OAuth2Application{UID: user.ID, Name: createdApp.Name})
db.AssertExistsAndLoadBean(t, &models.OAuth2Application{UID: user.ID, Name: createdApp.Name})
}
func testAPIListOAuth2Applications(t *testing.T) {
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
existApp := models.AssertExistsAndLoadBean(t, &models.OAuth2Application{
existApp := db.AssertExistsAndLoadBean(t, &models.OAuth2Application{
UID: user.ID,
Name: "test-app-1",
RedirectURIs: []string{
@ -74,15 +75,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])
models.AssertExistsAndLoadBean(t, &models.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name})
db.AssertExistsAndLoadBean(t, &models.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name})
}
func testAPIDeleteOAuth2Application(t *testing.T) {
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
oldApp := models.AssertExistsAndLoadBean(t, &models.OAuth2Application{
oldApp := db.AssertExistsAndLoadBean(t, &models.OAuth2Application{
UID: user.ID,
Name: "test-app-1",
}).(*models.OAuth2Application)
@ -91,7 +92,7 @@ func testAPIDeleteOAuth2Application(t *testing.T) {
req := NewRequest(t, "DELETE", urlStr)
session.MakeRequest(t, req, http.StatusNoContent)
models.AssertNotExistsBean(t, &models.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name})
db.AssertNotExistsBean(t, &models.OAuth2Application{UID: oldApp.UID, Name: oldApp.Name})
// Delete again will return not found
req = NewRequest(t, "DELETE", urlStr)
@ -99,11 +100,11 @@ func testAPIDeleteOAuth2Application(t *testing.T) {
}
func testAPIGetOAuth2Application(t *testing.T) {
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
existApp := models.AssertExistsAndLoadBean(t, &models.OAuth2Application{
existApp := db.AssertExistsAndLoadBean(t, &models.OAuth2Application{
UID: user.ID,
Name: "test-app-1",
RedirectURIs: []string{
@ -125,13 +126,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])
models.AssertExistsAndLoadBean(t, &models.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name})
db.AssertExistsAndLoadBean(t, &models.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name})
}
func testAPIUpdateOAuth2Application(t *testing.T) {
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
existApp := models.AssertExistsAndLoadBean(t, &models.OAuth2Application{
existApp := db.AssertExistsAndLoadBean(t, &models.OAuth2Application{
UID: user.ID,
Name: "test-app-1",
RedirectURIs: []string{
@ -159,5 +160,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])
models.AssertExistsAndLoadBean(t, &models.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name})
db.AssertExistsAndLoadBean(t, &models.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name})
}

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -43,7 +44,7 @@ func TestAPIOrgCreate(t *testing.T) {
assert.Equal(t, org.Location, apiOrg.Location)
assert.Equal(t, org.Visibility, apiOrg.Visibility)
models.AssertExistsAndLoadBean(t, &models.User{
db.AssertExistsAndLoadBean(t, &models.User{
Name: org.UserName,
LowerName: strings.ToLower(org.UserName),
FullName: org.FullName,

View File

@ -9,15 +9,16 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
)
func TestAPIPullCommits(t *testing.T) {
defer prepareTestEnv(t)()
pullIssue := models.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest)
pullIssue := db.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 2}).(*models.PullRequest)
assert.NoError(t, pullIssue.LoadIssue())
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.HeadRepoID}).(*models.Repository)
repo := db.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)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/json"
api "code.gitea.io/gitea/modules/structs"
@ -18,9 +19,9 @@ import (
func TestAPIPullReview(t *testing.T) {
defer prepareTestEnv(t)()
pullIssue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue)
pullIssue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue)
assert.NoError(t, pullIssue.LoadAttributes())
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.RepoID}).(*models.Repository)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.RepoID}).(*models.Repository)
// test ListPullReviews
session := loginUser(t, "user2")
@ -62,7 +63,7 @@ func TestAPIPullReview(t *testing.T) {
assert.EqualValues(t, *reviews[5], review)
// test GetPullReviewComments
comment := models.AssertExistsAndLoadBean(t, &models.Comment{ID: 7}).(*models.Comment)
comment := db.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
@ -195,9 +196,9 @@ func TestAPIPullReview(t *testing.T) {
// test get review requests
// to make it simple, use same api with get review
pullIssue12 := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 12}).(*models.Issue)
pullIssue12 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 12}).(*models.Issue)
assert.NoError(t, pullIssue12.LoadAttributes())
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue12.RepoID}).(*models.Repository)
repo3 := db.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)
@ -219,9 +220,9 @@ func TestAPIPullReview(t *testing.T) {
func TestAPIPullReviewRequest(t *testing.T) {
defer prepareTestEnv(t)()
pullIssue := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue)
pullIssue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 3}).(*models.Issue)
assert.NoError(t, pullIssue.LoadAttributes())
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.RepoID}).(*models.Repository)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue.RepoID}).(*models.Repository)
// Test add Review Request
session := loginUser(t, "user2")
@ -264,9 +265,9 @@ func TestAPIPullReviewRequest(t *testing.T) {
session.MakeRequest(t, req, http.StatusNoContent)
// Test team review request
pullIssue12 := models.AssertExistsAndLoadBean(t, &models.Issue{ID: 12}).(*models.Issue)
pullIssue12 := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 12}).(*models.Issue)
assert.NoError(t, pullIssue12.LoadAttributes())
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: pullIssue12.RepoID}).(*models.Repository)
repo3 := db.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{

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/services/forms"
@ -20,8 +21,8 @@ import (
func TestAPIViewPulls(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, "user2")
token := getTokenForLoggedInUser(t, session)
@ -30,16 +31,16 @@ func TestAPIViewPulls(t *testing.T) {
var pulls []*api.PullRequest
DecodeJSON(t, resp, &pulls)
expectedLen := models.GetCount(t, &models.Issue{RepoID: repo.ID}, models.Cond("is_pull = ?", true))
expectedLen := db.GetCount(t, &models.Issue{RepoID: repo.ID}, db.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 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
pr := models.AssertExistsAndLoadBean(t, &models.PullRequest{Status: models.PullRequestStatusMergeable}, models.Cond("has_merged = ?", false)).(*models.PullRequest)
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)
pr.LoadIssue()
issue_service.ChangeTitle(pr.Issue, owner, setting.Repository.PullRequest.WorkInProgressPrefixes[0]+" "+pr.Issue.Title)
@ -60,12 +61,12 @@ func TestAPIMergePullWIP(t *testing.T) {
func TestAPICreatePullSuccess(t *testing.T) {
defer prepareTestEnv(t)()
repo10 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
repo10 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
// repo10 have code, pulls units.
repo11 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository)
repo11 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository)
// repo11 only have code unit but should still create pulls
owner10 := models.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User)
owner11 := models.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User)
owner10 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User)
owner11 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User)
session := loginUser(t, owner11.Name)
token := getTokenForLoggedInUser(t, session)
@ -81,11 +82,11 @@ func TestAPICreatePullSuccess(t *testing.T) {
func TestAPICreatePullWithFieldsSuccess(t *testing.T) {
defer prepareTestEnv(t)()
// repo10 have code, pulls units.
repo10 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
owner10 := models.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User)
repo10 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
owner10 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User)
// repo11 only have code unit but should still create pulls
repo11 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository)
owner11 := models.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User)
repo11 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository)
owner11 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User)
session := loginUser(t, owner11.Name)
token := getTokenForLoggedInUser(t, session)
@ -118,11 +119,11 @@ func TestAPICreatePullWithFieldsSuccess(t *testing.T) {
func TestAPICreatePullWithFieldsFailure(t *testing.T) {
defer prepareTestEnv(t)()
// repo10 have code, pulls units.
repo10 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
owner10 := models.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User)
repo10 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
owner10 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User)
// repo11 only have code unit but should still create pulls
repo11 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository)
owner11 := models.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User)
repo11 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 11}).(*models.Repository)
owner11 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo11.OwnerID}).(*models.User)
session := loginUser(t, owner11.Name)
token := getTokenForLoggedInUser(t, session)
@ -151,8 +152,8 @@ func TestAPICreatePullWithFieldsFailure(t *testing.T) {
func TestAPIEditPull(t *testing.T) {
defer prepareTestEnv(t)()
repo10 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
owner10 := models.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User)
repo10 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 10}).(*models.Repository)
owner10 := db.AssertExistsAndLoadBean(t, &models.User{ID: repo10.OwnerID}).(*models.User)
session := loginUser(t, owner10.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/git"
api "code.gitea.io/gitea/modules/structs"
@ -20,8 +21,8 @@ import (
func TestAPIListReleases(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
session := loginUser(t, user2.LowerName)
token := getTokenForLoggedInUser(t, session)
@ -84,7 +85,7 @@ func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string,
var newRelease api.Release
DecodeJSON(t, resp, &newRelease)
models.AssertExistsAndLoadBean(t, &models.Release{
db.AssertExistsAndLoadBean(t, &models.Release{
ID: newRelease.ID,
TagName: newRelease.TagName,
Title: newRelease.Title,
@ -97,8 +98,8 @@ func createNewReleaseUsingAPI(t *testing.T, session *TestSession, token string,
func TestAPICreateAndUpdateRelease(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session)
@ -137,7 +138,7 @@ func TestAPICreateAndUpdateRelease(t *testing.T) {
resp = session.MakeRequest(t, req, http.StatusOK)
DecodeJSON(t, resp, &newRelease)
models.AssertExistsAndLoadBean(t, &models.Release{
db.AssertExistsAndLoadBean(t, &models.Release{
ID: newRelease.ID,
TagName: newRelease.TagName,
Title: newRelease.Title,
@ -148,8 +149,8 @@ func TestAPICreateAndUpdateRelease(t *testing.T) {
func TestAPICreateReleaseToDefaultBranch(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session)
@ -159,8 +160,8 @@ func TestAPICreateReleaseToDefaultBranch(t *testing.T) {
func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session)
@ -177,8 +178,8 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) {
func TestAPIGetReleaseByTag(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.LowerName)
tag := "v1.1"
@ -210,8 +211,8 @@ func TestAPIGetReleaseByTag(t *testing.T) {
func TestAPIDeleteReleaseByTagName(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session)

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -132,13 +133,13 @@ func TestAPIRepoEdit(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
bFalse, bTrue := false, true
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo15 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 15}).(*models.Repository) // empty repo
repo16 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
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
// Get user2's token
session := loginUser(t, user2.Name)
@ -164,7 +165,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 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1edited := db.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)
@ -189,7 +190,7 @@ func TestAPIRepoEdit(t *testing.T) {
DecodeJSON(t, resp, &repo)
assert.NotNil(t, repo)
// check repo1 was written to database
repo1edited = models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1edited = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1editedOption = getRepoEditOptionFromRepo(repo1edited)
assert.Equal(t, *repo1editedOption.HasIssues, true)
assert.Nil(t, repo1editedOption.ExternalTracker)
@ -211,7 +212,7 @@ func TestAPIRepoEdit(t *testing.T) {
DecodeJSON(t, resp, &repo)
assert.NotNil(t, repo)
// check repo1 was written to database
repo1edited = models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1edited = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1editedOption = getRepoEditOptionFromRepo(repo1edited)
assert.Equal(t, *repo1editedOption.HasIssues, true)
assert.Equal(t, *repo1editedOption.ExternalTracker, *repoEditOption.ExternalTracker)
@ -242,7 +243,7 @@ func TestAPIRepoEdit(t *testing.T) {
DecodeJSON(t, resp, &repo)
assert.NotNil(t, repo)
// check repo1 was written to database
repo1edited = models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1edited = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo1editedOption = getRepoEditOptionFromRepo(repo1edited)
assert.Equal(t, *repo1editedOption.Description, *repoEditOption.Description)
assert.Equal(t, *repo1editedOption.HasIssues, true)
@ -287,7 +288,7 @@ func TestAPIRepoEdit(t *testing.T) {
_ = session.MakeRequest(t, req, http.StatusOK)
// Test making a repo public that is private
repo16 = models.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository)
repo16 = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository)
assert.True(t, repo16.IsPrivate)
repoEditOption = &api.EditRepoOption{
Private: &bFalse,
@ -295,7 +296,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 = models.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository)
repo16 = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository)
assert.False(t, repo16.IsPrivate)
// Make it private again
repoEditOption.Private = &bTrue
@ -309,7 +310,7 @@ func TestAPIRepoEdit(t *testing.T) {
Archived: &bTrue,
})
_ = session.MakeRequest(t, req, http.StatusOK)
repo15 = models.AssertExistsAndLoadBean(t, &models.Repository{ID: 15}).(*models.Repository)
repo15 = db.AssertExistsAndLoadBean(t, &models.Repository{ID: 15}).(*models.Repository)
assert.True(t, repo15.IsArchived)
req = NewRequestWithJSON(t, "PATCH", url, &api.EditRepoOption{
Archived: &bFalse,

View File

@ -14,6 +14,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting"
@ -108,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 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
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
for n := 0; n < b.N; n++ {
treePath := fmt.Sprintf("update/file%d.txt", n)
@ -123,8 +124,8 @@ func BenchmarkAPICreateFileMedium(b *testing.B) {
onGiteaRunTB(b, func(t testing.TB, u *url.URL) {
b := t.(*testing.B)
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
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
b.ResetTimer()
for n := 0; n < b.N; n++ {
@ -137,12 +138,12 @@ func BenchmarkAPICreateFileMedium(b *testing.B) {
func TestAPICreateFile(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
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
fileID := 0
// Get user2's token

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -37,12 +38,12 @@ func getDeleteFileOptions() *api.DeleteFileOptions {
func TestAPIDeleteFile(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
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
fileID := 0
// Get user2's token

View File

@ -13,6 +13,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/setting"
@ -103,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 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
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
fileID := 0
// Get user2's token

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/git"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
@ -52,13 +53,13 @@ func TestAPIGetContentsList(t *testing.T) {
func testAPIGetContentsList(t *testing.T, u *url.URL) {
/*** SETUP ***/
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
treePath := "" // root dir
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
// Get user2's token
session := loginUser(t, user2.Name)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/git"
repo_module "code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
@ -53,12 +54,12 @@ func TestAPIGetContents(t *testing.T) {
func testAPIGetContents(t *testing.T, u *url.URL) {
/*** SETUP ***/
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3, is an org
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
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 := "README.md"
// Get user2's token

View File

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -16,12 +17,12 @@ import (
func TestAPIReposGitBlobs(t *testing.T) {
defer prepareTestEnv(t)()
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
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
repo1ReadmeSHA := "65f1bf27bc3bf70f64657658635e66094edbcb4d"
repo3ReadmeSHA := "d56a3073c1dbb7b15963110a049d50cdb5db99fc"
repo16ReadmeSHA := "f90451c72ef61a7645293d17b47be7a8e983da57"

View File

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -24,7 +25,7 @@ func compareCommitFiles(t *testing.T, expect []string, files []*api.CommitAffect
func TestAPIReposGitCommits(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
@ -52,7 +53,7 @@ func TestAPIReposGitCommits(t *testing.T) {
func TestAPIReposGitCommitList(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
@ -75,7 +76,7 @@ func TestAPIReposGitCommitList(t *testing.T) {
func TestAPIReposGitCommitListPage2Empty(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
@ -92,7 +93,7 @@ func TestAPIReposGitCommitListPage2Empty(t *testing.T) {
func TestAPIReposGitCommitListDifferentBranch(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -23,8 +24,8 @@ echo Hello, World!
func TestAPIListGitHooks(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
// user1 is an admin user
session := loginUser(t, "user1")
@ -49,8 +50,8 @@ func TestAPIListGitHooks(t *testing.T) {
func TestAPIListGitHooksNoHooks(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
// user1 is an admin user
session := loginUser(t, "user1")
@ -70,8 +71,8 @@ func TestAPIListGitHooksNoHooks(t *testing.T) {
func TestAPIListGitHooksNoAccess(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
@ -83,8 +84,8 @@ func TestAPIListGitHooksNoAccess(t *testing.T) {
func TestAPIGetGitHook(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
// user1 is an admin user
session := loginUser(t, "user1")
@ -101,8 +102,8 @@ func TestAPIGetGitHook(t *testing.T) {
func TestAPIGetGitHookNoAccess(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
@ -114,8 +115,8 @@ func TestAPIGetGitHookNoAccess(t *testing.T) {
func TestAPIEditGitHook(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
// user1 is an admin user
session := loginUser(t, "user1")
@ -144,8 +145,8 @@ func TestAPIEditGitHook(t *testing.T) {
func TestAPIEditGitHookNoAccess(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)
@ -160,8 +161,8 @@ func TestAPIEditGitHookNoAccess(t *testing.T) {
func TestAPIDeleteGitHook(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 37}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
// user1 is an admin user
session := loginUser(t, "user1")
@ -183,8 +184,8 @@ func TestAPIDeleteGitHook(t *testing.T) {
func TestAPIDeleteGitHookNoAccess(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -10,13 +10,14 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
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 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -9,11 +9,12 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
)
func TestAPIReposGitRefs(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/git"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
@ -19,8 +20,8 @@ import (
func TestAPIGitTags(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
@ -64,8 +65,8 @@ func TestAPIGitTags(t *testing.T) {
func TestAPIDeleteTagByName(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
session := loginUser(t, owner.LowerName)
token := getTokenForLoggedInUser(t, session)

View File

@ -9,16 +9,17 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
)
func TestAPIReposGitTrees(t *testing.T) {
defer prepareTestEnv(t)()
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo1 & repo16
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of the repo3
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // owner of neither repos
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) // public repo
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // public repo
repo16 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 16}).(*models.Repository) // private repo
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
repo1TreeSHA := "65f1bf27bc3bf70f64657658635e66094edbcb4d"
repo3TreeSHA := "2a47ca4b614a9f5a43abbd5ad851a54a616ffee6"
repo16TreeSHA := "69554a64c1e6030f051e5c3f94bfbd773cd6a324"

View File

@ -11,6 +11,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -21,8 +22,8 @@ import (
func TestAPILFSLocksNotStarted(t *testing.T) {
defer prepareTestEnv(t)()
setting.LFS.StartServer = false
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := db.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)
@ -37,8 +38,8 @@ func TestAPILFSLocksNotStarted(t *testing.T) {
func TestAPILFSLocksNotLogin(t *testing.T) {
defer prepareTestEnv(t)()
setting.LFS.StartServer = true
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := db.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)
@ -51,11 +52,11 @@ func TestAPILFSLocksNotLogin(t *testing.T) {
func TestAPILFSLocksLogged(t *testing.T) {
defer prepareTestEnv(t)()
setting.LFS.StartServer = true
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) //in org 3
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) //in org 3
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
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) // own by 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
tests := []struct {
user *models.User

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -25,7 +26,7 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) {
setting.ImportLocalPaths = true
setting.Migrations.AllowLocalNetworks = true
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -13,6 +13,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/setting"
@ -25,8 +26,8 @@ func TestAPILFSNotStarted(t *testing.T) {
setting.LFS.StartServer = false
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := db.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)
@ -45,8 +46,8 @@ func TestAPILFSMediaType(t *testing.T) {
setting.LFS.StartServer = true
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := db.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)

View File

@ -9,11 +9,12 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
)
func TestAPIReposRaw(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -18,7 +19,7 @@ import (
func TestAPIRepoTags(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
// Login as User2.
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -19,9 +20,9 @@ func TestAPIRepoTeams(t *testing.T) {
defer prepareTestEnv(t)()
// publicOrgRepo = user3/repo21
publicOrgRepo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 32}).(*models.Repository)
publicOrgRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 32}).(*models.Repository)
// user4
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
@ -61,7 +62,7 @@ func TestAPIRepoTeams(t *testing.T) {
res = session.MakeRequest(t, req, http.StatusForbidden)
// AddTeam with user2
user = models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user = db.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)

View File

@ -12,6 +12,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
@ -21,15 +22,15 @@ import (
func TestAPIUserReposNotLogin(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.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 := models.GetCount(t, models.Repository{OwnerID: user.ID},
models.Cond("is_private = ?", false))
expectedLen := db.GetCount(t, models.Repository{OwnerID: user.ID},
db.Cond("is_private = ?", false))
assert.Len(t, apiRepos, expectedLen)
for _, repo := range apiRepos {
assert.EqualValues(t, user.ID, repo.Owner.ID)
@ -52,11 +53,11 @@ func TestAPISearchRepo(t *testing.T) {
assert.False(t, repo.Private)
}
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 15}).(*models.User)
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 16}).(*models.User)
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 18}).(*models.User)
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 20}).(*models.User)
orgUser := models.AssertExistsAndLoadBean(t, &models.User{ID: 17}).(*models.User)
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)
oldAPIDefaultNum := setting.API.DefaultPagingNum
defer func() {
@ -208,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] = models.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.Repository)
repoCache[repoID] = db.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.Repository)
}
return repoCache[repoID]
}
@ -245,11 +246,11 @@ func TestAPIViewRepo(t *testing.T) {
func TestAPIOrgRepos(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User)
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)
// User3 is an Org. Check their repos.
sourceOrg := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)
sourceOrg := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)
expectedResults := map[*models.User]struct {
count int
@ -291,7 +292,7 @@ func TestAPIOrgRepos(t *testing.T) {
func TestAPIGetRepoByIDUnauthorized(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User)
user := db.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)
@ -315,7 +316,7 @@ func TestAPIRepoMigrate(t *testing.T) {
defer prepareTestEnv(t)()
for _, testCase := range testCases {
user := models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User)
user := db.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{
@ -394,7 +395,7 @@ func TestAPIOrgRepoCreate(t *testing.T) {
defer prepareTestEnv(t)()
for _, testCase := range testCases {
user := models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User)
user := db.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{
@ -462,7 +463,7 @@ func TestAPIRepoTransfer(t *testing.T) {
defer prepareTestEnv(t)()
//create repo to move
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
repoName := "moveME"
@ -479,8 +480,8 @@ func TestAPIRepoTransfer(t *testing.T) {
//start testing
for _, testCase := range testCases {
user = models.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: apiRepo.ID}).(*models.Repository)
user = db.AssertExistsAndLoadBean(t, &models.User{ID: testCase.ctxUserID}).(*models.User)
repo := db.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{
@ -491,18 +492,18 @@ func TestAPIRepoTransfer(t *testing.T) {
}
//cleanup
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: apiRepo.ID}).(*models.Repository)
repo := db.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 := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
templateRepo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 44}).(*models.Repository)
templateRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 44}).(*models.Repository)
// user
repo := new(api.Repository)
@ -534,10 +535,10 @@ func TestAPIGenerateRepo(t *testing.T) {
func TestAPIRepoGetReviewers(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := db.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)
@ -548,10 +549,10 @@ func TestAPIRepoGetReviewers(t *testing.T) {
func TestAPIRepoGetAssignees(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := db.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)

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -50,11 +51,11 @@ func TestAPITopicSearch(t *testing.T) {
func TestAPIRepoTopic(t *testing.T) {
defer prepareTestEnv(t)()
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of repo2
user3 := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) // owner of repo3
user4 := models.AssertExistsAndLoadBean(t, &models.User{ID: 4}).(*models.User) // write access to repo 3
repo2 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository)
repo3 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository)
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)
// Get user2's token
session := loginUser(t, user2.Name)

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/convert"
api "code.gitea.io/gitea/modules/structs"
@ -20,9 +21,9 @@ import (
func TestAPITeam(t *testing.T) {
defer prepareTestEnv(t)()
teamUser := models.AssertExistsAndLoadBean(t, &models.TeamUser{}).(*models.TeamUser)
team := models.AssertExistsAndLoadBean(t, &models.Team{ID: teamUser.TeamID}).(*models.Team)
user := models.AssertExistsAndLoadBean(t, &models.User{ID: teamUser.UID}).(*models.User)
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)
session := loginUser(t, user.Name)
token := getTokenForLoggedInUser(t, session)
@ -35,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 := models.AssertExistsAndLoadBean(t, &models.TeamUser{ID: 3}).(*models.TeamUser)
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: teamUser2.UID}).(*models.User)
teamUser2 := db.AssertExistsAndLoadBean(t, &models.TeamUser{ID: 3}).(*models.TeamUser)
user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: teamUser2.UID}).(*models.User)
session = loginUser(t, user2.Name)
token = getTokenForLoggedInUser(t, session)
@ -47,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 = models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
user = db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
session = loginUser(t, user.Name)
token = getTokenForLoggedInUser(t, session)
org := models.AssertExistsAndLoadBean(t, &models.User{ID: 6}).(*models.User)
org := db.AssertExistsAndLoadBean(t, &models.User{ID: 6}).(*models.User)
// Create team.
teamToCreate := &api.CreateTeamOption{
@ -101,7 +102,7 @@ func TestAPITeam(t *testing.T) {
teamToEdit.Permission, teamToEdit.Units)
// Read team.
teamRead := models.AssertExistsAndLoadBean(t, &models.Team{ID: teamID}).(*models.Team)
teamRead := db.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)
@ -111,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)
models.AssertNotExistsBean(t, &models.Team{ID: teamID})
db.AssertNotExistsBean(t, &models.Team{ID: teamID})
}
func checkTeamResponse(t *testing.T, apiTeam *api.Team, name, description string, includesAllRepositories bool, permission string, units []string) {
@ -125,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 := models.AssertExistsAndLoadBean(t, &models.Team{ID: id}).(*models.Team)
team := db.AssertExistsAndLoadBean(t, &models.Team{ID: id}).(*models.Team)
assert.NoError(t, team.GetUnits(), "GetUnits")
checkTeamResponse(t, convert.ToTeam(team), name, description, includesAllRepositories, permission, units)
}
@ -138,8 +139,8 @@ type TeamSearchResults struct {
func TestAPITeamSearch(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
org := models.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
org := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User)
var results TeamSearchResults
@ -154,7 +155,7 @@ func TestAPITeamSearch(t *testing.T) {
assert.Equal(t, "test_team", results.Data[0].Name)
// no access if not organization member
user5 := models.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User)
user5 := db.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")

View File

@ -10,6 +10,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/convert"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -29,7 +30,7 @@ func TestAPITeamUser(t *testing.T) {
var user2 *api.User
DecodeJSON(t, resp, &user2)
user2.Created = user2.Created.In(time.Local)
user := models.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User)
expectedUser := convert.ToUser(user, user)

View File

@ -9,13 +9,14 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
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 := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
req := NewRequestWithJSON(t, "POST", "/api/v1/users/user1/tokens", map[string]string{
"name": "test-key-1",
@ -25,7 +26,7 @@ func TestAPICreateAndDeleteToken(t *testing.T) {
var newAccessToken api.AccessToken
DecodeJSON(t, resp, &newAccessToken)
models.AssertExistsAndLoadBean(t, &models.AccessToken{
db.AssertExistsAndLoadBean(t, &models.AccessToken{
ID: newAccessToken.ID,
Name: newAccessToken.Name,
Token: newAccessToken.Token,
@ -36,7 +37,7 @@ func TestAPICreateAndDeleteToken(t *testing.T) {
req = AddBasicAuthHeader(req, user.Name)
MakeRequest(t, req, http.StatusNoContent)
models.AssertNotExistsBean(t, &models.AccessToken{ID: newAccessToken.ID})
db.AssertNotExistsBean(t, &models.AccessToken{ID: newAccessToken.ID})
req = NewRequestWithJSON(t, "POST", "/api/v1/users/user1/tokens", map[string]string{
"name": "test-key-2",
@ -49,15 +50,15 @@ func TestAPICreateAndDeleteToken(t *testing.T) {
req = AddBasicAuthHeader(req, user.Name)
MakeRequest(t, req, http.StatusNoContent)
models.AssertNotExistsBean(t, &models.AccessToken{ID: newAccessToken.ID})
db.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 := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
req := NewRequestf(t, "DELETE", "/api/v1/users/user1/tokens/%d", models.NonexistentID)
req := NewRequestf(t, "DELETE", "/api/v1/users/user1/tokens/%d", db.NonexistentID)
req = AddBasicAuthHeader(req, user.Name)
MakeRequest(t, req, http.StatusNotFound)
}

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -24,7 +25,7 @@ func TestUserOrgs(t *testing.T) {
orgs := getUserOrgs(t, adminUsername, normalUsername)
user3 := models.AssertExistsAndLoadBean(t, &models.User{Name: "user3"}).(*models.User)
user3 := db.AssertExistsAndLoadBean(t, &models.User{Name: "user3"}).(*models.User)
assert.Equal(t, []*api.Organization{
{
@ -80,7 +81,7 @@ func TestMyOrgs(t *testing.T) {
resp = session.MakeRequest(t, req, http.StatusOK)
var orgs []*api.Organization
DecodeJSON(t, resp, &orgs)
user3 := models.AssertExistsAndLoadBean(t, &models.User{Name: "user3"}).(*models.User)
user3 := db.AssertExistsAndLoadBean(t, &models.User{Name: "user3"}).(*models.User)
assert.Equal(t, []*api.Organization{
{

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -51,7 +52,7 @@ func TestAPIUserSearchNotLoggedIn(t *testing.T) {
var modelUser *models.User
for _, user := range results.Data {
assert.Contains(t, user.UserName, query)
modelUser = models.AssertExistsAndLoadBean(t, &models.User{ID: user.ID}).(*models.User)
modelUser = db.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 {

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
)
@ -32,7 +33,7 @@ func BenchmarkRepoBranchCommit(b *testing.B) {
for _, repoID := range samples {
b.StopTimer()
repo := models.AssertExistsAndLoadBean(b, &models.Repository{ID: repoID}).(*models.Repository)
repo := db.AssertExistsAndLoadBean(b, &models.Repository{ID: repoID}).(*models.Repository)
b.StartTimer()
b.Run(repo.Name, func(b *testing.B) {
session := loginUser(b, "user2")

View File

@ -10,12 +10,13 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
)
func TestChangeDefaultBranch(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.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)

View File

@ -10,18 +10,19 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
)
func assertUserDeleted(t *testing.T, userID int64) {
models.AssertNotExistsBean(t, &models.User{ID: userID})
models.AssertNotExistsBean(t, &models.Follow{UserID: userID})
models.AssertNotExistsBean(t, &models.Follow{FollowID: userID})
models.AssertNotExistsBean(t, &models.Repository{OwnerID: userID})
models.AssertNotExistsBean(t, &models.Access{UserID: userID})
models.AssertNotExistsBean(t, &models.OrgUser{UID: userID})
models.AssertNotExistsBean(t, &models.IssueUser{UID: userID})
models.AssertNotExistsBean(t, &models.TeamUser{UID: userID})
models.AssertNotExistsBean(t, &models.Star{UID: userID})
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})
}
func TestUserDeleteAccount(t *testing.T) {
@ -51,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
models.AssertExistsAndLoadBean(t, &models.User{ID: 2})
db.AssertExistsAndLoadBean(t, &models.User{ID: 2})
}

View File

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
)
func TestEmptyRepo(t *testing.T) {
@ -19,8 +20,8 @@ func TestEmptyRepo(t *testing.T) {
"commit/1ae57b34ccf7e18373",
"graph",
}
emptyRepo := models.AssertExistsAndLoadBean(t, &models.Repository{}, models.Cond("is_empty = ?", true)).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: emptyRepo.OwnerID}).(*models.User)
emptyRepo := db.AssertExistsAndLoadBean(t, &models.Repository{}, db.Cond("is_empty = ?", true)).(*models.Repository)
owner := db.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)

View File

@ -11,6 +11,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/eventsource"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -49,9 +50,9 @@ func TestEventSourceManagerRun(t *testing.T) {
}
}
user2 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
thread5 := models.AssertExistsAndLoadBean(t, &models.Notification{ID: 5}).(*models.Notification)
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)
assert.NoError(t, thread5.LoadAttributes())
session := loginUser(t, user2.Name)
token := getTokenForLoggedInUser(t, session)

View File

@ -18,6 +18,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/lfs"
"code.gitea.io/gitea/modules/setting"
@ -630,7 +631,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
return
}
pullNum := models.GetCount(t, &models.PullRequest{})
pullNum := db.GetCount(t, &models.PullRequest{})
t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
@ -666,8 +667,8 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
if !assert.NoError(t, err) {
return
}
models.AssertCount(t, &models.PullRequest{}, pullNum+1)
pr1 = models.AssertExistsAndLoadBean(t, &models.PullRequest{
db.AssertCount(t, &models.PullRequest{}, pullNum+1)
pr1 = db.AssertExistsAndLoadBean(t, &models.PullRequest{
HeadRepoID: repo.ID,
Flow: models.PullRequestFlowAGit,
}).(*models.PullRequest)
@ -687,8 +688,8 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
if !assert.NoError(t, err) {
return
}
models.AssertCount(t, &models.PullRequest{}, pullNum+2)
pr2 = models.AssertExistsAndLoadBean(t, &models.PullRequest{
db.AssertCount(t, &models.PullRequest{}, pullNum+2)
pr2 = db.AssertExistsAndLoadBean(t, &models.PullRequest{
HeadRepoID: repo.ID,
Index: pr1.Index + 1,
Flow: models.PullRequestFlowAGit,
@ -740,7 +741,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
if !assert.NoError(t, err) {
return
}
models.AssertCount(t, &models.PullRequest{}, pullNum+2)
db.AssertCount(t, &models.PullRequest{}, pullNum+2)
prMsg, err := doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr1.Index)(t)
if !assert.NoError(t, err) {
return
@ -752,7 +753,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB
if !assert.NoError(t, err) {
return
}
models.AssertCount(t, &models.PullRequest{}, pullNum+2)
db.AssertCount(t, &models.PullRequest{}, pullNum+2)
prMsg, err = doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr2.Index)(t)
if !assert.NoError(t, err) {
return

View File

@ -13,6 +13,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/process"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -60,7 +61,7 @@ func TestGPGGit(t *testing.T) {
setting.Repository.Signing.SigningKey = rootKeyID
setting.Repository.Signing.SigningName = "gitea"
setting.Repository.Signing.SigningEmail = "gitea@fake.local"
user := models.AssertExistsAndLoadBean(t, &models.User{Name: username}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{Name: username}).(*models.User)
setting.Repository.Signing.InitialCommit = []string{"never"}
setting.Repository.Signing.CRUDActions = []string{"never"}

View File

@ -25,6 +25,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/graceful"
@ -111,7 +112,7 @@ func TestMain(m *testing.M) {
}
}
err := models.InitFixtures(
err := db.InitFixtures(
path.Join(filepath.Dir(setting.AppPath), "models/fixtures/"),
)
if err != nil {
@ -247,7 +248,7 @@ func prepareTestEnv(t testing.TB, skip ...int) func() {
ourSkip += skip[0]
}
deferFn := PrintCurrentTest(t, ourSkip)
assert.NoError(t, models.LoadFixtures())
assert.NoError(t, db.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))
@ -524,7 +525,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, models.LoadFixtures())
assert.NoError(t, db.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))
}

View File

@ -14,6 +14,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/indexer/issues"
"code.gitea.io/gitea/modules/references"
"code.gitea.io/gitea/modules/setting"
@ -35,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 models.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repoID, Index: int64(index)}).(*models.Issue)
return db.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repoID, Index: int64(index)}).(*models.Issue)
}
func assertMatch(t testing.TB, issue *models.Issue, keyword string) {
@ -60,8 +61,8 @@ func TestNoLoginViewIssues(t *testing.T) {
func TestViewIssuesSortByType(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
session := loginUser(t, user.Name)
req := NewRequest(t, "GET", repo.RelLink()+"/issues?type=created_by")
@ -69,10 +70,10 @@ func TestViewIssuesSortByType(t *testing.T) {
htmlDoc := NewHTMLParser(t, resp.Body)
issuesSelection := getIssuesSelection(t, htmlDoc)
expectedNumIssues := models.GetCount(t,
expectedNumIssues := db.GetCount(t,
&models.Issue{RepoID: repo.ID, PosterID: user.ID},
models.Cond("is_closed=?", false),
models.Cond("is_pull=?", false),
db.Cond("is_closed=?", false),
db.Cond("is_pull=?", false),
)
if expectedNumIssues > setting.UI.IssuePagingNum {
expectedNumIssues = setting.UI.IssuePagingNum
@ -88,8 +89,8 @@ func TestViewIssuesSortByType(t *testing.T) {
func TestViewIssuesKeyword(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
issue := models.AssertExistsAndLoadBean(t, &models.Issue{
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
issue := db.AssertExistsAndLoadBean(t, &models.Issue{
RepoID: repo.ID,
Index: 1,
}).(*models.Issue)
@ -235,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")
models.AssertExistsAndLoadBean(t, &models.Comment{
db.AssertExistsAndLoadBean(t, &models.Comment{
IssueID: issueBase.ID,
RefRepoID: 1,
RefIssueID: issueRef.ID,
@ -245,7 +246,7 @@ func TestIssueCrossReference(t *testing.T) {
// Edit title, neuter ref
testIssueChangeInfo(t, "user2", issueRefURL, "title", "Title no ref")
models.AssertExistsAndLoadBean(t, &models.Comment{
db.AssertExistsAndLoadBean(t, &models.Comment{
IssueID: issueBase.ID,
RefRepoID: 1,
RefIssueID: issueRef.ID,
@ -255,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))
models.AssertExistsAndLoadBean(t, &models.Comment{
db.AssertExistsAndLoadBean(t, &models.Comment{
IssueID: issueBase.ID,
RefRepoID: 1,
RefIssueID: issueRef.ID,
@ -265,7 +266,7 @@ func TestIssueCrossReference(t *testing.T) {
// Edit content, neuter ref
testIssueChangeInfo(t, "user2", issueRefURL, "content", "Description no ref")
models.AssertExistsAndLoadBean(t, &models.Comment{
db.AssertExistsAndLoadBean(t, &models.Comment{
IssueID: issueBase.ID,
RefRepoID: 1,
RefIssueID: issueRef.ID,
@ -283,11 +284,11 @@ func TestIssueCrossReference(t *testing.T) {
RefCommentID: commentID,
RefIsPull: false,
RefAction: references.XRefActionNone}
models.AssertExistsAndLoadBean(t, comment)
db.AssertExistsAndLoadBean(t, comment)
// Ref from a different repository
issueRefURL, issueRef = testIssueWithBean(t, "user12", 10, "TitleXRef", fmt.Sprintf("Description ref user2/repo1#%d", issueBase.Index))
models.AssertExistsAndLoadBean(t, &models.Comment{
db.AssertExistsAndLoadBean(t, &models.Comment{
IssueID: issueBase.ID,
RefRepoID: 10,
RefIssueID: issueRef.ID,
@ -303,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)}
models.AssertExistsAndLoadBean(t, issue)
db.AssertExistsAndLoadBean(t, issue)
return issueURL, issue
}

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/migrations"
"code.gitea.io/gitea/modules/setting"
@ -17,9 +18,9 @@ import (
)
func TestMigrateLocalPath(t *testing.T) {
assert.NoError(t, models.PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
adminUser := models.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User)
adminUser := db.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User)
old := setting.ImportLocalPaths
setting.ImportLocalPaths = true

View File

@ -19,7 +19,7 @@ import (
"testing"
"code.gitea.io/gitea/integrations"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/migrations"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/charset"
@ -256,13 +256,13 @@ func doMigrationTest(t *testing.T, version string) {
setting.NewXORMLogService(false)
err := models.NewEngine(context.Background(), wrappedMigrate)
err := db.NewEngine(context.Background(), wrappedMigrate)
assert.NoError(t, err)
currentEngine.Close()
beans, _ := models.NamesToBean()
beans, _ := db.NamesToBean()
err = models.NewEngine(context.Background(), func(x *xorm.Engine) error {
err = db.NewEngine(context.Background(), func(x *xorm.Engine) error {
currentEngine = x
return migrations.RecreateTables(beans...)(x)
})
@ -270,7 +270,7 @@ func doMigrationTest(t *testing.T, version string) {
currentEngine.Close()
// We do this a second time to ensure that there is not a problem with retained indices
err = models.NewEngine(context.Background(), func(x *xorm.Engine) error {
err = db.NewEngine(context.Background(), func(x *xorm.Engine) error {
currentEngine = x
return migrations.RecreateTables(beans...)(x)
})

View File

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/git"
migration "code.gitea.io/gitea/modules/migrations/base"
"code.gitea.io/gitea/modules/repository"
@ -21,8 +22,8 @@ import (
func TestMirrorPull(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repoPath := models.RepoPath(user.Name, repo.Name)
opts := migration.MigrateOptions{

View File

@ -12,6 +12,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/repository"
"code.gitea.io/gitea/modules/setting"
@ -29,8 +30,8 @@ func testMirrorPush(t *testing.T, u *url.URL) {
setting.Migrations.AllowLocalNetworks = true
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
srcRepo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
srcRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
mirrorRepo, err := repository.CreateRepository(user, user, models.CreateRepoOptions{
Name: "test-push-mirror",

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
)
@ -110,7 +111,7 @@ func doCheckOrgCounts(username string, orgCounts map[string]int, strict bool, ca
}
return func(t *testing.T) {
user := models.AssertExistsAndLoadBean(t, &models.User{
user := db.AssertExistsAndLoadBean(t, &models.User{
Name: username,
}).(*models.User)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
api "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
@ -24,8 +25,8 @@ const privateActivityTestOtherUser = "user4"
// activity helpers
func testPrivateActivityDoSomethingForActionEntries(t *testing.T) {
repoBefore := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User)
repoBefore := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repoBefore.OwnerID}).(*models.User)
session := loginUser(t, privateActivityTestUser)
token := getTokenForLoggedInUser(t, session)

View File

@ -17,6 +17,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/git"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
@ -219,15 +220,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 := models.AssertExistsAndLoadBean(t, &models.User{
user1 := db.AssertExistsAndLoadBean(t, &models.User{
Name: "user1",
}).(*models.User)
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{
repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{
OwnerID: user1.ID,
Name: "repo1",
}).(*models.Repository)
pr := models.AssertExistsAndLoadBean(t, &models.PullRequest{
pr := db.AssertExistsAndLoadBean(t, &models.PullRequest{
HeadRepoID: repo1.ID,
BaseRepoID: repo1.ID,
HeadBranch: "conflict",
@ -256,10 +257,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 := models.AssertExistsAndLoadBean(t, &models.User{
user1 := db.AssertExistsAndLoadBean(t, &models.User{
Name: "user1",
}).(*models.User)
repo1 := models.AssertExistsAndLoadBean(t, &models.Repository{
repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{
OwnerID: user1.ID,
Name: "repo1",
}).(*models.Repository)
@ -318,7 +319,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 := models.AssertExistsAndLoadBean(t, &models.PullRequest{
pr := db.AssertExistsAndLoadBean(t, &models.PullRequest{
HeadRepoID: repo1.ID,
BaseRepoID: repo1.ID,
HeadBranch: "unrelated",

View File

@ -11,6 +11,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/repofiles"
repo_module "code.gitea.io/gitea/modules/repository"
pull_service "code.gitea.io/gitea/services/pull"
@ -22,8 +23,8 @@ import (
func TestAPIPullUpdate(t *testing.T) {
onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) {
//Create PR to test
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
org26 := models.AssertExistsAndLoadBean(t, &models.User{ID: 26}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
org26 := db.AssertExistsAndLoadBean(t, &models.User{ID: 26}).(*models.User)
pr := createOutdatedPR(t, user, org26)
//Test GetDiverging
@ -50,8 +51,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 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
org26 := models.AssertExistsAndLoadBean(t, &models.User{ID: 26}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
org26 := db.AssertExistsAndLoadBean(t, &models.User{ID: 26}).(*models.User)
pr := createOutdatedPR(t, user, org26)
//Test GetDiverging
@ -162,7 +163,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 := models.AssertExistsAndLoadBean(t, &models.Issue{Title: "Test Pull -to-update-"}).(*models.Issue)
issue := db.AssertExistsAndLoadBean(t, &models.Issue{Title: "Test Pull -to-update-"}).(*models.Issue)
pr, err := models.GetPullRequestByIssueID(issue.ID)
assert.NoError(t, err)

View File

@ -11,6 +11,7 @@ import (
"time"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
@ -133,7 +134,7 @@ func TestCreateReleasePaging(t *testing.T) {
func TestViewReleaseListNoLogin(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
link := repo.Link() + "/releases"
@ -159,7 +160,7 @@ func TestViewReleaseListNoLogin(t *testing.T) {
func TestViewReleaseListLogin(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
link := repo.Link() + "/releases"
@ -190,7 +191,7 @@ func TestViewReleaseListLogin(t *testing.T) {
func TestViewTagsList(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
link := repo.Link() + "/tags"

View File

@ -11,12 +11,13 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
)
func testRepoFork(t *testing.T, session *TestSession, ownerName, repoName, forkOwnerName, forkRepoName string) *httptest.ResponseRecorder {
forkOwner := models.AssertExistsAndLoadBean(t, &models.User{Name: forkOwnerName}).(*models.User)
forkOwner := db.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)

View File

@ -11,12 +11,13 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
)
func testRepoGenerate(t *testing.T, session *TestSession, templateOwnerName, templateRepoName, generateOwnerName, generateRepoName string) *httptest.ResponseRecorder {
generateOwner := models.AssertExistsAndLoadBean(t, &models.User{Name: generateOwnerName}).(*models.User)
generateOwner := db.AssertExistsAndLoadBean(t, &models.User{Name: generateOwnerName}).(*models.User)
// Step0: check the existence of the generated repo
req := NewRequestf(t, "GET", "/%s/%s", generateOwnerName, generateRepoName)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/services/release"
@ -20,8 +21,8 @@ import (
func TestCreateNewTagProtected(t *testing.T) {
defer prepareTestEnv(t)()
repo := models.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := models.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository)
owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User)
t.Run("API", func(t *testing.T) {
defer PrintCurrentTest(t)()

View File

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
)
@ -17,8 +18,8 @@ func TestRepoWatch(t *testing.T) {
// Test round-trip auto-watch
setting.Service.AutoWatchOnChanges = true
session := loginUser(t, "user2")
models.AssertNotExistsBean(t, &models.Watch{UserID: 2, RepoID: 3})
db.AssertNotExistsBean(t, &models.Watch{UserID: 2, RepoID: 3})
testEditFile(t, session, "user3", "repo3", "master", "README.md", "Hello, World (Edited for watch)\n")
models.AssertExistsAndLoadBean(t, &models.Watch{UserID: 2, RepoID: 3, Mode: models.RepoWatchModeAuto})
db.AssertExistsAndLoadBean(t, &models.Watch{UserID: 2, RepoID: 3, Mode: models.RepoWatchModeAuto})
})
}

View File

@ -9,6 +9,7 @@ import (
"testing"
"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"
@ -66,7 +67,7 @@ func TestDeleteRepoFile(t *testing.T) {
func testDeleteRepoFile(t *testing.T, u *url.URL) {
// setup
models.PrepareTestEnv(t)
db.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1")
ctx.SetParams(":id", "1")
test.LoadRepo(t, ctx, 1)
@ -105,7 +106,7 @@ func TestDeleteRepoFileWithoutBranchNames(t *testing.T) {
func testDeleteRepoFileWithoutBranchNames(t *testing.T, u *url.URL) {
// setup
models.PrepareTestEnv(t)
db.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1")
ctx.SetParams(":id", "1")
test.LoadRepo(t, ctx, 1)
@ -135,7 +136,7 @@ func testDeleteRepoFileWithoutBranchNames(t *testing.T, u *url.URL) {
func TestDeleteRepoFileErrors(t *testing.T) {
// setup
models.PrepareTestEnv(t)
db.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1")
ctx.SetParams(":id", "1")
test.LoadRepo(t, ctx, 1)

View File

@ -10,6 +10,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
"github.com/unknwon/i18n"
@ -33,13 +34,13 @@ func testLoginFailed(t *testing.T, username, password, message string) {
func TestSignin(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.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
models.AssertSuccessfulInsert(t, user)
db.AssertSuccessfulInsert(t, user)
samples := []struct {
username string

View File

@ -11,6 +11,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
"github.com/stretchr/testify/assert"
"github.com/unknwon/i18n"
@ -52,7 +53,7 @@ func TestSignupAsRestricted(t *testing.T) {
req = NewRequest(t, "GET", "/restrictedUser")
MakeRequest(t, req, http.StatusOK)
user2 := models.AssertExistsAndLoadBean(t, &models.User{Name: "restrictedUser"}).(*models.User)
user2 := db.AssertExistsAndLoadBean(t, &models.User{Name: "restrictedUser"}).(*models.User)
assert.True(t, user2.IsRestricted)
}

View File

@ -15,13 +15,14 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"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 := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo3, is an org
user2 := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo3, is an org
seed := user2.Email
if len(seed) == 0 {
@ -71,7 +72,7 @@ func TestUserAvatar(t *testing.T) {
session.MakeRequest(t, req, http.StatusFound)
user2 = models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo3, is an org
user2 = db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // owner of the repo3, is an org
req = NewRequest(t, "GET", user2.AvatarLink())
resp := session.MakeRequest(t, req, http.StatusFound)

View File

@ -9,6 +9,7 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert"
@ -34,8 +35,8 @@ func TestRenameUsername(t *testing.T) {
})
session.MakeRequest(t, req, http.StatusFound)
models.AssertExistsAndLoadBean(t, &models.User{Name: "newUsername"})
models.AssertNotExistsBean(t, &models.User{Name: "user2"})
db.AssertExistsAndLoadBean(t, &models.User{Name: "newUsername"})
db.AssertNotExistsBean(t, &models.User{Name: "user2"})
}
func TestRenameInvalidUsername(t *testing.T) {
@ -66,7 +67,7 @@ func TestRenameInvalidUsername(t *testing.T) {
i18n.Tr("en", "form.alpha_dash_dot_error"),
)
models.AssertNotExistsBean(t, &models.User{Name: invalidUsername})
db.AssertNotExistsBean(t, &models.User{Name: invalidUsername})
}
}
@ -112,7 +113,7 @@ func TestRenameReservedUsername(t *testing.T) {
i18n.Tr("en", "user.form.name_reserved", reservedUsername),
)
models.AssertNotExistsBean(t, &models.User{Name: reservedUsername})
db.AssertNotExistsBean(t, &models.User{Name: reservedUsername})
}
}

View File

@ -9,13 +9,14 @@ import (
"testing"
"code.gitea.io/gitea/models"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
)
func TestXSSUserFullName(t *testing.T) {
defer prepareTestEnv(t)()
user := models.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User)
const fullName = `name & <script class="evil">alert('Oh no!');</script>`
session := loginUser(t, user.Name)

View File

@ -8,6 +8,7 @@ package models
import (
"fmt"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log"
)
@ -71,7 +72,11 @@ type Access struct {
Mode AccessMode
}
func accessLevel(e Engine, user *User, repo *Repository) (AccessMode, error) {
func init() {
db.RegisterModel(new(Access))
}
func accessLevel(e db.Engine, user *User, repo *Repository) (AccessMode, error) {
mode := AccessModeNone
var userID int64
restricted := false
@ -111,7 +116,7 @@ func (repoAccess) TableName() string {
// GetRepositoryAccesses finds all repositories with their access mode where a user has access but does not own.
func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
rows, err := x.
rows, err := db.DefaultContext().Engine().
Join("INNER", "repository", "repository.id = access.repo_id").
Where("access.user_id = ?", user.ID).
And("repository.owner_id <> ?", user.ID).
@ -146,7 +151,7 @@ func (user *User) GetRepositoryAccesses() (map[*Repository]AccessMode, error) {
// GetAccessibleRepositories finds repositories which the user has access but does not own.
// If limit is smaller than 1 means returns all found results.
func (user *User) GetAccessibleRepositories(limit int) (repos []*Repository, _ error) {
sess := x.
sess := db.DefaultContext().Engine().
Where("owner_id !=? ", user.ID).
Desc("updated_unix")
if limit > 0 {
@ -185,7 +190,7 @@ func updateUserAccess(accessMap map[int64]*userAccess, user *User, mode AccessMo
}
// FIXME: do cross-comparison so reduce deletions and additions to the minimum?
func (repo *Repository) refreshAccesses(e Engine, accessMap map[int64]*userAccess) (err error) {
func (repo *Repository) refreshAccesses(e db.Engine, accessMap map[int64]*userAccess) (err error) {
minMode := AccessModeRead
if !repo.IsPrivate {
minMode = AccessModeWrite
@ -219,7 +224,7 @@ func (repo *Repository) refreshAccesses(e Engine, accessMap map[int64]*userAcces
}
// refreshCollaboratorAccesses retrieves repository collaborations with their access modes.
func (repo *Repository) refreshCollaboratorAccesses(e Engine, accessMap map[int64]*userAccess) error {
func (repo *Repository) refreshCollaboratorAccesses(e db.Engine, accessMap map[int64]*userAccess) error {
collaborators, err := repo.getCollaborators(e, ListOptions{})
if err != nil {
return fmt.Errorf("getCollaborations: %v", err)
@ -233,7 +238,7 @@ func (repo *Repository) refreshCollaboratorAccesses(e Engine, accessMap map[int6
// recalculateTeamAccesses recalculates new accesses for teams of an organization
// except the team whose ID is given. It is used to assign a team ID when
// remove repository from that team.
func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err error) {
func (repo *Repository) recalculateTeamAccesses(e db.Engine, ignTeamID int64) (err error) {
accessMap := make(map[int64]*userAccess, 20)
if err = repo.getOwner(e); err != nil {
@ -276,7 +281,7 @@ func (repo *Repository) recalculateTeamAccesses(e Engine, ignTeamID int64) (err
// recalculateUserAccess recalculates new access for a single user
// Usable if we know access only affected one user
func (repo *Repository) recalculateUserAccess(e Engine, uid int64) (err error) {
func (repo *Repository) recalculateUserAccess(e db.Engine, uid int64) (err error) {
minMode := AccessModeRead
if !repo.IsPrivate {
minMode = AccessModeWrite
@ -323,7 +328,7 @@ func (repo *Repository) recalculateUserAccess(e Engine, uid int64) (err error) {
return nil
}
func (repo *Repository) recalculateAccesses(e Engine) error {
func (repo *Repository) recalculateAccesses(e db.Engine) error {
if repo.Owner.IsOrganization() {
return repo.recalculateTeamAccesses(e, 0)
}
@ -337,5 +342,5 @@ func (repo *Repository) recalculateAccesses(e Engine) error {
// RecalculateAccesses recalculates all accesses for repository.
func (repo *Repository) RecalculateAccesses() error {
return repo.recalculateAccesses(x)
return repo.recalculateAccesses(db.DefaultContext().Engine())
}

View File

@ -7,27 +7,28 @@ package models
import (
"testing"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
)
func TestAccessLevel(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
user2 := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
user5 := AssertExistsAndLoadBean(t, &User{ID: 5}).(*User)
user29 := AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
user5 := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User)
user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
// A public repository owned by User 2
repo1 := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
assert.False(t, repo1.IsPrivate)
// A private repository owned by Org 3
repo3 := AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
repo3 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
assert.True(t, repo3.IsPrivate)
// Another public repository
repo4 := AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository)
repo4 := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository)
assert.False(t, repo4.IsPrivate)
// org. owned private repo
repo24 := AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository)
repo24 := db.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository)
level, err := AccessLevel(user2, repo1)
assert.NoError(t, err)
@ -62,15 +63,15 @@ func TestAccessLevel(t *testing.T) {
}
func TestHasAccess(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
user1 := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
user2 := AssertExistsAndLoadBean(t, &User{ID: 5}).(*User)
user1 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
user2 := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User)
// A public repository owned by User 2
repo1 := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
assert.False(t, repo1.IsPrivate)
// A private repository owned by Org 3
repo2 := AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
assert.True(t, repo2.IsPrivate)
has, err := HasAccess(user1.ID, repo1)
@ -88,33 +89,33 @@ func TestHasAccess(t *testing.T) {
}
func TestUser_GetRepositoryAccesses(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
user1 := AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
accesses, err := user1.GetRepositoryAccesses()
assert.NoError(t, err)
assert.Len(t, accesses, 0)
user29 := AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
user29 := db.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, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
user1 := AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
repos, err := user1.GetAccessibleRepositories(0)
assert.NoError(t, err)
assert.Len(t, repos, 0)
user2 := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
repos, err = user2.GetAccessibleRepositories(0)
assert.NoError(t, err)
assert.Len(t, repos, 4)
user29 := AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
repos, err = user29.GetAccessibleRepositories(0)
assert.NoError(t, err)
assert.Len(t, repos, 2)
@ -122,16 +123,16 @@ func TestUser_GetAccessibleRepositories(t *testing.T) {
func TestRepository_RecalculateAccesses(t *testing.T) {
// test with organization repo
assert.NoError(t, PrepareTestDatabase())
repo1 := AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
assert.NoError(t, db.PrepareTestDatabase())
repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository)
assert.NoError(t, repo1.GetOwner())
_, err := x.Delete(&Collaboration{UserID: 2, RepoID: 3})
_, err := db.DefaultContext().Engine().Delete(&Collaboration{UserID: 2, RepoID: 3})
assert.NoError(t, err)
assert.NoError(t, repo1.RecalculateAccesses())
access := &Access{UserID: 2, RepoID: 3}
has, err := x.Get(access)
has, err := db.DefaultContext().Engine().Get(access)
assert.NoError(t, err)
assert.True(t, has)
assert.Equal(t, AccessModeOwner, access.Mode)
@ -139,25 +140,25 @@ func TestRepository_RecalculateAccesses(t *testing.T) {
func TestRepository_RecalculateAccesses2(t *testing.T) {
// test with non-organization repo
assert.NoError(t, PrepareTestDatabase())
repo1 := AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository)
assert.NoError(t, db.PrepareTestDatabase())
repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository)
assert.NoError(t, repo1.GetOwner())
_, err := x.Delete(&Collaboration{UserID: 4, RepoID: 4})
_, err := db.DefaultContext().Engine().Delete(&Collaboration{UserID: 4, RepoID: 4})
assert.NoError(t, err)
assert.NoError(t, repo1.RecalculateAccesses())
has, err := x.Get(&Access{UserID: 4, RepoID: 4})
has, err := db.DefaultContext().Engine().Get(&Access{UserID: 4, RepoID: 4})
assert.NoError(t, err)
assert.False(t, has)
}
func TestRepository_RecalculateAccesses3(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
team5 := AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team)
user29 := AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
assert.NoError(t, db.PrepareTestDatabase())
team5 := db.AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team)
user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User)
has, err := x.Get(&Access{UserID: 29, RepoID: 23})
has, err := db.DefaultContext().Engine().Get(&Access{UserID: 29, RepoID: 23})
assert.NoError(t, err)
assert.False(t, has)
@ -165,7 +166,7 @@ func TestRepository_RecalculateAccesses3(t *testing.T) {
// even though repo 23 is public
assert.NoError(t, AddTeamMember(team5, user29.ID))
has, err = x.Get(&Access{UserID: 29, RepoID: 23})
has, err = db.DefaultContext().Engine().Get(&Access{UserID: 29, RepoID: 23})
assert.NoError(t, err)
assert.True(t, has)
}

View File

@ -12,6 +12,7 @@ import (
"strings"
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/git"
"code.gitea.io/gitea/modules/log"
@ -74,6 +75,10 @@ type Action struct {
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
}
func init() {
db.RegisterModel(new(Action))
}
// GetOpType gets the ActionType of this action.
func (a *Action) GetOpType() ActionType {
return a.OpType
@ -203,10 +208,10 @@ func GetRepositoryFromMatch(ownerName, repoName string) (*Repository, error) {
// GetCommentLink returns link to action comment.
func (a *Action) GetCommentLink() string {
return a.getCommentLink(x)
return a.getCommentLink(db.DefaultContext().Engine())
}
func (a *Action) getCommentLink(e Engine) string {
func (a *Action) getCommentLink(e db.Engine) string {
if a == nil {
return "#"
}
@ -312,7 +317,7 @@ func GetFeeds(opts GetFeedsOptions) ([]*Action, error) {
actions := make([]*Action, 0, setting.UI.FeedPagingNum)
if err := x.Limit(setting.UI.FeedPagingNum).Desc("id").Where(cond).Find(&actions); err != nil {
if err := db.DefaultContext().Engine().Limit(setting.UI.FeedPagingNum).Desc("id").Where(cond).Find(&actions); err != nil {
return nil, fmt.Errorf("Find: %v", err)
}
@ -403,6 +408,6 @@ func DeleteOldActions(olderThan time.Duration) (err error) {
return nil
}
_, err = x.Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{})
_, err = db.DefaultContext().Engine().Where("created_unix < ?", time.Now().Add(-olderThan).Unix()).Delete(&Action{})
return
}

View File

@ -4,7 +4,11 @@
package models
import "fmt"
import (
"fmt"
"code.gitea.io/gitea/models/db"
)
// ActionList defines a list of actions
type ActionList []*Action
@ -19,7 +23,7 @@ func (actions ActionList) getUserIDs() []int64 {
return keysInt64(userIDs)
}
func (actions ActionList) loadUsers(e Engine) ([]*User, error) {
func (actions ActionList) loadUsers(e db.Engine) ([]*User, error) {
if len(actions) == 0 {
return nil, nil
}
@ -41,7 +45,7 @@ func (actions ActionList) loadUsers(e Engine) ([]*User, error) {
// LoadUsers loads actions' all users
func (actions ActionList) LoadUsers() ([]*User, error) {
return actions.loadUsers(x)
return actions.loadUsers(db.DefaultContext().Engine())
}
func (actions ActionList) getRepoIDs() []int64 {
@ -54,7 +58,7 @@ func (actions ActionList) getRepoIDs() []int64 {
return keysInt64(repoIDs)
}
func (actions ActionList) loadRepositories(e Engine) ([]*Repository, error) {
func (actions ActionList) loadRepositories(e db.Engine) ([]*Repository, error) {
if len(actions) == 0 {
return nil, nil
}
@ -76,11 +80,11 @@ func (actions ActionList) loadRepositories(e Engine) ([]*Repository, error) {
// LoadRepositories loads actions' all repositories
func (actions ActionList) LoadRepositories() ([]*Repository, error) {
return actions.loadRepositories(x)
return actions.loadRepositories(db.DefaultContext().Engine())
}
// loadAttributes loads all attributes
func (actions ActionList) loadAttributes(e Engine) (err error) {
func (actions ActionList) loadAttributes(e db.Engine) (err error) {
if _, err = actions.loadUsers(e); err != nil {
return
}
@ -94,5 +98,5 @@ func (actions ActionList) loadAttributes(e Engine) (err error) {
// LoadAttributes loads attributes of the actions
func (actions ActionList) LoadAttributes() error {
return actions.loadAttributes(x)
return actions.loadAttributes(db.DefaultContext().Engine())
}

View File

@ -8,23 +8,24 @@ import (
"path"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
"github.com/stretchr/testify/assert"
)
func TestAction_GetRepoPath(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
repo := AssertExistsAndLoadBean(t, &Repository{}).(*Repository)
owner := AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User)
assert.NoError(t, db.PrepareTestDatabase())
repo := db.AssertExistsAndLoadBean(t, &Repository{}).(*Repository)
owner := db.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, PrepareTestDatabase())
repo := AssertExistsAndLoadBean(t, &Repository{}).(*Repository)
owner := AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User)
assert.NoError(t, db.PrepareTestDatabase())
repo := db.AssertExistsAndLoadBean(t, &Repository{}).(*Repository)
owner := db.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User)
action := &Action{RepoID: repo.ID}
setting.AppSubURL = "/suburl"
expected := path.Join(setting.AppSubURL, owner.Name, repo.Name)
@ -33,8 +34,8 @@ func TestAction_GetRepoLink(t *testing.T) {
func TestGetFeeds(t *testing.T) {
// test with an individual user
assert.NoError(t, PrepareTestDatabase())
user := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
assert.NoError(t, db.PrepareTestDatabase())
user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
actions, err := GetFeeds(GetFeedsOptions{
RequestedUser: user,
@ -61,9 +62,9 @@ func TestGetFeeds(t *testing.T) {
func TestGetFeeds2(t *testing.T) {
// test with an organization user
assert.NoError(t, PrepareTestDatabase())
org := AssertExistsAndLoadBean(t, &User{ID: 3}).(*User)
user := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
assert.NoError(t, db.PrepareTestDatabase())
org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User)
user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
actions, err := GetFeeds(GetFeedsOptions{
RequestedUser: org,

View File

@ -8,6 +8,7 @@ package models
import (
"fmt"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/modules/timeutil"
@ -32,6 +33,10 @@ type Notice struct {
CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
}
func init() {
db.RegisterModel(new(Notice))
}
// TrStr returns a translation format string.
func (n *Notice) TrStr() string {
return fmt.Sprintf("admin.notices.type_%d", n.Type)
@ -39,10 +44,10 @@ func (n *Notice) TrStr() string {
// CreateNotice creates new system notice.
func CreateNotice(tp NoticeType, desc string, args ...interface{}) error {
return createNotice(x, tp, desc, args...)
return createNotice(db.DefaultContext().Engine(), tp, desc, args...)
}
func createNotice(e Engine, tp NoticeType, desc string, args ...interface{}) error {
func createNotice(e db.Engine, tp NoticeType, desc string, args ...interface{}) error {
if len(args) > 0 {
desc = fmt.Sprintf(desc, args...)
}
@ -56,22 +61,22 @@ func createNotice(e Engine, tp NoticeType, desc string, args ...interface{}) err
// CreateRepositoryNotice creates new system notice with type NoticeRepository.
func CreateRepositoryNotice(desc string, args ...interface{}) error {
return createNotice(x, NoticeRepository, desc, args...)
return createNotice(db.DefaultContext().Engine(), NoticeRepository, desc, args...)
}
// RemoveAllWithNotice removes all directories in given path and
// creates a system notice when error occurs.
func RemoveAllWithNotice(title, path string) {
removeAllWithNotice(x, title, path)
removeAllWithNotice(db.DefaultContext().Engine(), title, path)
}
// RemoveStorageWithNotice removes a file from the storage and
// creates a system notice when error occurs.
func RemoveStorageWithNotice(bucket storage.ObjectStorage, title, path string) {
removeStorageWithNotice(x, bucket, title, path)
removeStorageWithNotice(db.DefaultContext().Engine(), bucket, title, path)
}
func removeStorageWithNotice(e Engine, bucket storage.ObjectStorage, title, path string) {
func removeStorageWithNotice(e db.Engine, bucket storage.ObjectStorage, title, path string) {
if err := bucket.Delete(path); err != nil {
desc := fmt.Sprintf("%s [%s]: %v", title, path, err)
log.Warn(title+" [%s]: %v", path, err)
@ -81,7 +86,7 @@ func removeStorageWithNotice(e Engine, bucket storage.ObjectStorage, title, path
}
}
func removeAllWithNotice(e Engine, title, path string) {
func removeAllWithNotice(e db.Engine, title, path string) {
if err := util.RemoveAll(path); err != nil {
desc := fmt.Sprintf("%s [%s]: %v", title, path, err)
log.Warn(title+" [%s]: %v", path, err)
@ -93,14 +98,14 @@ func removeAllWithNotice(e Engine, title, path string) {
// CountNotices returns number of notices.
func CountNotices() int64 {
count, _ := x.Count(new(Notice))
count, _ := db.DefaultContext().Engine().Count(new(Notice))
return count
}
// Notices returns notices in given page.
func Notices(page, pageSize int) ([]*Notice, error) {
notices := make([]*Notice, 0, pageSize)
return notices, x.
return notices, db.DefaultContext().Engine().
Limit(pageSize, (page-1)*pageSize).
Desc("id").
Find(&notices)
@ -108,18 +113,18 @@ func Notices(page, pageSize int) ([]*Notice, error) {
// DeleteNotice deletes a system notice by given ID.
func DeleteNotice(id int64) error {
_, err := x.ID(id).Delete(new(Notice))
_, err := db.DefaultContext().Engine().ID(id).Delete(new(Notice))
return err
}
// DeleteNotices deletes all notices with ID from start to end (inclusive).
func DeleteNotices(start, end int64) error {
if start == 0 && end == 0 {
_, err := x.Exec("DELETE FROM notice")
_, err := db.DefaultContext().Engine().Exec("DELETE FROM notice")
return err
}
sess := x.Where("id >= ?", start)
sess := db.DefaultContext().Engine().Where("id >= ?", start)
if end > 0 {
sess.And("id <= ?", end)
}
@ -132,7 +137,7 @@ func DeleteNoticesByIDs(ids []int64) error {
if len(ids) == 0 {
return nil
}
_, err := x.
_, err := db.DefaultContext().Engine().
In("id", ids).
Delete(new(Notice))
return err
@ -141,7 +146,7 @@ func DeleteNoticesByIDs(ids []int64) error {
// GetAdminUser returns the first administrator
func GetAdminUser() (*User, error) {
var admin User
has, err := x.Where("is_admin=?", true).Get(&admin)
has, err := db.DefaultContext().Engine().Where("is_admin=?", true).Get(&admin)
if err != nil {
return nil, err
} else if !has {

View File

@ -7,6 +7,7 @@ package models
import (
"testing"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
)
@ -19,38 +20,38 @@ func TestNotice_TrStr(t *testing.T) {
}
func TestCreateNotice(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
noticeBean := &Notice{
Type: NoticeRepository,
Description: "test description",
}
AssertNotExistsBean(t, noticeBean)
db.AssertNotExistsBean(t, noticeBean)
assert.NoError(t, CreateNotice(noticeBean.Type, noticeBean.Description))
AssertExistsAndLoadBean(t, noticeBean)
db.AssertExistsAndLoadBean(t, noticeBean)
}
func TestCreateRepositoryNotice(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
noticeBean := &Notice{
Type: NoticeRepository,
Description: "test description",
}
AssertNotExistsBean(t, noticeBean)
db.AssertNotExistsBean(t, noticeBean)
assert.NoError(t, CreateRepositoryNotice(noticeBean.Description))
AssertExistsAndLoadBean(t, noticeBean)
db.AssertExistsAndLoadBean(t, noticeBean)
}
// TODO TestRemoveAllWithNotice
func TestCountNotices(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
assert.Equal(t, int64(3), CountNotices())
}
func TestNotices(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
notices, err := Notices(1, 2)
assert.NoError(t, err)
@ -67,47 +68,47 @@ func TestNotices(t *testing.T) {
}
func TestDeleteNotice(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
AssertExistsAndLoadBean(t, &Notice{ID: 3})
db.AssertExistsAndLoadBean(t, &Notice{ID: 3})
assert.NoError(t, DeleteNotice(3))
AssertNotExistsBean(t, &Notice{ID: 3})
db.AssertNotExistsBean(t, &Notice{ID: 3})
}
func TestDeleteNotices(t *testing.T) {
// delete a non-empty range
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
AssertExistsAndLoadBean(t, &Notice{ID: 1})
AssertExistsAndLoadBean(t, &Notice{ID: 2})
AssertExistsAndLoadBean(t, &Notice{ID: 3})
db.AssertExistsAndLoadBean(t, &Notice{ID: 1})
db.AssertExistsAndLoadBean(t, &Notice{ID: 2})
db.AssertExistsAndLoadBean(t, &Notice{ID: 3})
assert.NoError(t, DeleteNotices(1, 2))
AssertNotExistsBean(t, &Notice{ID: 1})
AssertNotExistsBean(t, &Notice{ID: 2})
AssertExistsAndLoadBean(t, &Notice{ID: 3})
db.AssertNotExistsBean(t, &Notice{ID: 1})
db.AssertNotExistsBean(t, &Notice{ID: 2})
db.AssertExistsAndLoadBean(t, &Notice{ID: 3})
}
func TestDeleteNotices2(t *testing.T) {
// delete an empty range
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
AssertExistsAndLoadBean(t, &Notice{ID: 1})
AssertExistsAndLoadBean(t, &Notice{ID: 2})
AssertExistsAndLoadBean(t, &Notice{ID: 3})
db.AssertExistsAndLoadBean(t, &Notice{ID: 1})
db.AssertExistsAndLoadBean(t, &Notice{ID: 2})
db.AssertExistsAndLoadBean(t, &Notice{ID: 3})
assert.NoError(t, DeleteNotices(3, 2))
AssertExistsAndLoadBean(t, &Notice{ID: 1})
AssertExistsAndLoadBean(t, &Notice{ID: 2})
AssertExistsAndLoadBean(t, &Notice{ID: 3})
db.AssertExistsAndLoadBean(t, &Notice{ID: 1})
db.AssertExistsAndLoadBean(t, &Notice{ID: 2})
db.AssertExistsAndLoadBean(t, &Notice{ID: 3})
}
func TestDeleteNoticesByIDs(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
AssertExistsAndLoadBean(t, &Notice{ID: 1})
AssertExistsAndLoadBean(t, &Notice{ID: 2})
AssertExistsAndLoadBean(t, &Notice{ID: 3})
db.AssertExistsAndLoadBean(t, &Notice{ID: 1})
db.AssertExistsAndLoadBean(t, &Notice{ID: 2})
db.AssertExistsAndLoadBean(t, &Notice{ID: 3})
assert.NoError(t, DeleteNoticesByIDs([]int64{1, 3}))
AssertNotExistsBean(t, &Notice{ID: 1})
AssertExistsAndLoadBean(t, &Notice{ID: 2})
AssertNotExistsBean(t, &Notice{ID: 3})
db.AssertNotExistsBean(t, &Notice{ID: 1})
db.AssertExistsAndLoadBean(t, &Notice{ID: 2})
db.AssertNotExistsBean(t, &Notice{ID: 3})
}

View File

@ -8,6 +8,7 @@ import (
"fmt"
"path"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/modules/timeutil"
@ -30,10 +31,14 @@ type Attachment struct {
CreatedUnix timeutil.TimeStamp `xorm:"created"`
}
func init() {
db.RegisterModel(new(Attachment))
}
// IncreaseDownloadCount is update download count + 1
func (a *Attachment) IncreaseDownloadCount() error {
// Update download count.
if _, err := x.Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil {
if _, err := db.DefaultContext().Engine().Exec("UPDATE `attachment` SET download_count=download_count+1 WHERE id=?", a.ID); err != nil {
return fmt.Errorf("increase attachment count: %v", err)
}
@ -81,10 +86,10 @@ func (a *Attachment) LinkedRepository() (*Repository, UnitType, error) {
// GetAttachmentByID returns attachment by given id
func GetAttachmentByID(id int64) (*Attachment, error) {
return getAttachmentByID(x, id)
return getAttachmentByID(db.DefaultContext().Engine(), id)
}
func getAttachmentByID(e Engine, id int64) (*Attachment, error) {
func getAttachmentByID(e db.Engine, id int64) (*Attachment, error) {
attach := &Attachment{}
if has, err := e.ID(id).Get(attach); err != nil {
return nil, err
@ -94,7 +99,7 @@ func getAttachmentByID(e Engine, id int64) (*Attachment, error) {
return attach, nil
}
func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
func getAttachmentByUUID(e db.Engine, uuid string) (*Attachment, error) {
attach := &Attachment{}
has, err := e.Where("uuid=?", uuid).Get(attach)
if err != nil {
@ -106,11 +111,11 @@ func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
}
// GetAttachmentsByUUIDs returns attachment by given UUID list.
func GetAttachmentsByUUIDs(ctx DBContext, uuids []string) ([]*Attachment, error) {
return getAttachmentsByUUIDs(ctx.e, uuids)
func GetAttachmentsByUUIDs(ctx *db.Context, uuids []string) ([]*Attachment, error) {
return getAttachmentsByUUIDs(ctx.Engine(), uuids)
}
func getAttachmentsByUUIDs(e Engine, uuids []string) ([]*Attachment, error) {
func getAttachmentsByUUIDs(e db.Engine, uuids []string) ([]*Attachment, error) {
if len(uuids) == 0 {
return []*Attachment{}, nil
}
@ -122,41 +127,41 @@ func getAttachmentsByUUIDs(e Engine, uuids []string) ([]*Attachment, error) {
// GetAttachmentByUUID returns attachment by given UUID.
func GetAttachmentByUUID(uuid string) (*Attachment, error) {
return getAttachmentByUUID(x, uuid)
return getAttachmentByUUID(db.DefaultContext().Engine(), uuid)
}
// ExistAttachmentsByUUID returns true if attachment is exist by given UUID
func ExistAttachmentsByUUID(uuid string) (bool, error) {
return x.Where("`uuid`=?", uuid).Exist(new(Attachment))
return db.DefaultContext().Engine().Where("`uuid`=?", uuid).Exist(new(Attachment))
}
// GetAttachmentByReleaseIDFileName returns attachment by given releaseId and fileName.
func GetAttachmentByReleaseIDFileName(releaseID int64, fileName string) (*Attachment, error) {
return getAttachmentByReleaseIDFileName(x, releaseID, fileName)
return getAttachmentByReleaseIDFileName(db.DefaultContext().Engine(), releaseID, fileName)
}
func getAttachmentsByIssueID(e Engine, issueID int64) ([]*Attachment, error) {
func getAttachmentsByIssueID(e db.Engine, issueID int64) ([]*Attachment, error) {
attachments := make([]*Attachment, 0, 10)
return attachments, e.Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
}
// GetAttachmentsByIssueID returns all attachments of an issue.
func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
return getAttachmentsByIssueID(x, issueID)
return getAttachmentsByIssueID(db.DefaultContext().Engine(), issueID)
}
// GetAttachmentsByCommentID returns all attachments if comment by given ID.
func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
return getAttachmentsByCommentID(x, commentID)
return getAttachmentsByCommentID(db.DefaultContext().Engine(), commentID)
}
func getAttachmentsByCommentID(e Engine, commentID int64) ([]*Attachment, error) {
func getAttachmentsByCommentID(e db.Engine, commentID int64) ([]*Attachment, error) {
attachments := make([]*Attachment, 0, 10)
return attachments, e.Where("comment_id=?", commentID).Find(&attachments)
}
// getAttachmentByReleaseIDFileName return a file based on the the following infos:
func getAttachmentByReleaseIDFileName(e Engine, releaseID int64, fileName string) (*Attachment, error) {
func getAttachmentByReleaseIDFileName(e db.Engine, releaseID int64, fileName string) (*Attachment, error) {
attach := &Attachment{ReleaseID: releaseID, Name: fileName}
has, err := e.Get(attach)
if err != nil {
@ -169,12 +174,12 @@ func getAttachmentByReleaseIDFileName(e Engine, releaseID int64, fileName string
// DeleteAttachment deletes the given attachment and optionally the associated file.
func DeleteAttachment(a *Attachment, remove bool) error {
_, err := DeleteAttachments(DefaultDBContext(), []*Attachment{a}, remove)
_, err := DeleteAttachments(db.DefaultContext(), []*Attachment{a}, remove)
return err
}
// DeleteAttachments deletes the given attachments and optionally the associated files.
func DeleteAttachments(ctx DBContext, attachments []*Attachment, remove bool) (int, error) {
func DeleteAttachments(ctx *db.Context, attachments []*Attachment, remove bool) (int, error) {
if len(attachments) == 0 {
return 0, nil
}
@ -184,7 +189,7 @@ func DeleteAttachments(ctx DBContext, attachments []*Attachment, remove bool) (i
ids = append(ids, a.ID)
}
cnt, err := ctx.e.In("id", ids).NoAutoCondition().Delete(attachments[0])
cnt, err := ctx.Engine().In("id", ids).NoAutoCondition().Delete(attachments[0])
if err != nil {
return 0, err
}
@ -206,7 +211,7 @@ func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
return 0, err
}
return DeleteAttachments(DefaultDBContext(), attachments, remove)
return DeleteAttachments(db.DefaultContext(), attachments, remove)
}
// DeleteAttachmentsByComment deletes all attachments associated with the given comment.
@ -216,24 +221,24 @@ func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
return 0, err
}
return DeleteAttachments(DefaultDBContext(), attachments, remove)
return DeleteAttachments(db.DefaultContext(), attachments, remove)
}
// UpdateAttachment updates the given attachment in database
func UpdateAttachment(atta *Attachment) error {
return updateAttachment(x, atta)
return updateAttachment(db.DefaultContext().Engine(), atta)
}
// UpdateAttachmentByUUID Updates attachment via uuid
func UpdateAttachmentByUUID(ctx DBContext, attach *Attachment, cols ...string) error {
func UpdateAttachmentByUUID(ctx *db.Context, attach *Attachment, cols ...string) error {
if attach.UUID == "" {
return fmt.Errorf("Attachement uuid should not blank")
}
_, err := ctx.e.Where("uuid=?", attach.UUID).Cols(cols...).Update(attach)
_, err := ctx.Engine().Where("uuid=?", attach.UUID).Cols(cols...).Update(attach)
return err
}
func updateAttachment(e Engine, atta *Attachment) error {
func updateAttachment(e db.Engine, atta *Attachment) error {
var sess *xorm.Session
if atta.ID != 0 && atta.UUID == "" {
sess = e.ID(atta.ID)
@ -247,7 +252,7 @@ func updateAttachment(e Engine, atta *Attachment) error {
// DeleteAttachmentsByRelease deletes all attachments associated with the given release.
func DeleteAttachmentsByRelease(releaseID int64) error {
_, err := x.Where("release_id = ?", releaseID).Delete(&Attachment{})
_, err := db.DefaultContext().Engine().Where("release_id = ?", releaseID).Delete(&Attachment{})
return err
}
@ -257,7 +262,7 @@ func IterateAttachment(f func(attach *Attachment) error) error {
const batchSize = 100
for {
attachments := make([]*Attachment, 0, batchSize)
if err := x.Limit(batchSize, start).Find(&attachments); err != nil {
if err := db.DefaultContext().Engine().Limit(batchSize, start).Find(&attachments); err != nil {
return err
}
if len(attachments) == 0 {
@ -275,13 +280,13 @@ func IterateAttachment(f func(attach *Attachment) error) error {
// CountOrphanedAttachments returns the number of bad attachments
func CountOrphanedAttachments() (int64, error) {
return x.Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
return db.DefaultContext().Engine().Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
Count(new(Attachment))
}
// DeleteOrphanedAttachments delete all bad attachments
func DeleteOrphanedAttachments() error {
_, err := x.Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
_, err := db.DefaultContext().Engine().Where("(issue_id > 0 and issue_id not in (select id from issue)) or (release_id > 0 and release_id not in (select id from `release`))").
Delete(new(Attachment))
return err
}

View File

@ -7,11 +7,12 @@ package models
import (
"testing"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
)
func TestIncreaseDownloadCount(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
attachment, err := GetAttachmentByUUID("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11")
assert.NoError(t, err)
@ -27,7 +28,7 @@ func TestIncreaseDownloadCount(t *testing.T) {
}
func TestGetByCommentOrIssueID(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
// count of attachments from issue ID
attachments, err := GetAttachmentsByIssueID(1)
@ -40,7 +41,7 @@ func TestGetByCommentOrIssueID(t *testing.T) {
}
func TestDeleteAttachments(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
count, err := DeleteAttachmentsByIssue(4, false)
assert.NoError(t, err)
@ -60,7 +61,7 @@ func TestDeleteAttachments(t *testing.T) {
}
func TestGetAttachmentByID(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
attach, err := GetAttachmentByID(1)
assert.NoError(t, err)
@ -76,7 +77,7 @@ func TestAttachment_DownloadURL(t *testing.T) {
}
func TestUpdateAttachment(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
attach, err := GetAttachmentByID(1)
assert.NoError(t, err)
@ -85,13 +86,13 @@ func TestUpdateAttachment(t *testing.T) {
attach.Name = "new_name"
assert.NoError(t, UpdateAttachment(attach))
AssertExistsAndLoadBean(t, &Attachment{Name: "new_name"})
db.AssertExistsAndLoadBean(t, &Attachment{Name: "new_name"})
}
func TestGetAttachmentsByUUIDs(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
attachList, err := GetAttachmentsByUUIDs(DefaultDBContext(), []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"})
attachList, err := GetAttachmentsByUUIDs(db.DefaultContext(), []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"})
assert.NoError(t, err)
assert.Len(t, attachList, 2)
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attachList[0].UUID)
@ -101,7 +102,7 @@ func TestGetAttachmentsByUUIDs(t *testing.T) {
}
func TestLinkedRepository(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
testCases := []struct {
name string
attachID int64

View File

@ -12,6 +12,7 @@ import (
"strconv"
"strings"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/cache"
"code.gitea.io/gitea/modules/log"
@ -24,6 +25,10 @@ type EmailHash struct {
Email string `xorm:"UNIQUE NOT NULL"`
}
func init() {
db.RegisterModel(new(EmailHash))
}
// DefaultAvatarLink the default avatar link
func DefaultAvatarLink() string {
u, err := url.Parse(setting.AppSubURL)
@ -59,7 +64,7 @@ func GetEmailForHash(md5Sum string) (string, error) {
Hash: strings.ToLower(strings.TrimSpace(md5Sum)),
}
_, err := x.Get(&emailHash)
_, err := db.DefaultContext().Engine().Get(&emailHash)
return emailHash.Email, err
})
}
@ -90,19 +95,15 @@ func HashedAvatarLink(email string, size int) string {
Hash: sum,
}
// OK we're going to open a session just because I think that that might hide away any problems with postgres reporting errors
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
// we don't care about any DB problem just return the lowerEmail
return lowerEmail, nil
}
has, err := sess.Where("email = ? AND hash = ?", emailHash.Email, emailHash.Hash).Get(new(EmailHash))
if has || err != nil {
// Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time
return lowerEmail, nil
}
_, _ = sess.Insert(emailHash)
if err := sess.Commit(); err != nil {
if err := db.WithTx(func(ctx *db.Context) error {
has, err := ctx.Engine().Where("email = ? AND hash = ?", emailHash.Email, emailHash.Hash).Get(new(EmailHash))
if has || err != nil {
// Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time
return nil
}
_, _ = ctx.Engine().Insert(emailHash)
return nil
}); err != nil {
// Seriously we don't care about any DB problems just return the lowerEmail - we expect the transaction to fail most of the time
return lowerEmail, nil
}

View File

@ -10,6 +10,7 @@ import (
"strings"
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/base"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/timeutil"
@ -49,6 +50,11 @@ type ProtectedBranch struct {
UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
}
func init() {
db.RegisterModel(new(ProtectedBranch))
db.RegisterModel(new(DeletedBranch))
}
// IsProtected returns if the branch is protected
func (protectBranch *ProtectedBranch) IsProtected() bool {
return protectBranch.ID > 0
@ -116,10 +122,10 @@ func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64, permi
// IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
func (protectBranch *ProtectedBranch) IsUserOfficialReviewer(user *User) (bool, error) {
return protectBranch.isUserOfficialReviewer(x, user)
return protectBranch.isUserOfficialReviewer(db.DefaultContext().Engine(), user)
}
func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e Engine, user *User) (bool, error) {
func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e db.Engine, user *User) (bool, error) {
repo, err := getRepositoryByID(e, protectBranch.RepoID)
if err != nil {
return false, err
@ -156,7 +162,7 @@ func (protectBranch *ProtectedBranch) HasEnoughApprovals(pr *PullRequest) bool {
// GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist.
func (protectBranch *ProtectedBranch) GetGrantedApprovalsCount(pr *PullRequest) int64 {
sess := x.Where("issue_id = ?", pr.IssueID).
sess := db.DefaultContext().Engine().Where("issue_id = ?", pr.IssueID).
And("type = ?", ReviewTypeApprove).
And("official = ?", true).
And("dismissed = ?", false)
@ -177,7 +183,7 @@ func (protectBranch *ProtectedBranch) MergeBlockedByRejectedReview(pr *PullReque
if !protectBranch.BlockOnRejectedReviews {
return false
}
rejectExist, err := x.Where("issue_id = ?", pr.IssueID).
rejectExist, err := db.DefaultContext().Engine().Where("issue_id = ?", pr.IssueID).
And("type = ?", ReviewTypeReject).
And("official = ?", true).
And("dismissed = ?", false).
@ -196,7 +202,7 @@ func (protectBranch *ProtectedBranch) MergeBlockedByOfficialReviewRequests(pr *P
if !protectBranch.BlockOnOfficialReviewRequests {
return false
}
has, err := x.Where("issue_id = ?", pr.IssueID).
has, err := db.DefaultContext().Engine().Where("issue_id = ?", pr.IssueID).
And("type = ?", ReviewTypeRequest).
And("official = ?", true).
Exist(new(Review))
@ -294,10 +300,10 @@ func (protectBranch *ProtectedBranch) IsUnprotectedFile(patterns []glob.Glob, pa
// GetProtectedBranchBy getting protected branch by ID/Name
func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) {
return getProtectedBranchBy(x, repoID, branchName)
return getProtectedBranchBy(db.DefaultContext().Engine(), repoID, branchName)
}
func getProtectedBranchBy(e Engine, repoID int64, branchName string) (*ProtectedBranch, error) {
func getProtectedBranchBy(e db.Engine, repoID int64, branchName string) (*ProtectedBranch, error) {
rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName}
has, err := e.Get(rel)
if err != nil {
@ -369,13 +375,13 @@ func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts
// Make sure protectBranch.ID is not 0 for whitelists
if protectBranch.ID == 0 {
if _, err = x.Insert(protectBranch); err != nil {
if _, err = db.DefaultContext().Engine().Insert(protectBranch); err != nil {
return fmt.Errorf("Insert: %v", err)
}
return nil
}
if _, err = x.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
if _, err = db.DefaultContext().Engine().ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
return fmt.Errorf("Update: %v", err)
}
@ -385,7 +391,7 @@ func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts
// GetProtectedBranches get all protected branches
func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
protectedBranches := make([]*ProtectedBranch, 0)
return protectedBranches, x.Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
return protectedBranches, db.DefaultContext().Engine().Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
}
// GetBranchProtection get the branch protection of a branch
@ -400,7 +406,7 @@ func (repo *Repository) IsProtectedBranch(branchName string) (bool, error) {
BranchName: branchName,
}
has, err := x.Exist(protectedBranch)
has, err := db.DefaultContext().Engine().Exist(protectedBranch)
if err != nil {
return true, err
}
@ -487,19 +493,13 @@ func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
ID: id,
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if affected, err := sess.Delete(protectedBranch); err != nil {
if affected, err := db.DefaultContext().Engine().Delete(protectedBranch); err != nil {
return err
} else if affected != 1 {
return fmt.Errorf("delete protected branch ID(%v) failed", id)
}
return sess.Commit()
return nil
}
// DeletedBranch struct
@ -522,29 +522,20 @@ func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID
DeletedByID: deletedByID,
}
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
if _, err := sess.InsertOne(deletedBranch); err != nil {
return err
}
return sess.Commit()
_, err := db.DefaultContext().Engine().InsertOne(deletedBranch)
return err
}
// GetDeletedBranches returns all the deleted branches
func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
deletedBranches := make([]*DeletedBranch, 0)
return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
return deletedBranches, db.DefaultContext().Engine().Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
}
// GetDeletedBranchByID get a deleted branch by its ID
func (repo *Repository) GetDeletedBranchByID(id int64) (*DeletedBranch, error) {
deletedBranch := &DeletedBranch{}
has, err := x.ID(id).Get(deletedBranch)
has, err := db.DefaultContext().Engine().ID(id).Get(deletedBranch)
if err != nil {
return nil, err
}
@ -561,19 +552,13 @@ func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
ID: id,
}
sess := x.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if affected, err := sess.Delete(deletedBranch); err != nil {
if affected, err := db.DefaultContext().Engine().Delete(deletedBranch); err != nil {
return err
} else if affected != 1 {
return fmt.Errorf("remove deleted branch ID(%v) failed", id)
}
return sess.Commit()
return nil
}
// LoadUser loads the user that deleted the branch
@ -588,7 +573,7 @@ func (deletedBranch *DeletedBranch) LoadUser() {
// RemoveDeletedBranch removes all deleted branches
func RemoveDeletedBranch(repoID int64, branch string) error {
_, err := x.Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
_, err := db.DefaultContext().Engine().Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
return err
}
@ -598,7 +583,7 @@ func RemoveOldDeletedBranches(ctx context.Context, olderThan time.Duration) {
log.Trace("Doing: DeletedBranchesCleanup")
deleteBefore := time.Now().Add(-olderThan)
_, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
_, err := db.DefaultContext().Engine().Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
if err != nil {
log.Error("DeletedBranchesCleanup: %v", err)
}

View File

@ -7,21 +7,22 @@ package models
import (
"testing"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
)
func TestAddDeletedBranch(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
firstBranch := AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch)
assert.NoError(t, db.PrepareTestDatabase())
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
firstBranch := db.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, PrepareTestDatabase())
repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
assert.NoError(t, db.PrepareTestDatabase())
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
branches, err := repo.GetDeletedBranches()
assert.NoError(t, err)
@ -29,17 +30,17 @@ func TestGetDeletedBranches(t *testing.T) {
}
func TestGetDeletedBranch(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
firstBranch := AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch)
assert.NoError(t, db.PrepareTestDatabase())
firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch)
assert.NotNil(t, getDeletedBranch(t, firstBranch))
}
func TestDeletedBranchLoadUser(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
firstBranch := AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch)
secondBranch := AssertExistsAndLoadBean(t, &DeletedBranch{ID: 2}).(*DeletedBranch)
firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch)
secondBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 2}).(*DeletedBranch)
branch := getDeletedBranch(t, firstBranch)
assert.Nil(t, branch.DeletedBy)
@ -55,19 +56,19 @@ func TestDeletedBranchLoadUser(t *testing.T) {
}
func TestRemoveDeletedBranch(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
assert.NoError(t, db.PrepareTestDatabase())
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
firstBranch := AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch)
firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch)
err := repo.RemoveDeletedBranch(1)
assert.NoError(t, err)
AssertNotExistsBean(t, firstBranch)
AssertExistsAndLoadBean(t, &DeletedBranch{ID: 2})
db.AssertNotExistsBean(t, firstBranch)
db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 2})
}
func getDeletedBranch(t *testing.T, branch *DeletedBranch) *DeletedBranch {
repo := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
deletedBranch, err := repo.GetDeletedBranchByID(branch.ID)
assert.NoError(t, err)

View File

@ -10,6 +10,7 @@ import (
"strings"
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
@ -37,7 +38,11 @@ type CommitStatus struct {
UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
}
func (status *CommitStatus) loadAttributes(e Engine) (err error) {
func init() {
db.RegisterModel(new(CommitStatus))
}
func (status *CommitStatus) loadAttributes(e db.Engine) (err error) {
if status.Repo == nil {
status.Repo, err = getRepositoryByID(e, status.RepoID)
if err != nil {
@ -55,7 +60,7 @@ func (status *CommitStatus) loadAttributes(e Engine) (err error) {
// APIURL returns the absolute APIURL to this commit-status.
func (status *CommitStatus) APIURL() string {
_ = status.loadAttributes(x)
_ = status.loadAttributes(db.DefaultContext().Engine())
return fmt.Sprintf("%sapi/v1/repos/%s/statuses/%s",
setting.AppURL, status.Repo.FullName(), status.SHA)
}
@ -112,7 +117,7 @@ func GetCommitStatuses(repo *Repository, sha string, opts *CommitStatusOptions)
}
func listCommitStatusesStatement(repo *Repository, sha string, opts *CommitStatusOptions) *xorm.Session {
sess := x.Where("repo_id = ?", repo.ID).And("sha = ?", sha)
sess := db.DefaultContext().Engine().Where("repo_id = ?", repo.ID).And("sha = ?", sha)
switch opts.State {
case "pending", "success", "error", "failure", "warning":
sess.And("state = ?", opts.State)
@ -139,10 +144,10 @@ func sortCommitStatusesSession(sess *xorm.Session, sortType string) {
// GetLatestCommitStatus returns all statuses with a unique context for a given commit.
func GetLatestCommitStatus(repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) {
return getLatestCommitStatus(x, repoID, sha, listOptions)
return getLatestCommitStatus(db.DefaultContext().Engine(), repoID, sha, listOptions)
}
func getLatestCommitStatus(e Engine, repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) {
func getLatestCommitStatus(e db.Engine, repoID int64, sha string, listOptions ListOptions) ([]*CommitStatus, error) {
ids := make([]int64, 0, 10)
sess := e.Table(&CommitStatus{}).
Where("repo_id = ?", repoID).And("sha = ?", sha).
@ -166,7 +171,7 @@ func getLatestCommitStatus(e Engine, repoID int64, sha string, listOptions ListO
func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]string, error) {
start := timeutil.TimeStampNow().AddDuration(-before)
ids := make([]int64, 0, 10)
if err := x.Table("commit_status").
if err := db.DefaultContext().Engine().Table("commit_status").
Where("repo_id = ?", repoID).
And("updated_unix >= ?", start).
Select("max( id ) as id").
@ -179,7 +184,7 @@ func FindRepoRecentCommitStatusContexts(repoID int64, before time.Duration) ([]s
if len(ids) == 0 {
return contexts, nil
}
return contexts, x.Select("context").Table("commit_status").In("id", ids).Find(&contexts)
return contexts, db.DefaultContext().Engine().Select("context").Table("commit_status").In("id", ids).Find(&contexts)
}
// NewCommitStatusOptions holds options for creating a CommitStatus
@ -201,12 +206,11 @@ func NewCommitStatus(opts NewCommitStatusOptions) error {
return fmt.Errorf("NewCommitStatus[%s, %s]: no user specified", repoPath, opts.SHA)
}
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
ctx, committer, err := db.TxContext()
if err != nil {
return fmt.Errorf("NewCommitStatus[repo_id: %d, user_id: %d, sha: %s]: %v", opts.Repo.ID, opts.Creator.ID, opts.SHA, err)
}
defer committer.Close()
opts.CommitStatus.Description = strings.TrimSpace(opts.CommitStatus.Description)
opts.CommitStatus.Context = strings.TrimSpace(opts.CommitStatus.Context)
@ -221,11 +225,8 @@ func NewCommitStatus(opts NewCommitStatusOptions) error {
SHA: opts.SHA,
RepoID: opts.Repo.ID,
}
has, err := sess.Desc("index").Limit(1).Get(lastCommitStatus)
has, err := ctx.Engine().Desc("index").Limit(1).Get(lastCommitStatus)
if err != nil {
if err := sess.Rollback(); err != nil {
log.Error("NewCommitStatus: sess.Rollback: %v", err)
}
return fmt.Errorf("NewCommitStatus[%s, %s]: %v", repoPath, opts.SHA, err)
}
if has {
@ -238,14 +239,11 @@ func NewCommitStatus(opts NewCommitStatusOptions) error {
opts.CommitStatus.ContextHash = hashCommitStatusContext(opts.CommitStatus.Context)
// Insert new CommitStatus
if _, err = sess.Insert(opts.CommitStatus); err != nil {
if err := sess.Rollback(); err != nil {
log.Error("Insert CommitStatus: sess.Rollback: %v", err)
}
if _, err = ctx.Engine().Insert(opts.CommitStatus); err != nil {
return fmt.Errorf("Insert CommitStatus[%s, %s]: %v", repoPath, opts.SHA, err)
}
return sess.Commit()
return committer.Commit()
}
// SignCommitWithStatuses represents a commit with validation of signature and status state.

View File

@ -7,14 +7,15 @@ package models
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert"
)
func TestGetCommitStatuses(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
repo1 := AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository)
sha1 := "1234123412341234123412341234123412341234"

View File

@ -5,13 +5,11 @@
package models
import (
"fmt"
"reflect"
"regexp"
"strings"
"testing"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
"xorm.io/builder"
)
@ -43,7 +41,7 @@ func CheckConsistencyFor(t *testing.T, beansToCheck ...interface{}) {
ptrToSliceValue := reflect.New(sliceType)
ptrToSliceValue.Elem().Set(sliceValue)
assert.NoError(t, x.Table(bean).Find(ptrToSliceValue.Interface()))
assert.NoError(t, db.DefaultContext().Engine().Table(bean).Find(ptrToSliceValue.Interface()))
sliceValue = ptrToSliceValue.Elem()
for i := 0; i < sliceValue.Len(); i++ {
@ -60,7 +58,7 @@ func CheckConsistencyFor(t *testing.T, beansToCheck ...interface{}) {
}
// getCount get the count of database entries matching bean
func getCount(t *testing.T, e Engine, bean interface{}) int64 {
func getCount(t *testing.T, e db.Engine, bean interface{}) int64 {
count, err := e.Count(bean)
assert.NoError(t, err)
return count
@ -68,7 +66,7 @@ func getCount(t *testing.T, e Engine, bean interface{}) int64 {
// assertCount test the count of database entries matching bean
func assertCount(t *testing.T, bean interface{}, expected int) {
assert.EqualValues(t, expected, getCount(t, x, bean),
assert.EqualValues(t, expected, getCount(t, db.DefaultContext().Engine(), bean),
"Failed consistency test, the counted bean (of type %T) was %+v", bean, bean)
}
@ -91,46 +89,46 @@ func (repo *Repository) checkForConsistency(t *testing.T) {
assertCount(t, &Milestone{RepoID: repo.ID}, repo.NumMilestones)
assertCount(t, &Repository{ForkID: repo.ID}, repo.NumForks)
if repo.IsFork {
AssertExistsAndLoadBean(t, &Repository{ID: repo.ForkID})
db.AssertExistsAndLoadBean(t, &Repository{ID: repo.ForkID})
}
actual := getCount(t, x.Where("Mode<>?", RepoWatchModeDont), &Watch{RepoID: repo.ID})
actual := getCount(t, db.DefaultContext().Engine().Where("Mode<>?", RepoWatchModeDont), &Watch{RepoID: repo.ID})
assert.EqualValues(t, repo.NumWatches, actual,
"Unexpected number of watches for repo %+v", repo)
actual = getCount(t, x.Where("is_pull=?", false), &Issue{RepoID: repo.ID})
actual = getCount(t, db.DefaultContext().Engine().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, x.Where("is_pull=? AND is_closed=?", false, true), &Issue{RepoID: repo.ID})
actual = getCount(t, db.DefaultContext().Engine().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, x.Where("is_pull=?", true), &Issue{RepoID: repo.ID})
actual = getCount(t, db.DefaultContext().Engine().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, x.Where("is_pull=? AND is_closed=?", true, true), &Issue{RepoID: repo.ID})
actual = getCount(t, db.DefaultContext().Engine().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, x.Where("is_closed=?", true), &Milestone{RepoID: repo.ID})
actual = getCount(t, db.DefaultContext().Engine().Where("is_closed=?", true), &Milestone{RepoID: repo.ID})
assert.EqualValues(t, repo.NumClosedMilestones, actual,
"Unexpected number of closed milestones for repo %+v", repo)
}
func (issue *Issue) checkForConsistency(t *testing.T) {
actual := getCount(t, x.Where("type=?", CommentTypeComment), &Comment{IssueID: issue.ID})
actual := getCount(t, db.DefaultContext().Engine().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 := AssertExistsAndLoadBean(t, &PullRequest{IssueID: issue.ID}).(*PullRequest)
pr := db.AssertExistsAndLoadBean(t, &PullRequest{IssueID: issue.ID}).(*PullRequest)
assert.EqualValues(t, pr.Index, issue.Index)
}
}
func (pr *PullRequest) checkForConsistency(t *testing.T) {
issue := AssertExistsAndLoadBean(t, &Issue{ID: pr.IssueID}).(*Issue)
issue := db.AssertExistsAndLoadBean(t, &Issue{ID: pr.IssueID}).(*Issue)
assert.True(t, issue.IsPull)
assert.EqualValues(t, issue.Index, pr.Index)
}
@ -138,7 +136,7 @@ func (pr *PullRequest) checkForConsistency(t *testing.T) {
func (milestone *Milestone) checkForConsistency(t *testing.T) {
assertCount(t, &Issue{MilestoneID: milestone.ID}, milestone.NumIssues)
actual := getCount(t, x.Where("is_closed=?", true), &Issue{MilestoneID: milestone.ID})
actual := getCount(t, db.DefaultContext().Engine().Where("is_closed=?", true), &Issue{MilestoneID: milestone.ID})
assert.EqualValues(t, milestone.NumClosedIssues, actual,
"Unexpected number of closed issues for milestone %+v", milestone)
@ -151,7 +149,7 @@ func (milestone *Milestone) checkForConsistency(t *testing.T) {
func (label *Label) checkForConsistency(t *testing.T) {
issueLabels := make([]*IssueLabel, 0, 10)
assert.NoError(t, x.Find(&issueLabels, &IssueLabel{LabelID: label.ID}))
assert.NoError(t, db.DefaultContext().Engine().Find(&issueLabels, &IssueLabel{LabelID: label.ID}))
assert.EqualValues(t, label.NumIssues, len(issueLabels),
"Unexpected number of issue for label %+v", label)
@ -162,7 +160,7 @@ func (label *Label) checkForConsistency(t *testing.T) {
expected := int64(0)
if len(issueIDs) > 0 {
expected = getCount(t, x.In("id", issueIDs).Where("is_closed=?", true), &Issue{})
expected = getCount(t, db.DefaultContext().Engine().In("id", issueIDs).Where("is_closed=?", true), &Issue{})
}
assert.EqualValues(t, expected, label.NumClosedIssues,
"Unexpected number of closed issues for label %+v", label)
@ -174,18 +172,18 @@ func (team *Team) checkForConsistency(t *testing.T) {
}
func (action *Action) checkForConsistency(t *testing.T) {
repo := AssertExistsAndLoadBean(t, &Repository{ID: action.RepoID}).(*Repository)
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 := x.Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count("label.id")
noref, err := db.DefaultContext().Engine().Table("label").Where("repo_id=? AND org_id=?", 0, 0).Count("label.id")
if err != nil {
return 0, err
}
norepo, err := x.Table("label").
norepo, err := db.DefaultContext().Engine().Table("label").
Where(builder.And(
builder.Gt{"repo_id": 0},
builder.NotIn("repo_id", builder.Select("id").From("repository")),
@ -195,7 +193,7 @@ func CountOrphanedLabels() (int64, error) {
return 0, err
}
noorg, err := x.Table("label").
noorg, err := db.DefaultContext().Engine().Table("label").
Where(builder.And(
builder.Gt{"org_id": 0},
builder.NotIn("org_id", builder.Select("id").From("user")),
@ -211,12 +209,12 @@ func CountOrphanedLabels() (int64, error) {
// DeleteOrphanedLabels delete labels witch are broken and not accessible via ui anymore
func DeleteOrphanedLabels() error {
// delete labels with no reference
if _, err := x.Table("label").Where("repo_id=? AND org_id=?", 0, 0).Delete(new(Label)); err != nil {
if _, err := db.DefaultContext().Engine().Table("label").Where("repo_id=? AND org_id=?", 0, 0).Delete(new(Label)); err != nil {
return err
}
// delete labels with none existing repos
if _, err := x.
if _, err := db.DefaultContext().Engine().
Where(builder.And(
builder.Gt{"repo_id": 0},
builder.NotIn("repo_id", builder.Select("id").From("repository")),
@ -226,7 +224,7 @@ func DeleteOrphanedLabels() error {
}
// delete labels with none existing orgs
if _, err := x.
if _, err := db.DefaultContext().Engine().
Where(builder.And(
builder.Gt{"org_id": 0},
builder.NotIn("org_id", builder.Select("id").From("user")),
@ -240,14 +238,14 @@ func DeleteOrphanedLabels() error {
// CountOrphanedIssueLabels return count of IssueLabels witch have no label behind anymore
func CountOrphanedIssueLabels() (int64, error) {
return x.Table("issue_label").
return db.DefaultContext().Engine().Table("issue_label").
NotIn("label_id", builder.Select("id").From("label")).
Count()
}
// DeleteOrphanedIssueLabels delete IssueLabels witch have no label behind anymore
func DeleteOrphanedIssueLabels() error {
_, err := x.
_, err := db.DefaultContext().Engine().
NotIn("label_id", builder.Select("id").From("label")).
Delete(IssueLabel{})
@ -256,7 +254,7 @@ func DeleteOrphanedIssueLabels() error {
// CountOrphanedIssues count issues without a repo
func CountOrphanedIssues() (int64, error) {
return x.Table("issue").
return db.DefaultContext().Engine().Table("issue").
Join("LEFT", "repository", "issue.repo_id=repository.id").
Where(builder.IsNull{"repository.id"}).
Count("id")
@ -264,15 +262,15 @@ func CountOrphanedIssues() (int64, error) {
// DeleteOrphanedIssues delete issues without a repo
func DeleteOrphanedIssues() error {
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
ctx, committer, err := db.TxContext()
if err != nil {
return err
}
defer committer.Close()
var ids []int64
if err := sess.Table("issue").Distinct("issue.repo_id").
if err := ctx.Engine().Table("issue").Distinct("issue.repo_id").
Join("LEFT", "repository", "issue.repo_id=repository.id").
Where(builder.IsNull{"repository.id"}).GroupBy("issue.repo_id").
Find(&ids); err != nil {
@ -281,27 +279,28 @@ func DeleteOrphanedIssues() error {
var attachmentPaths []string
for i := range ids {
paths, err := deleteIssuesByRepoID(sess, ids[i])
paths, err := deleteIssuesByRepoID(ctx.Engine(), ids[i])
if err != nil {
return err
}
attachmentPaths = append(attachmentPaths, paths...)
}
if err := sess.Commit(); err != nil {
if err := committer.Commit(); err != nil {
return err
}
committer.Close()
// Remove issue attachment files.
for i := range attachmentPaths {
removeAllWithNotice(x, "Delete issue attachment", attachmentPaths[i])
removeAllWithNotice(db.DefaultContext().Engine(), "Delete issue attachment", attachmentPaths[i])
}
return nil
}
// CountOrphanedObjects count subjects with have no existing refobject anymore
func CountOrphanedObjects(subject, refobject, joinCond string) (int64, error) {
return x.Table("`"+subject+"`").
return db.DefaultContext().Engine().Table("`"+subject+"`").
Join("LEFT", refobject, joinCond).
Where(builder.IsNull{"`" + refobject + "`.id"}).
Count("id")
@ -317,45 +316,45 @@ func DeleteOrphanedObjects(subject, refobject, joinCond string) error {
if err != nil {
return err
}
_, err = x.Exec(append([]interface{}{sql}, args...)...)
_, err = db.DefaultContext().Engine().Exec(append([]interface{}{sql}, args...)...)
return err
}
// CountNullArchivedRepository counts the number of repositories with is_archived is null
func CountNullArchivedRepository() (int64, error) {
return x.Where(builder.IsNull{"is_archived"}).Count(new(Repository))
return db.DefaultContext().Engine().Where(builder.IsNull{"is_archived"}).Count(new(Repository))
}
// FixNullArchivedRepository sets is_archived to false where it is null
func FixNullArchivedRepository() (int64, error) {
return x.Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{
return db.DefaultContext().Engine().Where(builder.IsNull{"is_archived"}).Cols("is_archived").NoAutoTime().Update(&Repository{
IsArchived: false,
})
}
// CountWrongUserType count OrgUser who have wrong type
func CountWrongUserType() (int64, error) {
return x.Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User))
return db.DefaultContext().Engine().Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Count(new(User))
}
// FixWrongUserType fix OrgUser who have wrong type
func FixWrongUserType() (int64, error) {
return x.Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1})
return db.DefaultContext().Engine().Where(builder.Eq{"type": 0}.And(builder.Neq{"num_teams": 0})).Cols("type").NoAutoTime().Update(&User{Type: 1})
}
// CountCommentTypeLabelWithEmptyLabel count label comments with empty label
func CountCommentTypeLabelWithEmptyLabel() (int64, error) {
return x.Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Count(new(Comment))
return db.DefaultContext().Engine().Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Count(new(Comment))
}
// FixCommentTypeLabelWithEmptyLabel count label comments with empty label
func FixCommentTypeLabelWithEmptyLabel() (int64, error) {
return x.Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Delete(new(Comment))
return db.DefaultContext().Engine().Where(builder.Eq{"type": CommentTypeLabel, "label_id": 0}).Delete(new(Comment))
}
// CountCommentTypeLabelWithOutsideLabels count label comments with outside label
func CountCommentTypeLabelWithOutsideLabels() (int64, error) {
return x.Where("comment.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))", CommentTypeLabel).
return db.DefaultContext().Engine().Where("comment.type = ? AND ((label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id))", CommentTypeLabel).
Table("comment").
Join("inner", "label", "label.id = comment.label_id").
Join("inner", "issue", "issue.id = comment.issue_id ").
@ -365,7 +364,7 @@ func CountCommentTypeLabelWithOutsideLabels() (int64, error) {
// FixCommentTypeLabelWithOutsideLabels count label comments with outside label
func FixCommentTypeLabelWithOutsideLabels() (int64, error) {
res, err := x.Exec(`DELETE FROM comment WHERE comment.id IN (
res, err := db.DefaultContext().Engine().Exec(`DELETE FROM comment WHERE comment.id IN (
SELECT il_too.id FROM (
SELECT com.id
FROM comment AS com
@ -384,7 +383,7 @@ func FixCommentTypeLabelWithOutsideLabels() (int64, error) {
// CountIssueLabelWithOutsideLabels count label comments with outside label
func CountIssueLabelWithOutsideLabels() (int64, error) {
return x.Where(builder.Expr("(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)")).
return db.DefaultContext().Engine().Where(builder.Expr("(label.org_id = 0 AND issue.repo_id != label.repo_id) OR (label.repo_id = 0 AND label.org_id != repository.owner_id)")).
Table("issue_label").
Join("inner", "label", "issue_label.label_id = label.id ").
Join("inner", "issue", "issue.id = issue_label.issue_id ").
@ -394,7 +393,7 @@ func CountIssueLabelWithOutsideLabels() (int64, error) {
// FixIssueLabelWithOutsideLabels fix label comments with outside label
func FixIssueLabelWithOutsideLabels() (int64, error) {
res, err := x.Exec(`DELETE FROM issue_label WHERE issue_label.id IN (
res, err := db.DefaultContext().Engine().Exec(`DELETE FROM issue_label WHERE issue_label.id IN (
SELECT il_too.id FROM (
SELECT il_too_too.id
FROM issue_label AS il_too_too
@ -411,61 +410,3 @@ func FixIssueLabelWithOutsideLabels() (int64, error) {
return res.RowsAffected()
}
// CountBadSequences looks for broken sequences from recreate-table mistakes
func CountBadSequences() (int64, error) {
if !setting.Database.UsePostgreSQL {
return 0, nil
}
sess := x.NewSession()
defer sess.Close()
var sequences []string
schema := sess.Engine().Dialect().URI().Schema
sess.Engine().SetSchema("")
if err := sess.Table("information_schema.sequences").Cols("sequence_name").Where("sequence_name LIKE 'tmp_recreate__%_id_seq%' AND sequence_catalog = ?", setting.Database.Name).Find(&sequences); err != nil {
return 0, err
}
sess.Engine().SetSchema(schema)
return int64(len(sequences)), nil
}
// FixBadSequences fixes for broken sequences from recreate-table mistakes
func FixBadSequences() error {
if !setting.Database.UsePostgreSQL {
return nil
}
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
var sequences []string
schema := sess.Engine().Dialect().URI().Schema
sess.Engine().SetSchema("")
if err := sess.Table("information_schema.sequences").Cols("sequence_name").Where("sequence_name LIKE 'tmp_recreate__%_id_seq%' AND sequence_catalog = ?", setting.Database.Name).Find(&sequences); err != nil {
return err
}
sess.Engine().SetSchema(schema)
sequenceRegexp := regexp.MustCompile(`tmp_recreate__(\w+)_id_seq.*`)
for _, sequence := range sequences {
tableName := sequenceRegexp.FindStringSubmatch(sequence)[1]
newSequenceName := tableName + "_id_seq"
if _, err := sess.Exec(fmt.Sprintf("ALTER SEQUENCE `%s` RENAME TO `%s`", sequence, newSequenceName)); err != nil {
return err
}
if _, err := sess.Exec(fmt.Sprintf("SELECT setval('%s', COALESCE((SELECT MAX(id)+1 FROM `%s`), 1), false)", newSequenceName, tableName)); err != nil {
return err
}
}
return sess.Commit()
}

View File

@ -7,16 +7,17 @@ package models
import (
"testing"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
)
func TestDeleteOrphanedObjects(t *testing.T) {
assert.NoError(t, PrepareTestDatabase())
assert.NoError(t, db.PrepareTestDatabase())
countBefore, err := x.Count(&PullRequest{})
countBefore, err := db.DefaultContext().Engine().Count(&PullRequest{})
assert.NoError(t, err)
_, err = x.Insert(&PullRequest{IssueID: 1000}, &PullRequest{IssueID: 1001}, &PullRequest{IssueID: 1003})
_, err = db.DefaultContext().Engine().Insert(&PullRequest{IssueID: 1000}, &PullRequest{IssueID: 1001}, &PullRequest{IssueID: 1003})
assert.NoError(t, err)
orphaned, err := CountOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id")
@ -26,7 +27,7 @@ func TestDeleteOrphanedObjects(t *testing.T) {
err = DeleteOrphanedObjects("pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err)
countAfter, err := x.Count(&PullRequest{})
countAfter, err := db.DefaultContext().Engine().Count(&PullRequest{})
assert.NoError(t, err)
assert.EqualValues(t, countBefore, countAfter)
}

View File

@ -1,71 +0,0 @@
// Copyright 2019 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 models
import (
"code.gitea.io/gitea/modules/setting"
"xorm.io/builder"
)
// DBContext represents a db context
type DBContext struct {
e Engine
}
// DefaultDBContext represents a DBContext with default Engine
func DefaultDBContext() DBContext {
return DBContext{x}
}
// Committer represents an interface to Commit or Close the dbcontext
type Committer interface {
Commit() error
Close() error
}
// TxDBContext represents a transaction DBContext
func TxDBContext() (DBContext, Committer, error) {
sess := x.NewSession()
if err := sess.Begin(); err != nil {
sess.Close()
return DBContext{}, nil, err
}
return DBContext{sess}, sess, nil
}
// WithContext represents executing database operations
func WithContext(f func(ctx DBContext) error) error {
return f(DBContext{x})
}
// WithTx represents executing database operations on a transaction
func WithTx(f func(ctx DBContext) error) error {
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
if err := f(DBContext{sess}); err != nil {
return err
}
return sess.Commit()
}
// Iterate iterates the databases and doing something
func Iterate(ctx DBContext, tableBean interface{}, cond builder.Cond, fun func(idx int, bean interface{}) error) error {
return ctx.e.Where(cond).
BufferSize(setting.Database.IterateBufferSize).
Iterate(tableBean, fun)
}
// Insert inserts records into database
func Insert(ctx DBContext, beans ...interface{}) error {
_, err := ctx.e.Insert(beans...)
return err
}

86
models/db/context.go Normal file
View File

@ -0,0 +1,86 @@
// Copyright 2019 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
import (
"code.gitea.io/gitea/modules/setting"
"xorm.io/builder"
"xorm.io/xorm"
)
// Context represents a db context
type Context struct {
e Engine
}
// Engine returns db engine
func (ctx *Context) Engine() Engine {
return ctx.e
}
// NewSession returns a new session
func (ctx *Context) NewSession() *xorm.Session {
e, ok := ctx.e.(*xorm.Engine)
if ok {
return e.NewSession()
}
return nil
}
// DefaultContext represents a Context with default Engine
func DefaultContext() *Context {
return &Context{x}
}
// Committer represents an interface to Commit or Close the Context
type Committer interface {
Commit() error
Close() error
}
// TxContext represents a transaction Context
func TxContext() (*Context, Committer, error) {
sess := x.NewSession()
if err := sess.Begin(); err != nil {
sess.Close()
return nil, nil, err
}
return &Context{sess}, sess, nil
}
// WithContext represents executing database operations
func WithContext(f func(ctx *Context) error) error {
return f(&Context{x})
}
// WithTx represents executing database operations on a transaction
func WithTx(f func(ctx *Context) error) error {
sess := x.NewSession()
defer sess.Close()
if err := sess.Begin(); err != nil {
return err
}
if err := f(&Context{sess}); err != nil {
return err
}
return sess.Commit()
}
// Iterate iterates the databases and doing something
func Iterate(ctx *Context, tableBean interface{}, cond builder.Cond, fun func(idx int, bean interface{}) error) error {
return ctx.e.Where(cond).
BufferSize(setting.Database.IterateBufferSize).
Iterate(tableBean, fun)
}
// Insert inserts records into database
func Insert(ctx *Context, beans ...interface{}) error {
_, err := ctx.e.Insert(beans...)
return err
}

View File

@ -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 models
package db
import (
"fmt"

Some files were not shown because too many files have changed in this diff Show More