1
1
mirror of https://github.com/go-gitea/gitea synced 2025-08-29 04:48:28 +00:00

Remove incorrect "db.DefaultContext" usages (#35366)

This commit is contained in:
wxiaoguang
2025-08-28 11:52:43 +08:00
committed by GitHub
parent 7aef7ea2d4
commit 0cbaa0b662
256 changed files with 1951 additions and 2098 deletions

View File

@@ -18,12 +18,12 @@ func TestChangePasswordCommand(t *testing.T) {
ctx := t.Context()
defer func() {
require.NoError(t, db.TruncateBeans(db.DefaultContext, &user_model.User{}))
require.NoError(t, db.TruncateBeans(t.Context(), &user_model.User{}))
}()
t.Run("change password successfully", func(t *testing.T) {
// defer func() {
// require.NoError(t, db.TruncateBeans(db.DefaultContext, &user_model.User{}))
// require.NoError(t, db.TruncateBeans(t.Context(), &user_model.User{}))
// }()
// Prepare test user
unittest.AssertNotExistsBean(t, &user_model.User{LowerName: "testuser"})

View File

@@ -19,9 +19,9 @@ import (
func TestAdminUserCreate(t *testing.T) {
reset := func() {
require.NoError(t, db.TruncateBeans(db.DefaultContext, &user_model.User{}))
require.NoError(t, db.TruncateBeans(db.DefaultContext, &user_model.EmailAddress{}))
require.NoError(t, db.TruncateBeans(db.DefaultContext, &auth_model.AccessToken{}))
require.NoError(t, db.TruncateBeans(t.Context(), &user_model.User{}))
require.NoError(t, db.TruncateBeans(t.Context(), &user_model.EmailAddress{}))
require.NoError(t, db.TruncateBeans(t.Context(), &auth_model.AccessToken{}))
}
t.Run("MustChangePassword", func(t *testing.T) {

View File

@@ -19,9 +19,9 @@ import (
func TestAdminUserDelete(t *testing.T) {
ctx := t.Context()
defer func() {
require.NoError(t, db.TruncateBeans(db.DefaultContext, &user_model.User{}))
require.NoError(t, db.TruncateBeans(db.DefaultContext, &user_model.EmailAddress{}))
require.NoError(t, db.TruncateBeans(db.DefaultContext, &auth_model.AccessToken{}))
require.NoError(t, db.TruncateBeans(t.Context(), &user_model.User{}))
require.NoError(t, db.TruncateBeans(t.Context(), &user_model.EmailAddress{}))
require.NoError(t, db.TruncateBeans(t.Context(), &auth_model.AccessToken{}))
}()
setupTestUser := func(t *testing.T) {
@@ -104,8 +104,8 @@ func TestAdminUserDeleteFailure(t *testing.T) {
require.Contains(t, err.Error(), tc.expectedErr)
})
require.NoError(t, db.TruncateBeans(db.DefaultContext, &user_model.User{}))
require.NoError(t, db.TruncateBeans(db.DefaultContext, &user_model.EmailAddress{}))
require.NoError(t, db.TruncateBeans(db.DefaultContext, &auth_model.AccessToken{}))
require.NoError(t, db.TruncateBeans(t.Context(), &user_model.User{}))
require.NoError(t, db.TruncateBeans(t.Context(), &user_model.EmailAddress{}))
require.NoError(t, db.TruncateBeans(t.Context(), &auth_model.AccessToken{}))
}
}

View File

@@ -16,7 +16,7 @@ import (
func TestMustChangePassword(t *testing.T) {
defer func() {
require.NoError(t, db.TruncateBeans(db.DefaultContext, &user_model.User{}))
require.NoError(t, db.TruncateBeans(t.Context(), &user_model.User{}))
}()
err := microcmdUserCreate().Run(t.Context(), []string{"create", "--username", "testuser", "--email", "testuser@gitea.local", "--random-password"})
require.NoError(t, err)

View File

@@ -8,7 +8,6 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/packages"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -30,7 +29,7 @@ func TestMigratePackages(t *testing.T) {
assert.NoError(t, err)
defer buf.Close()
v, f, err := packages_service.CreatePackageAndAddFile(db.DefaultContext, &packages_service.PackageCreationInfo{
v, f, err := packages_service.CreatePackageAndAddFile(t.Context(), &packages_service.PackageCreationInfo{
PackageInfo: packages_service.PackageInfo{
Owner: creator,
PackageType: packages.TypeGeneric,

View File

@@ -6,7 +6,6 @@ package actions
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert"
@@ -15,16 +14,16 @@ import (
func TestGetLatestRunnerToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
token := unittest.AssertExistsAndLoadBean(t, &ActionRunnerToken{ID: 3})
expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0)
expectedToken, err := GetLatestRunnerToken(t.Context(), 1, 0)
assert.NoError(t, err)
assert.Equal(t, expectedToken, token)
}
func TestNewRunnerToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
token, err := NewRunnerToken(db.DefaultContext, 1, 0)
token, err := NewRunnerToken(t.Context(), 1, 0)
assert.NoError(t, err)
expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0)
expectedToken, err := GetLatestRunnerToken(t.Context(), 1, 0)
assert.NoError(t, err)
assert.Equal(t, expectedToken, token)
}
@@ -33,8 +32,8 @@ func TestUpdateRunnerToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
token := unittest.AssertExistsAndLoadBean(t, &ActionRunnerToken{ID: 3})
token.IsActive = true
assert.NoError(t, UpdateRunnerToken(db.DefaultContext, token))
expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0)
assert.NoError(t, UpdateRunnerToken(t.Context(), token))
expectedToken, err := GetLatestRunnerToken(t.Context(), 1, 0)
assert.NoError(t, err)
assert.Equal(t, expectedToken, token)
}

View File

@@ -25,7 +25,7 @@ func TestAction_GetRepoPath(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
action := &activities_model.Action{RepoID: repo.ID}
assert.Equal(t, path.Join(owner.Name, repo.Name), action.GetRepoPath(db.DefaultContext))
assert.Equal(t, path.Join(owner.Name, repo.Name), action.GetRepoPath(t.Context()))
}
func TestAction_GetRepoLink(t *testing.T) {
@@ -37,9 +37,9 @@ func TestAction_GetRepoLink(t *testing.T) {
defer test.MockVariableValue(&setting.AppURL, "https://try.gitea.io/suburl/")()
defer test.MockVariableValue(&setting.AppSubURL, "/suburl")()
expected := path.Join(setting.AppSubURL, owner.Name, repo.Name)
assert.Equal(t, expected, action.GetRepoLink(db.DefaultContext))
assert.Equal(t, repo.HTMLURL(), action.GetRepoAbsoluteLink(db.DefaultContext))
assert.Equal(t, comment.HTMLURL(db.DefaultContext), action.GetCommentHTMLURL(db.DefaultContext))
assert.Equal(t, expected, action.GetRepoLink(t.Context()))
assert.Equal(t, repo.HTMLURL(), action.GetRepoAbsoluteLink(t.Context()))
assert.Equal(t, comment.HTMLURL(t.Context()), action.GetCommentHTMLURL(t.Context()))
}
func TestActivityReadable(t *testing.T) {
@@ -91,37 +91,37 @@ func TestConsistencyUpdateAction(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &activities_model.Action{
ID: int64(id),
})
_, err := db.GetEngine(db.DefaultContext).Exec(`UPDATE action SET created_unix = '' WHERE id = ?`, id)
_, err := db.GetEngine(t.Context()).Exec(`UPDATE action SET created_unix = '' WHERE id = ?`, id)
assert.NoError(t, err)
actions := make([]*activities_model.Action, 0, 1)
//
// XORM returns an error when created_unix is a string
//
err = db.GetEngine(db.DefaultContext).Where("id = ?", id).Find(&actions)
err = db.GetEngine(t.Context()).Where("id = ?", id).Find(&actions)
if assert.Error(t, err) {
assert.Contains(t, err.Error(), "type string to a int64: invalid syntax")
}
//
// Get rid of incorrectly set created_unix
//
count, err := activities_model.CountActionCreatedUnixString(db.DefaultContext)
count, err := activities_model.CountActionCreatedUnixString(t.Context())
assert.NoError(t, err)
assert.EqualValues(t, 1, count)
count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext)
count, err = activities_model.FixActionCreatedUnixString(t.Context())
assert.NoError(t, err)
assert.EqualValues(t, 1, count)
count, err = activities_model.CountActionCreatedUnixString(db.DefaultContext)
count, err = activities_model.CountActionCreatedUnixString(t.Context())
assert.NoError(t, err)
assert.EqualValues(t, 0, count)
count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext)
count, err = activities_model.FixActionCreatedUnixString(t.Context())
assert.NoError(t, err)
assert.EqualValues(t, 0, count)
//
// XORM must be happy now
//
assert.NoError(t, db.GetEngine(db.DefaultContext).Where("id = ?", id).Find(&actions))
assert.NoError(t, db.GetEngine(t.Context()).Where("id = ?", id).Find(&actions))
unittest.CheckConsistencyFor(t, &activities_model.Action{})
}
@@ -133,19 +133,19 @@ func TestDeleteIssueActions(t *testing.T) {
assert.NotEqual(t, issue.ID, issue.Index) // it needs to use different ID/Index to test the DeleteIssueActions to delete some actions by IssueIndex
// insert a comment
err := db.Insert(db.DefaultContext, &issue_model.Comment{Type: issue_model.CommentTypeComment, IssueID: issue.ID})
err := db.Insert(t.Context(), &issue_model.Comment{Type: issue_model.CommentTypeComment, IssueID: issue.ID})
assert.NoError(t, err)
comment := unittest.AssertExistsAndLoadBean(t, &issue_model.Comment{Type: issue_model.CommentTypeComment, IssueID: issue.ID})
// truncate action table and insert some actions
err = db.TruncateBeans(db.DefaultContext, &activities_model.Action{})
err = db.TruncateBeans(t.Context(), &activities_model.Action{})
assert.NoError(t, err)
err = db.Insert(db.DefaultContext, &activities_model.Action{
err = db.Insert(t.Context(), &activities_model.Action{
OpType: activities_model.ActionCommentIssue,
CommentID: comment.ID,
})
assert.NoError(t, err)
err = db.Insert(db.DefaultContext, &activities_model.Action{
err = db.Insert(t.Context(), &activities_model.Action{
OpType: activities_model.ActionCreateIssue,
RepoID: issue.RepoID,
Content: fmt.Sprintf("%d|content...", issue.Index),
@@ -154,6 +154,6 @@ func TestDeleteIssueActions(t *testing.T) {
// assert that the actions exist, then delete them
unittest.AssertCount(t, &activities_model.Action{}, 2)
assert.NoError(t, activities_model.DeleteIssueActions(db.DefaultContext, issue.RepoID, issue.ID, issue.Index))
assert.NoError(t, activities_model.DeleteIssueActions(t.Context(), issue.RepoID, issue.ID, issue.Index))
unittest.AssertCount(t, &activities_model.Action{}, 0)
}

View File

@@ -20,7 +20,7 @@ func TestCreateOrUpdateIssueNotifications(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
assert.NoError(t, activities_model.CreateOrUpdateIssueNotifications(db.DefaultContext, issue.ID, 0, 2, 0))
assert.NoError(t, activities_model.CreateOrUpdateIssueNotifications(t.Context(), issue.ID, 0, 2, 0))
// User 9 is inactive, thus notifications for user 1 and 4 are created
notf := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{UserID: 1, IssueID: issue.ID})
@@ -34,7 +34,7 @@ func TestCreateOrUpdateIssueNotifications(t *testing.T) {
func TestNotificationsForUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
notfs, err := db.Find[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{
notfs, err := db.Find[activities_model.Notification](t.Context(), activities_model.FindNotificationOptions{
UserID: user.ID,
Status: []activities_model.NotificationStatus{
activities_model.NotificationStatusRead,
@@ -55,7 +55,7 @@ func TestNotificationsForUser(t *testing.T) {
func TestNotification_GetRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
notf := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{RepoID: 1})
repo, err := notf.GetRepo(db.DefaultContext)
repo, err := notf.GetRepo(t.Context())
assert.NoError(t, err)
assert.Equal(t, repo, notf.Repository)
assert.Equal(t, notf.RepoID, repo.ID)
@@ -64,7 +64,7 @@ func TestNotification_GetRepo(t *testing.T) {
func TestNotification_GetIssue(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
notf := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{RepoID: 1})
issue, err := notf.GetIssue(db.DefaultContext)
issue, err := notf.GetIssue(t.Context())
assert.NoError(t, err)
assert.Equal(t, issue, notf.Issue)
assert.Equal(t, notf.IssueID, issue.ID)
@@ -73,7 +73,7 @@ func TestNotification_GetIssue(t *testing.T) {
func TestGetNotificationCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
cnt, err := db.Count[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{
cnt, err := db.Count[activities_model.Notification](t.Context(), activities_model.FindNotificationOptions{
UserID: user.ID,
Status: []activities_model.NotificationStatus{
activities_model.NotificationStatusRead,
@@ -82,7 +82,7 @@ func TestGetNotificationCount(t *testing.T) {
assert.NoError(t, err)
assert.EqualValues(t, 0, cnt)
cnt, err = db.Count[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{
cnt, err = db.Count[activities_model.Notification](t.Context(), activities_model.FindNotificationOptions{
UserID: user.ID,
Status: []activities_model.NotificationStatus{
activities_model.NotificationStatusUnread,
@@ -97,14 +97,14 @@ func TestSetNotificationStatus(t *testing.T) {
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
notf := unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead})
_, err := activities_model.SetNotificationStatus(db.DefaultContext, notf.ID, user, activities_model.NotificationStatusPinned)
_, err := activities_model.SetNotificationStatus(t.Context(), notf.ID, user, activities_model.NotificationStatusPinned)
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{ID: notf.ID, Status: activities_model.NotificationStatusPinned})
_, err = activities_model.SetNotificationStatus(db.DefaultContext, 1, user, activities_model.NotificationStatusRead)
_, err = activities_model.SetNotificationStatus(t.Context(), 1, user, activities_model.NotificationStatusRead)
assert.Error(t, err)
_, err = activities_model.SetNotificationStatus(db.DefaultContext, unittest.NonexistentID, user, activities_model.NotificationStatusRead)
_, err = activities_model.SetNotificationStatus(t.Context(), unittest.NonexistentID, user, activities_model.NotificationStatusRead)
assert.Error(t, err)
}
@@ -117,7 +117,7 @@ func TestUpdateNotificationStatuses(t *testing.T) {
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead})
notfPinned := unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusPinned})
assert.NoError(t, activities_model.UpdateNotificationStatuses(db.DefaultContext, user, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead))
assert.NoError(t, activities_model.UpdateNotificationStatuses(t.Context(), user, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead))
unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{ID: notfUnread.ID, Status: activities_model.NotificationStatusRead})
unittest.AssertExistsAndLoadBean(t,
@@ -130,11 +130,11 @@ func TestSetIssueReadBy(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
assert.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error {
assert.NoError(t, db.WithTx(t.Context(), func(ctx context.Context) error {
return activities_model.SetIssueReadBy(ctx, issue.ID, user.ID)
}))
nt, err := activities_model.GetIssueNotification(db.DefaultContext, user.ID, issue.ID)
nt, err := activities_model.GetIssueNotification(t.Context(), user.ID, issue.ID)
assert.NoError(t, err)
assert.Equal(t, activities_model.NotificationStatusRead, nt.Status)
}

View File

@@ -8,7 +8,6 @@ import (
"time"
activities_model "code.gitea.io/gitea/models/activities"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/json"
@@ -70,7 +69,7 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
}
// get the action for comparison
actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
actions, count, err := activities_model.GetFeeds(t.Context(), activities_model.GetFeedsOptions{
RequestedUser: user,
Actor: doer,
IncludePrivate: true,
@@ -80,7 +79,7 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
assert.NoError(t, err)
// Get the heatmap and compare
heatmap, err := activities_model.GetUserHeatmapDataByUser(db.DefaultContext, user, doer)
heatmap, err := activities_model.GetUserHeatmapDataByUser(t.Context(), user, doer)
var contributions int
for _, hm := range heatmap {
contributions += int(hm.Contributions)

View File

@@ -232,7 +232,7 @@ Q0KHb+QcycSgbDx0ZAvdIacuKvBBcbxrsmFUI4LR+oIup0G9gUc0roPvr014jYQL
=zHo9
-----END PGP PUBLIC KEY BLOCK-----`
keys, err := AddGPGKey(db.DefaultContext, 1, testEmailWithUpperCaseLetters, "", "")
keys, err := AddGPGKey(t.Context(), 1, testEmailWithUpperCaseLetters, "", "")
assert.NoError(t, err)
if assert.NotEmpty(t, keys) {
key := keys[0]
@@ -407,12 +407,12 @@ func TestTryGetKeyIDFromSignature(t *testing.T) {
func TestParseGPGKey(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, db.Insert(db.DefaultContext, &user_model.EmailAddress{UID: 1, Email: "email1@example.com", IsActivated: true}))
assert.NoError(t, db.Insert(t.Context(), &user_model.EmailAddress{UID: 1, Email: "email1@example.com", IsActivated: true}))
// create a key for test email
e, err := openpgp.NewEntity("name", "comment", "email1@example.com", nil)
require.NoError(t, err)
k, err := parseGPGKey(db.DefaultContext, 1, e, true)
k, err := parseGPGKey(t.Context(), 1, e, true)
require.NoError(t, err)
assert.NotEmpty(t, k.KeyID)
assert.NotEmpty(t, k.Emails) // the key is valid, matches the email
@@ -421,7 +421,7 @@ func TestParseGPGKey(t *testing.T) {
for _, id := range e.Identities {
id.Revocations = append(id.Revocations, &packet.Signature{RevocationReason: util.ToPointer(packet.KeyCompromised)})
}
k, err = parseGPGKey(db.DefaultContext, 1, e, true)
k, err = parseGPGKey(t.Context(), 1, e, true)
require.NoError(t, err)
assert.NotEmpty(t, k.KeyID)
assert.Empty(t, k.Emails) // the key is revoked, matches no email

View File

@@ -12,7 +12,6 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
@@ -476,7 +475,7 @@ func runErr(t *testing.T, stdin []byte, args ...string) {
func Test_PublicKeysAreExternallyManaged(t *testing.T) {
key1 := unittest.AssertExistsAndLoadBean(t, &PublicKey{ID: 1})
externals, err := PublicKeysAreExternallyManaged(db.DefaultContext, []*PublicKey{key1})
externals, err := PublicKeysAreExternallyManaged(t.Context(), []*PublicKey{key1})
assert.NoError(t, err)
assert.Len(t, externals, 1)
assert.False(t, externals[0])

View File

@@ -19,7 +19,7 @@ func TestNewAccessToken(t *testing.T) {
UID: 3,
Name: "Token C",
}
assert.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token))
assert.NoError(t, auth_model.NewAccessToken(t.Context(), token))
unittest.AssertExistsAndLoadBean(t, token)
invalidToken := &auth_model.AccessToken{
@@ -27,7 +27,7 @@ func TestNewAccessToken(t *testing.T) {
UID: 2,
Name: "Token F",
}
assert.Error(t, auth_model.NewAccessToken(db.DefaultContext, invalidToken))
assert.Error(t, auth_model.NewAccessToken(t.Context(), invalidToken))
}
func TestAccessTokenByNameExists(t *testing.T) {
@@ -40,16 +40,16 @@ func TestAccessTokenByNameExists(t *testing.T) {
}
// Check to make sure it doesn't exists already
exist, err := auth_model.AccessTokenByNameExists(db.DefaultContext, token)
exist, err := auth_model.AccessTokenByNameExists(t.Context(), token)
assert.NoError(t, err)
assert.False(t, exist)
// Save it to the database
assert.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token))
assert.NoError(t, auth_model.NewAccessToken(t.Context(), token))
unittest.AssertExistsAndLoadBean(t, token)
// This token must be found by name in the DB now
exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, token)
exist, err = auth_model.AccessTokenByNameExists(t.Context(), token)
assert.NoError(t, err)
assert.True(t, exist)
@@ -60,32 +60,32 @@ func TestAccessTokenByNameExists(t *testing.T) {
// Name matches but different user ID, this shouldn't exists in the
// database
exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, user4Token)
exist, err = auth_model.AccessTokenByNameExists(t.Context(), user4Token)
assert.NoError(t, err)
assert.False(t, exist)
}
func TestGetAccessTokenBySHA(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "d2c6c1ba3890b309189a8e618c72a162e4efbf36")
token, err := auth_model.GetAccessTokenBySHA(t.Context(), "d2c6c1ba3890b309189a8e618c72a162e4efbf36")
assert.NoError(t, err)
assert.Equal(t, int64(1), token.UID)
assert.Equal(t, "Token A", token.Name)
assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash)
assert.Equal(t, "e4efbf36", token.TokenLastEight)
_, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "notahash")
_, err = auth_model.GetAccessTokenBySHA(t.Context(), "notahash")
assert.Error(t, err)
assert.True(t, auth_model.IsErrAccessTokenNotExist(err))
_, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "")
_, err = auth_model.GetAccessTokenBySHA(t.Context(), "")
assert.Error(t, err)
assert.True(t, auth_model.IsErrAccessTokenEmpty(err))
}
func TestListAccessTokens(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
tokens, err := db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 1})
tokens, err := db.Find[auth_model.AccessToken](t.Context(), auth_model.ListAccessTokensOptions{UserID: 1})
assert.NoError(t, err)
if assert.Len(t, tokens, 2) {
assert.Equal(t, int64(1), tokens[0].UID)
@@ -94,39 +94,39 @@ func TestListAccessTokens(t *testing.T) {
assert.Contains(t, []string{tokens[0].Name, tokens[1].Name}, "Token B")
}
tokens, err = db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 2})
tokens, err = db.Find[auth_model.AccessToken](t.Context(), auth_model.ListAccessTokensOptions{UserID: 2})
assert.NoError(t, err)
if assert.Len(t, tokens, 1) {
assert.Equal(t, int64(2), tokens[0].UID)
assert.Equal(t, "Token A", tokens[0].Name)
}
tokens, err = db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 100})
tokens, err = db.Find[auth_model.AccessToken](t.Context(), auth_model.ListAccessTokensOptions{UserID: 100})
assert.NoError(t, err)
assert.Empty(t, tokens)
}
func TestUpdateAccessToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c")
token, err := auth_model.GetAccessTokenBySHA(t.Context(), "4c6f36e6cf498e2a448662f915d932c09c5a146c")
assert.NoError(t, err)
token.Name = "Token Z"
assert.NoError(t, auth_model.UpdateAccessToken(db.DefaultContext, token))
assert.NoError(t, auth_model.UpdateAccessToken(t.Context(), token))
unittest.AssertExistsAndLoadBean(t, token)
}
func TestDeleteAccessTokenByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c")
token, err := auth_model.GetAccessTokenBySHA(t.Context(), "4c6f36e6cf498e2a448662f915d932c09c5a146c")
assert.NoError(t, err)
assert.Equal(t, int64(1), token.UID)
assert.NoError(t, auth_model.DeleteAccessTokenByID(db.DefaultContext, token.ID, 1))
assert.NoError(t, auth_model.DeleteAccessTokenByID(t.Context(), token.ID, 1))
unittest.AssertNotExistsBean(t, token)
err = auth_model.DeleteAccessTokenByID(db.DefaultContext, 100, 100)
err = auth_model.DeleteAccessTokenByID(t.Context(), 100, 100)
assert.Error(t, err)
assert.True(t, auth_model.IsErrAccessTokenNotExist(err))
}

View File

@@ -7,7 +7,6 @@ import (
"testing"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert"
@@ -16,7 +15,7 @@ import (
func TestOAuth2Application_GenerateClientSecret(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
secret, err := app.GenerateClientSecret(db.DefaultContext)
secret, err := app.GenerateClientSecret(t.Context())
assert.NoError(t, err)
assert.NotEmpty(t, secret)
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1, ClientSecret: app.ClientSecret})
@@ -26,7 +25,7 @@ func BenchmarkOAuth2Application_GenerateClientSecret(b *testing.B) {
assert.NoError(b, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(b, &auth_model.OAuth2Application{ID: 1})
for b.Loop() {
_, _ = app.GenerateClientSecret(db.DefaultContext)
_, _ = app.GenerateClientSecret(b.Context())
}
}
@@ -76,7 +75,7 @@ func TestOAuth2Application_ContainsRedirect_Slash(t *testing.T) {
func TestOAuth2Application_ValidateClientSecret(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
secret, err := app.GenerateClientSecret(db.DefaultContext)
secret, err := app.GenerateClientSecret(t.Context())
assert.NoError(t, err)
assert.True(t, app.ValidateClientSecret([]byte(secret)))
assert.False(t, app.ValidateClientSecret([]byte("fewijfowejgfiowjeoifew")))
@@ -84,18 +83,18 @@ func TestOAuth2Application_ValidateClientSecret(t *testing.T) {
func TestGetOAuth2ApplicationByClientID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
app, err := auth_model.GetOAuth2ApplicationByClientID(db.DefaultContext, "da7da3ba-9a13-4167-856f-3899de0b0138")
app, err := auth_model.GetOAuth2ApplicationByClientID(t.Context(), "da7da3ba-9a13-4167-856f-3899de0b0138")
assert.NoError(t, err)
assert.Equal(t, "da7da3ba-9a13-4167-856f-3899de0b0138", app.ClientID)
app, err = auth_model.GetOAuth2ApplicationByClientID(db.DefaultContext, "invalid client id")
app, err = auth_model.GetOAuth2ApplicationByClientID(t.Context(), "invalid client id")
assert.Error(t, err)
assert.Nil(t, app)
}
func TestCreateOAuth2Application(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
app, err := auth_model.CreateOAuth2Application(db.DefaultContext, auth_model.CreateOAuth2ApplicationOptions{Name: "newapp", UserID: 1})
app, err := auth_model.CreateOAuth2Application(t.Context(), auth_model.CreateOAuth2ApplicationOptions{Name: "newapp", UserID: 1})
assert.NoError(t, err)
assert.Equal(t, "newapp", app.Name)
assert.Len(t, app.ClientID, 36)
@@ -109,11 +108,11 @@ func TestOAuth2Application_TableName(t *testing.T) {
func TestOAuth2Application_GetGrantByUserID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
grant, err := app.GetGrantByUserID(db.DefaultContext, 1)
grant, err := app.GetGrantByUserID(t.Context(), 1)
assert.NoError(t, err)
assert.Equal(t, int64(1), grant.UserID)
grant, err = app.GetGrantByUserID(db.DefaultContext, 34923458)
grant, err = app.GetGrantByUserID(t.Context(), 34923458)
assert.NoError(t, err)
assert.Nil(t, grant)
}
@@ -121,7 +120,7 @@ func TestOAuth2Application_GetGrantByUserID(t *testing.T) {
func TestOAuth2Application_CreateGrant(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
grant, err := app.CreateGrant(db.DefaultContext, 2, "")
grant, err := app.CreateGrant(t.Context(), 2, "")
assert.NoError(t, err)
assert.NotNil(t, grant)
assert.Equal(t, int64(2), grant.UserID)
@@ -133,11 +132,11 @@ func TestOAuth2Application_CreateGrant(t *testing.T) {
func TestGetOAuth2GrantByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
grant, err := auth_model.GetOAuth2GrantByID(db.DefaultContext, 1)
grant, err := auth_model.GetOAuth2GrantByID(t.Context(), 1)
assert.NoError(t, err)
assert.Equal(t, int64(1), grant.ID)
grant, err = auth_model.GetOAuth2GrantByID(db.DefaultContext, 34923458)
grant, err = auth_model.GetOAuth2GrantByID(t.Context(), 34923458)
assert.NoError(t, err)
assert.Nil(t, grant)
}
@@ -145,7 +144,7 @@ func TestGetOAuth2GrantByID(t *testing.T) {
func TestOAuth2Grant_IncreaseCounter(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 1})
assert.NoError(t, grant.IncreaseCounter(db.DefaultContext))
assert.NoError(t, grant.IncreaseCounter(t.Context()))
assert.Equal(t, int64(2), grant.Counter)
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 2})
}
@@ -162,7 +161,7 @@ func TestOAuth2Grant_ScopeContains(t *testing.T) {
func TestOAuth2Grant_GenerateNewAuthorizationCode(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1})
code, err := grant.GenerateNewAuthorizationCode(db.DefaultContext, "https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256")
code, err := grant.GenerateNewAuthorizationCode(t.Context(), "https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256")
assert.NoError(t, err)
assert.NotNil(t, code)
assert.Greater(t, len(code.Code), 32) // secret length > 32
@@ -174,20 +173,20 @@ func TestOAuth2Grant_TableName(t *testing.T) {
func TestGetOAuth2GrantsByUserID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
result, err := auth_model.GetOAuth2GrantsByUserID(db.DefaultContext, 1)
result, err := auth_model.GetOAuth2GrantsByUserID(t.Context(), 1)
assert.NoError(t, err)
assert.Len(t, result, 1)
assert.Equal(t, int64(1), result[0].ID)
assert.Equal(t, result[0].ApplicationID, result[0].Application.ID)
result, err = auth_model.GetOAuth2GrantsByUserID(db.DefaultContext, 34134)
result, err = auth_model.GetOAuth2GrantsByUserID(t.Context(), 34134)
assert.NoError(t, err)
assert.Empty(t, result)
}
func TestRevokeOAuth2Grant(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, auth_model.RevokeOAuth2Grant(db.DefaultContext, 1, 1))
assert.NoError(t, auth_model.RevokeOAuth2Grant(t.Context(), 1, 1))
unittest.AssertNotExistsBean(t, &auth_model.OAuth2Grant{ID: 1, UserID: 1})
}
@@ -195,13 +194,13 @@ func TestRevokeOAuth2Grant(t *testing.T) {
func TestGetOAuth2AuthorizationByCode(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
code, err := auth_model.GetOAuth2AuthorizationByCode(db.DefaultContext, "authcode")
code, err := auth_model.GetOAuth2AuthorizationByCode(t.Context(), "authcode")
assert.NoError(t, err)
assert.NotNil(t, code)
assert.Equal(t, "authcode", code.Code)
assert.Equal(t, int64(1), code.ID)
code, err = auth_model.GetOAuth2AuthorizationByCode(db.DefaultContext, "does not exist")
code, err = auth_model.GetOAuth2AuthorizationByCode(t.Context(), "does not exist")
assert.NoError(t, err)
assert.Nil(t, code)
}
@@ -256,7 +255,7 @@ func TestOAuth2AuthorizationCode_GenerateRedirectURI(t *testing.T) {
func TestOAuth2AuthorizationCode_Invalidate(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
code := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2AuthorizationCode{Code: "authcode"})
assert.NoError(t, code.Invalidate(db.DefaultContext))
assert.NoError(t, code.Invalidate(t.Context()))
unittest.AssertNotExistsBean(t, &auth_model.OAuth2AuthorizationCode{Code: "authcode"})
}

View File

@@ -14,7 +14,6 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/xorm"
"xorm.io/xorm/schemas"
)
@@ -46,7 +45,7 @@ func TestDumpAuthSource(t *testing.T) {
auth_model.RegisterTypeConfig(auth_model.OAuth2, new(TestSource))
auth_model.CreateSource(db.DefaultContext, &auth_model.Source{
auth_model.CreateSource(t.Context(), &auth_model.Source{
Type: auth_model.OAuth2,
Name: "TestSource",
IsActive: false,
@@ -59,7 +58,7 @@ func TestDumpAuthSource(t *testing.T) {
sb := new(strings.Builder)
// TODO: this test is quite hacky, it should use a low-level "select" (without model processors) but not a database dump
engine := db.GetEngine(db.DefaultContext).(*xorm.Engine)
engine := unittest.GetXORMEngine()
require.NoError(t, engine.DumpTables([]*schemas.Table{authSourceSchema}, sb))
assert.Contains(t, sb.String(), `"Provider":"ConvertibleSourceName"`)
}

View File

@@ -7,7 +7,6 @@ import (
"testing"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"github.com/go-webauthn/webauthn/webauthn"
@@ -17,11 +16,11 @@ import (
func TestGetWebAuthnCredentialByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
res, err := auth_model.GetWebAuthnCredentialByID(db.DefaultContext, 1)
res, err := auth_model.GetWebAuthnCredentialByID(t.Context(), 1)
assert.NoError(t, err)
assert.Equal(t, "WebAuthn credential", res.Name)
_, err = auth_model.GetWebAuthnCredentialByID(db.DefaultContext, 342432)
_, err = auth_model.GetWebAuthnCredentialByID(t.Context(), 342432)
assert.Error(t, err)
assert.True(t, auth_model.IsErrWebAuthnCredentialNotExist(err))
}
@@ -29,7 +28,7 @@ func TestGetWebAuthnCredentialByID(t *testing.T) {
func TestGetWebAuthnCredentialsByUID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
res, err := auth_model.GetWebAuthnCredentialsByUID(db.DefaultContext, 32)
res, err := auth_model.GetWebAuthnCredentialsByUID(t.Context(), 32)
assert.NoError(t, err)
assert.Len(t, res, 1)
assert.Equal(t, "WebAuthn credential", res[0].Name)
@@ -43,7 +42,7 @@ func TestWebAuthnCredential_UpdateSignCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
cred := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1})
cred.SignCount = 1
assert.NoError(t, cred.UpdateSignCount(db.DefaultContext))
assert.NoError(t, cred.UpdateSignCount(t.Context()))
unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1, SignCount: 1})
}
@@ -51,14 +50,14 @@ func TestWebAuthnCredential_UpdateLargeCounter(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
cred := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1})
cred.SignCount = 0xffffffff
assert.NoError(t, cred.UpdateSignCount(db.DefaultContext))
assert.NoError(t, cred.UpdateSignCount(t.Context()))
unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1, SignCount: 0xffffffff})
}
func TestCreateCredential(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
res, err := auth_model.CreateCredential(db.DefaultContext, 1, "WebAuthn Created Credential", &webauthn.Credential{ID: []byte("Test")})
res, err := auth_model.CreateCredential(t.Context(), 1, "WebAuthn Created Credential", &webauthn.Credential{ID: []byte("Test")})
assert.NoError(t, err)
assert.Equal(t, "WebAuthn Created Credential", res.Name)
assert.Equal(t, []byte("Test"), res.CredentialID)

View File

@@ -7,7 +7,6 @@ import (
"testing"
avatars_model "code.gitea.io/gitea/models/avatars"
"code.gitea.io/gitea/models/db"
system_model "code.gitea.io/gitea/models/system"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/setting/config"
@@ -18,14 +17,14 @@ import (
const gravatarSource = "https://secure.gravatar.com/avatar/"
func disableGravatar(t *testing.T) {
err := system_model.SetSettings(db.DefaultContext, map[string]string{setting.Config().Picture.EnableFederatedAvatar.DynKey(): "false"})
err := system_model.SetSettings(t.Context(), map[string]string{setting.Config().Picture.EnableFederatedAvatar.DynKey(): "false"})
assert.NoError(t, err)
err = system_model.SetSettings(db.DefaultContext, map[string]string{setting.Config().Picture.DisableGravatar.DynKey(): "true"})
err = system_model.SetSettings(t.Context(), map[string]string{setting.Config().Picture.DisableGravatar.DynKey(): "true"})
assert.NoError(t, err)
}
func enableGravatar(t *testing.T) {
err := system_model.SetSettings(db.DefaultContext, map[string]string{setting.Config().Picture.DisableGravatar.DynKey(): "false"})
err := system_model.SetSettings(t.Context(), map[string]string{setting.Config().Picture.DisableGravatar.DynKey(): "false"})
assert.NoError(t, err)
setting.GravatarSource = gravatarSource
}
@@ -47,12 +46,12 @@ func TestSizedAvatarLink(t *testing.T) {
disableGravatar(t)
config.GetDynGetter().InvalidateCache()
assert.Equal(t, "/testsuburl/assets/img/avatar_default.png",
avatars_model.GenerateEmailAvatarFastLink(db.DefaultContext, "gitea@example.com", 100))
avatars_model.GenerateEmailAvatarFastLink(t.Context(), "gitea@example.com", 100))
enableGravatar(t)
config.GetDynGetter().InvalidateCache()
assert.Equal(t,
"https://secure.gravatar.com/avatar/353cbad9b58e69c96154ad99f92bedc7?d=identicon&s=100",
avatars_model.GenerateEmailAvatarFastLink(db.DefaultContext, "gitea@example.com", 100),
avatars_model.GenerateEmailAvatarFastLink(t.Context(), "gitea@example.com", 100),
)
}

View File

@@ -17,26 +17,23 @@ import (
"xorm.io/xorm"
)
// DefaultContext is the default context to run xorm queries in
// will be overwritten by Init with HammerContext
var DefaultContext context.Context
type engineContextKeyType struct{}
var engineContextKey = engineContextKeyType{}
// Context represents a db context
type Context struct {
type xormContextType struct {
context.Context
engine Engine
}
func newContext(ctx context.Context, e Engine) *Context {
return &Context{Context: ctx, engine: e}
var xormContext *xormContextType
func newContext(ctx context.Context, e Engine) *xormContextType {
return &xormContextType{Context: ctx, engine: e}
}
// Value shadows Value for context.Context but allows us to get ourselves and an Engined object
func (ctx *Context) Value(key any) any {
func (ctx *xormContextType) Value(key any) any {
if key == engineContextKey {
return ctx
}
@@ -44,7 +41,7 @@ func (ctx *Context) Value(key any) any {
}
// WithContext returns this engine tied to this context
func (ctx *Context) WithContext(other context.Context) *Context {
func (ctx *xormContextType) WithContext(other context.Context) *xormContextType {
return newContext(ctx, ctx.engine.Context(other))
}
@@ -90,20 +87,24 @@ func contextSafetyCheck(e Engine) {
}
// GetEngine gets an existing db Engine/Statement or creates a new Session
func GetEngine(ctx context.Context) Engine {
func GetEngine(ctx context.Context) (e Engine) {
defer func() { contextSafetyCheck(e) }()
if e := getExistingEngine(ctx); e != nil {
return e
}
return xormEngine.Context(ctx)
}
func GetXORMEngineForTesting() *xorm.Engine {
return xormEngine
}
// getExistingEngine gets an existing db Engine/Statement from this context or returns nil
func getExistingEngine(ctx context.Context) (e Engine) {
defer func() { contextSafetyCheck(e) }()
if engined, ok := ctx.(*Context); ok {
if engined, ok := ctx.(*xormContextType); ok {
return engined.engine
}
if engined, ok := ctx.Value(engineContextKey).(*Context); ok {
if engined, ok := ctx.Value(engineContextKey).(*xormContextType); ok {
return engined.engine
}
return nil
@@ -150,7 +151,7 @@ func (c *halfCommitter) Close() error {
// So calling `Commit()` will do nothing, but calling `Close()` without calling `Commit()` will rollback the transaction.
// And all operations submitted by the caller stack will be rollbacked as well, not only the operations in the current function.
// d. It doesn't mean rollback is forbidden, but always do it only when there is an error, and you do want to rollback.
func TxContext(parentCtx context.Context) (*Context, Committer, error) {
func TxContext(parentCtx context.Context) (context.Context, Committer, error) {
if sess, ok := inTransaction(parentCtx); ok {
return newContext(parentCtx, sess), &halfCommitter{committer: sess}, nil
}
@@ -161,7 +162,7 @@ func TxContext(parentCtx context.Context) (*Context, Committer, error) {
return nil, nil, err
}
return newContext(DefaultContext, sess), sess, nil
return newContext(xormContext, sess), sess, nil
}
// WithTx represents executing database operations on a transaction, if the transaction exist,

View File

@@ -39,7 +39,7 @@ func Test_halfCommitter(t *testing.T) {
/*
Do something like:
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(t.Context())
if err != nil {
return nil
}

View File

@@ -15,13 +15,13 @@ import (
func TestInTransaction(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.False(t, db.InTransaction(db.DefaultContext))
assert.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error {
assert.False(t, db.InTransaction(t.Context()))
assert.NoError(t, db.WithTx(t.Context(), func(ctx context.Context) error {
assert.True(t, db.InTransaction(ctx))
return nil
}))
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(t.Context())
assert.NoError(t, err)
defer committer.Close()
assert.True(t, db.InTransaction(ctx))
@@ -35,14 +35,14 @@ func TestTxContext(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
{ // create new transaction
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(t.Context())
assert.NoError(t, err)
assert.True(t, db.InTransaction(ctx))
assert.NoError(t, committer.Commit())
}
{ // reuse the transaction created by TxContext and commit it
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(t.Context())
engine := db.GetEngine(ctx)
assert.NoError(t, err)
assert.True(t, db.InTransaction(ctx))
@@ -57,7 +57,7 @@ func TestTxContext(t *testing.T) {
}
{ // reuse the transaction created by TxContext and close it
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(t.Context())
engine := db.GetEngine(ctx)
assert.NoError(t, err)
assert.True(t, db.InTransaction(ctx))
@@ -72,7 +72,7 @@ func TestTxContext(t *testing.T) {
}
{ // reuse the transaction created by WithTx
assert.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error {
assert.NoError(t, db.WithTx(t.Context(), func(ctx context.Context) error {
assert.True(t, db.InTransaction(ctx))
{
ctx, committer, err := db.TxContext(ctx)
@@ -93,16 +93,16 @@ func TestContextSafety(t *testing.T) {
ID int64
}
assert.NoError(t, unittest.GetXORMEngine().Sync(&TestModel1{}, &TestModel2{}))
assert.NoError(t, db.TruncateBeans(db.DefaultContext, &TestModel1{}, &TestModel2{}))
assert.NoError(t, db.TruncateBeans(t.Context(), &TestModel1{}, &TestModel2{}))
testCount := 10
for i := 1; i <= testCount; i++ {
assert.NoError(t, db.Insert(db.DefaultContext, &TestModel1{ID: int64(i)}))
assert.NoError(t, db.Insert(db.DefaultContext, &TestModel2{ID: int64(-i)}))
assert.NoError(t, db.Insert(t.Context(), &TestModel1{ID: int64(i)}))
assert.NoError(t, db.Insert(t.Context(), &TestModel2{ID: int64(-i)}))
}
actualCount := 0
// here: db.GetEngine(db.DefaultContext) is a new *Session created from *Engine
_ = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
// here: db.GetEngine(t.Context()) is a new *Session created from *Engine
_ = db.WithTx(t.Context(), func(ctx context.Context) error {
_ = db.GetEngine(ctx).Iterate(&TestModel1{}, func(i int, bean any) error {
// here: db.GetEngine(ctx) is always the unclosed "Iterate" *Session with autoResetStatement=false,
// and the internal states (including "cond" and others) are always there and not be reset in this callback.
@@ -123,7 +123,7 @@ func TestContextSafety(t *testing.T) {
// deny the bad usages
assert.PanicsWithError(t, "using database context in an iterator would cause corrupted results", func() {
_ = unittest.GetXORMEngine().Iterate(&TestModel1{}, func(i int, bean any) error {
_ = db.GetEngine(db.DefaultContext)
_ = db.GetEngine(t.Context())
return nil
})
})

View File

@@ -59,8 +59,14 @@ type Engine interface {
Cols(...string) *xorm.Session
Context(ctx context.Context) *xorm.Session
Ping() error
IsTableExist(tableNameOrBean any) (bool, error)
}
var (
_ Engine = (*xorm.Engine)(nil)
_ Engine = (*xorm.Session)(nil)
)
// TableInfo returns table's information via an object
func TableInfo(v any) (*schemas.Table, error) {
return xormEngine.TableInfo(v)

View File

@@ -52,7 +52,7 @@ func newXORMEngine() (*xorm.Engine, error) {
return engine, nil
}
// InitEngine initializes the xorm.Engine and sets it as db.DefaultContext
// InitEngine initializes the xorm.Engine and sets it as XORM's default context
func InitEngine(ctx context.Context) error {
xe, err := newXORMEngine()
if err != nil {
@@ -70,7 +70,6 @@ func InitEngine(ctx context.Context) error {
xe.SetMaxOpenConns(setting.Database.MaxOpenConns)
xe.SetMaxIdleConns(setting.Database.MaxIdleConns)
xe.SetConnMaxLifetime(setting.Database.ConnMaxLifetime)
xe.SetDefaultContext(ctx)
if setting.Database.SlowQueryThreshold > 0 {
xe.AddHook(&EngineHook{
@@ -86,22 +85,23 @@ func InitEngine(ctx context.Context) error {
// SetDefaultEngine sets the default engine for db
func SetDefaultEngine(ctx context.Context, eng *xorm.Engine) {
xormEngine = eng
DefaultContext = &Context{Context: ctx, engine: xormEngine}
xormEngine.SetDefaultContext(ctx)
xormContext = &xormContextType{Context: ctx, engine: xormEngine}
}
// UnsetDefaultEngine closes and unsets the default engine
// We hope the SetDefaultEngine and UnsetDefaultEngine can be paired, but it's impossible now,
// there are many calls to InitEngine -> SetDefaultEngine directly to overwrite the `xormEngine` and DefaultContext without close
// there are many calls to InitEngine -> SetDefaultEngine directly to overwrite the `xormEngine` and `xormContext` without close
// Global database engine related functions are all racy and there is no graceful close right now.
func UnsetDefaultEngine() {
if xormEngine != nil {
_ = xormEngine.Close()
xormEngine = nil
}
DefaultContext = nil
xormContext = nil
}
// InitEngineWithMigration initializes a new xorm.Engine and sets it as the db.DefaultContext
// InitEngineWithMigration initializes a new xorm.Engine and sets it as the XORM's default context
// This function must never call .Sync() if the provided migration function fails.
// When called from the "doctor" command, the migration function is a version check
// that prevents the doctor from fixing anything in the database if the migration level

View File

@@ -27,7 +27,7 @@ func TestDumpDatabase(t *testing.T) {
ID int64 `xorm:"pk autoincr"`
Version int64
}
assert.NoError(t, db.GetEngine(db.DefaultContext).Sync(new(Version)))
assert.NoError(t, db.GetEngine(t.Context()).Sync(new(Version)))
for _, dbType := range setting.SupportedDatabaseTypes {
assert.NoError(t, db.DumpDatabase(filepath.Join(dir, dbType+".sql"), dbType))
@@ -37,20 +37,20 @@ func TestDumpDatabase(t *testing.T) {
func TestDeleteOrphanedObjects(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
countBefore, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{})
countBefore, err := db.GetEngine(t.Context()).Count(&issues_model.PullRequest{})
assert.NoError(t, err)
_, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003})
_, err = db.GetEngine(t.Context()).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003})
assert.NoError(t, err)
orphaned, err := db.CountOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id")
orphaned, err := db.CountOrphanedObjects(t.Context(), "pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err)
assert.EqualValues(t, 3, orphaned)
err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id")
err = db.DeleteOrphanedObjects(t.Context(), "pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err)
countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{})
countAfter, err := db.GetEngine(t.Context()).Count(&issues_model.PullRequest{})
assert.NoError(t, err)
assert.Equal(t, countBefore, countAfter)
}

View File

@@ -35,30 +35,30 @@ func TestSyncMaxResourceIndex(t *testing.T) {
xe := unittest.GetXORMEngine()
assert.NoError(t, xe.Sync(&TestIndex{}))
err := db.SyncMaxResourceIndex(db.DefaultContext, "test_index", 10, 51)
err := db.SyncMaxResourceIndex(t.Context(), "test_index", 10, 51)
assert.NoError(t, err)
// sync new max index
maxIndex, err := getCurrentResourceIndex(db.DefaultContext, "test_index", 10)
maxIndex, err := getCurrentResourceIndex(t.Context(), "test_index", 10)
assert.NoError(t, err)
assert.EqualValues(t, 51, maxIndex)
// smaller index doesn't change
err = db.SyncMaxResourceIndex(db.DefaultContext, "test_index", 10, 30)
err = db.SyncMaxResourceIndex(t.Context(), "test_index", 10, 30)
assert.NoError(t, err)
maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10)
maxIndex, err = getCurrentResourceIndex(t.Context(), "test_index", 10)
assert.NoError(t, err)
assert.EqualValues(t, 51, maxIndex)
// larger index changes
err = db.SyncMaxResourceIndex(db.DefaultContext, "test_index", 10, 62)
err = db.SyncMaxResourceIndex(t.Context(), "test_index", 10, 62)
assert.NoError(t, err)
maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10)
maxIndex, err = getCurrentResourceIndex(t.Context(), "test_index", 10)
assert.NoError(t, err)
assert.EqualValues(t, 62, maxIndex)
// commit transaction
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
err = db.WithTx(t.Context(), func(ctx context.Context) error {
err = db.SyncMaxResourceIndex(ctx, "test_index", 10, 73)
assert.NoError(t, err)
maxIndex, err = getCurrentResourceIndex(ctx, "test_index", 10)
@@ -67,12 +67,12 @@ func TestSyncMaxResourceIndex(t *testing.T) {
return nil
})
assert.NoError(t, err)
maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10)
maxIndex, err = getCurrentResourceIndex(t.Context(), "test_index", 10)
assert.NoError(t, err)
assert.EqualValues(t, 73, maxIndex)
// rollback transaction
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
err = db.WithTx(t.Context(), func(ctx context.Context) error {
err = db.SyncMaxResourceIndex(ctx, "test_index", 10, 84)
maxIndex, err = getCurrentResourceIndex(ctx, "test_index", 10)
assert.NoError(t, err)
@@ -80,7 +80,7 @@ func TestSyncMaxResourceIndex(t *testing.T) {
return errors.New("test rollback")
})
assert.Error(t, err)
maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10)
maxIndex, err = getCurrentResourceIndex(t.Context(), "test_index", 10)
assert.NoError(t, err)
assert.EqualValues(t, 73, maxIndex) // the max index doesn't change because the transaction was rolled back
}
@@ -91,36 +91,36 @@ func TestGetNextResourceIndex(t *testing.T) {
assert.NoError(t, xe.Sync(&TestIndex{}))
// create a new record
maxIndex, err := db.GetNextResourceIndex(db.DefaultContext, "test_index", 20)
maxIndex, err := db.GetNextResourceIndex(t.Context(), "test_index", 20)
assert.NoError(t, err)
assert.EqualValues(t, 1, maxIndex)
// increase the existing record
maxIndex, err = db.GetNextResourceIndex(db.DefaultContext, "test_index", 20)
maxIndex, err = db.GetNextResourceIndex(t.Context(), "test_index", 20)
assert.NoError(t, err)
assert.EqualValues(t, 2, maxIndex)
// commit transaction
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
err = db.WithTx(t.Context(), func(ctx context.Context) error {
maxIndex, err = db.GetNextResourceIndex(ctx, "test_index", 20)
assert.NoError(t, err)
assert.EqualValues(t, 3, maxIndex)
return nil
})
assert.NoError(t, err)
maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 20)
maxIndex, err = getCurrentResourceIndex(t.Context(), "test_index", 20)
assert.NoError(t, err)
assert.EqualValues(t, 3, maxIndex)
// rollback transaction
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
err = db.WithTx(t.Context(), func(ctx context.Context) error {
maxIndex, err = db.GetNextResourceIndex(ctx, "test_index", 20)
assert.NoError(t, err)
assert.EqualValues(t, 4, maxIndex)
return errors.New("test rollback")
})
assert.Error(t, err)
maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 20)
maxIndex, err = getCurrentResourceIndex(t.Context(), "test_index", 20)
assert.NoError(t, err)
assert.EqualValues(t, 3, maxIndex) // the max index doesn't change because the transaction was rolled back
}

View File

@@ -4,27 +4,22 @@
package install
import (
"context"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
"xorm.io/xorm"
)
func getXORMEngine() *xorm.Engine {
return db.GetEngine(db.DefaultContext).(*xorm.Engine)
}
// CheckDatabaseConnection checks the database connection
func CheckDatabaseConnection() error {
e := db.GetEngine(db.DefaultContext)
_, err := e.Exec("SELECT 1")
func CheckDatabaseConnection(ctx context.Context) error {
_, err := db.GetEngine(ctx).Exec("SELECT 1")
return err
}
// GetMigrationVersion gets the database migration version
func GetMigrationVersion() (int64, error) {
func GetMigrationVersion(ctx context.Context) (int64, error) {
var installedDbVersion int64
x := getXORMEngine()
x := db.GetEngine(ctx)
exist, err := x.IsTableExist("version")
if err != nil {
return 0, err
@@ -40,8 +35,8 @@ func GetMigrationVersion() (int64, error) {
}
// HasPostInstallationUsers checks whether there are users after installation
func HasPostInstallationUsers() (bool, error) {
x := getXORMEngine()
func HasPostInstallationUsers(ctx context.Context) (bool, error) {
x := db.GetEngine(ctx)
exist, err := x.IsTableExist("user")
if err != nil {
return false, err

View File

@@ -19,18 +19,18 @@ func TestIterate(t *testing.T) {
xe := unittest.GetXORMEngine()
assert.NoError(t, xe.Sync(&repo_model.RepoUnit{}))
cnt, err := db.GetEngine(db.DefaultContext).Count(&repo_model.RepoUnit{})
cnt, err := db.GetEngine(t.Context()).Count(&repo_model.RepoUnit{})
assert.NoError(t, err)
var repoUnitCnt int
err = db.Iterate(db.DefaultContext, nil, func(ctx context.Context, repo *repo_model.RepoUnit) error {
err = db.Iterate(t.Context(), nil, func(ctx context.Context, repo *repo_model.RepoUnit) error {
repoUnitCnt++
return nil
})
assert.NoError(t, err)
assert.EqualValues(t, cnt, repoUnitCnt)
err = db.Iterate(db.DefaultContext, nil, func(ctx context.Context, repoUnit *repo_model.RepoUnit) error {
err = db.Iterate(t.Context(), nil, func(ctx context.Context, repoUnit *repo_model.RepoUnit) error {
has, err := db.ExistByID[repo_model.RepoUnit](ctx, repoUnit.ID)
if err != nil {
return err

View File

@@ -32,20 +32,20 @@ func TestFind(t *testing.T) {
assert.NoError(t, xe.Sync(&repo_model.RepoUnit{}))
var repoUnitCount int
_, err := db.GetEngine(db.DefaultContext).SQL("SELECT COUNT(*) FROM repo_unit").Get(&repoUnitCount)
_, err := db.GetEngine(t.Context()).SQL("SELECT COUNT(*) FROM repo_unit").Get(&repoUnitCount)
assert.NoError(t, err)
assert.NotEmpty(t, repoUnitCount)
opts := mockListOptions{}
repoUnits, err := db.Find[repo_model.RepoUnit](db.DefaultContext, opts)
repoUnits, err := db.Find[repo_model.RepoUnit](t.Context(), opts)
assert.NoError(t, err)
assert.Len(t, repoUnits, repoUnitCount)
cnt, err := db.Count[repo_model.RepoUnit](db.DefaultContext, opts)
cnt, err := db.Count[repo_model.RepoUnit](t.Context(), opts)
assert.NoError(t, err)
assert.EqualValues(t, repoUnitCount, cnt)
repoUnits, newCnt, err := db.FindAndCount[repo_model.RepoUnit](db.DefaultContext, opts)
repoUnits, newCnt, err := db.FindAndCount[repo_model.RepoUnit](t.Context(), opts)
assert.NoError(t, err)
assert.Equal(t, cnt, newCnt)
assert.Len(t, repoUnits, repoUnitCount)

View File

@@ -9,8 +9,6 @@ import (
"os"
"testing"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
)
@@ -26,7 +24,7 @@ func TestDbfsBasic(t *testing.T) {
defer changeDefaultFileBlockSize(4)()
// test basic write/read
f, err := OpenFile(db.DefaultContext, "test.txt", os.O_RDWR|os.O_CREATE)
f, err := OpenFile(t.Context(), "test.txt", os.O_RDWR|os.O_CREATE)
assert.NoError(t, err)
n, err := f.Write([]byte("0123456789")) // blocks: 0123 4567 89
@@ -95,25 +93,25 @@ func TestDbfsBasic(t *testing.T) {
assert.NoError(t, f.Close())
// test rename
err = Rename(db.DefaultContext, "test.txt", "test2.txt")
err = Rename(t.Context(), "test.txt", "test2.txt")
assert.NoError(t, err)
_, err = OpenFile(db.DefaultContext, "test.txt", os.O_RDONLY)
_, err = OpenFile(t.Context(), "test.txt", os.O_RDONLY)
assert.Error(t, err)
f, err = OpenFile(db.DefaultContext, "test2.txt", os.O_RDONLY)
f, err = OpenFile(t.Context(), "test2.txt", os.O_RDONLY)
assert.NoError(t, err)
assert.NoError(t, f.Close())
// test remove
err = Remove(db.DefaultContext, "test2.txt")
err = Remove(t.Context(), "test2.txt")
assert.NoError(t, err)
_, err = OpenFile(db.DefaultContext, "test2.txt", os.O_RDONLY)
_, err = OpenFile(t.Context(), "test2.txt", os.O_RDONLY)
assert.Error(t, err)
// test stat
f, err = OpenFile(db.DefaultContext, "test/test.txt", os.O_RDWR|os.O_CREATE)
f, err = OpenFile(t.Context(), "test/test.txt", os.O_RDWR|os.O_CREATE)
assert.NoError(t, err)
stat, err := f.Stat()
assert.NoError(t, err)
@@ -129,11 +127,11 @@ func TestDbfsBasic(t *testing.T) {
func TestDbfsReadWrite(t *testing.T) {
defer changeDefaultFileBlockSize(4)()
f1, err := OpenFile(db.DefaultContext, "test.log", os.O_RDWR|os.O_CREATE)
f1, err := OpenFile(t.Context(), "test.log", os.O_RDWR|os.O_CREATE)
assert.NoError(t, err)
defer f1.Close()
f2, err := OpenFile(db.DefaultContext, "test.log", os.O_RDONLY)
f2, err := OpenFile(t.Context(), "test.log", os.O_RDONLY)
assert.NoError(t, err)
defer f2.Close()
@@ -161,7 +159,7 @@ func TestDbfsReadWrite(t *testing.T) {
func TestDbfsSeekWrite(t *testing.T) {
defer changeDefaultFileBlockSize(4)()
f, err := OpenFile(db.DefaultContext, "test2.log", os.O_RDWR|os.O_CREATE)
f, err := OpenFile(t.Context(), "test2.log", os.O_RDWR|os.O_CREATE)
assert.NoError(t, err)
defer f.Close()
@@ -180,7 +178,7 @@ func TestDbfsSeekWrite(t *testing.T) {
_, err = f.Write([]byte("333"))
assert.NoError(t, err)
fr, err := OpenFile(db.DefaultContext, "test2.log", os.O_RDONLY)
fr, err := OpenFile(t.Context(), "test2.log", os.O_RDONLY)
assert.NoError(t, err)
defer f.Close()

View File

@@ -25,8 +25,8 @@ func TestAddDeletedBranch(t *testing.T) {
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1})
assert.True(t, firstBranch.IsDeleted)
assert.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, firstBranch.Name, firstBranch.DeletedByID))
assert.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, "branch2", int64(1)))
assert.NoError(t, git_model.AddDeletedBranch(t.Context(), repo.ID, firstBranch.Name, firstBranch.DeletedByID))
assert.NoError(t, git_model.AddDeletedBranch(t.Context(), repo.ID, "branch2", int64(1)))
secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: repo.ID, Name: "branch2"})
assert.True(t, secondBranch.IsDeleted)
@@ -39,7 +39,7 @@ func TestAddDeletedBranch(t *testing.T) {
},
}
_, err := git_model.UpdateBranch(db.DefaultContext, repo.ID, secondBranch.PusherID, secondBranch.Name, commit)
_, err := git_model.UpdateBranch(t.Context(), repo.ID, secondBranch.PusherID, secondBranch.Name, commit)
assert.NoError(t, err)
}
@@ -47,7 +47,7 @@ func TestGetDeletedBranches(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
branches, err := db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{
branches, err := db.Find[git_model.Branch](t.Context(), git_model.FindBranchOptions{
ListOptions: db.ListOptionsAll,
RepoID: repo.ID,
IsDeletedBranch: optional.Some(true),
@@ -71,13 +71,13 @@ func TestDeletedBranchLoadUser(t *testing.T) {
branch := getDeletedBranch(t, firstBranch)
assert.Nil(t, branch.DeletedBy)
branch.LoadDeletedBy(db.DefaultContext)
branch.LoadDeletedBy(t.Context())
assert.NotNil(t, branch.DeletedBy)
assert.Equal(t, "user1", branch.DeletedBy.Name)
branch = getDeletedBranch(t, secondBranch)
assert.Nil(t, branch.DeletedBy)
branch.LoadDeletedBy(db.DefaultContext)
branch.LoadDeletedBy(t.Context())
assert.NotNil(t, branch.DeletedBy)
assert.Equal(t, "Ghost", branch.DeletedBy.Name)
}
@@ -88,7 +88,7 @@ func TestRemoveDeletedBranch(t *testing.T) {
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1})
err := git_model.RemoveDeletedBranchByID(db.DefaultContext, repo.ID, 1)
err := git_model.RemoveDeletedBranchByID(t.Context(), repo.ID, 1)
assert.NoError(t, err)
unittest.AssertNotExistsBean(t, firstBranch)
unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 2})
@@ -97,7 +97,7 @@ func TestRemoveDeletedBranch(t *testing.T) {
func getDeletedBranch(t *testing.T, branch *git_model.Branch) *git_model.Branch {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
deletedBranch, err := git_model.GetDeletedBranchByID(db.DefaultContext, repo.ID, branch.ID)
deletedBranch, err := git_model.GetDeletedBranchByID(t.Context(), repo.ID, branch.ID)
assert.NoError(t, err)
assert.Equal(t, branch.ID, deletedBranch.ID)
assert.Equal(t, branch.Name, deletedBranch.Name)
@@ -109,12 +109,12 @@ func getDeletedBranch(t *testing.T, branch *git_model.Branch) *git_model.Branch
func TestFindRenamedBranch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
branch, exist, err := git_model.FindRenamedBranch(db.DefaultContext, 1, "dev")
branch, exist, err := git_model.FindRenamedBranch(t.Context(), 1, "dev")
assert.NoError(t, err)
assert.True(t, exist)
assert.Equal(t, "master", branch.To)
_, exist, err = git_model.FindRenamedBranch(db.DefaultContext, 1, "unknow")
_, exist, err = git_model.FindRenamedBranch(t.Context(), 1, "unknow")
assert.NoError(t, err)
assert.False(t, exist)
}
@@ -124,7 +124,7 @@ func TestRenameBranch(t *testing.T) {
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
_isDefault := false
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(t.Context())
defer committer.Close()
assert.NoError(t, err)
assert.NoError(t, git_model.UpdateProtectBranch(ctx, repo1, &git_model.ProtectedBranch{
@@ -133,7 +133,7 @@ func TestRenameBranch(t *testing.T) {
}, git_model.WhitelistOptions{}))
assert.NoError(t, committer.Commit())
assert.NoError(t, git_model.RenameBranch(db.DefaultContext, repo1, "master", "main", func(ctx context.Context, isDefault bool) error {
assert.NoError(t, git_model.RenameBranch(t.Context(), repo1, "master", "main", func(ctx context.Context, isDefault bool) error {
_isDefault = isDefault
return nil
}))
@@ -167,7 +167,7 @@ func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) {
// is actually on repo with ID 1.
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
deletedBranch, err := git_model.GetDeletedBranchByID(db.DefaultContext, repo2.ID, 1)
deletedBranch, err := git_model.GetDeletedBranchByID(t.Context(), repo2.ID, 1)
// Expect error, and the returned branch is nil.
assert.Error(t, err)
@@ -177,7 +177,7 @@ func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) {
// This should return the deletedBranch.
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
deletedBranch, err = git_model.GetDeletedBranchByID(db.DefaultContext, repo1.ID, 1)
deletedBranch, err = git_model.GetDeletedBranchByID(t.Context(), repo1.ID, 1)
// Expect no error, and the returned branch to be not nil.
assert.NoError(t, err)

View File

@@ -27,7 +27,7 @@ func TestGetCommitStatuses(t *testing.T) {
sha1 := "1234123412341234123412341234123412341234" // the mocked commit ID in test fixtures
statuses, maxResults, err := db.FindAndCount[git_model.CommitStatus](db.DefaultContext, &git_model.CommitStatusOptions{
statuses, maxResults, err := db.FindAndCount[git_model.CommitStatus](t.Context(), &git_model.CommitStatusOptions{
ListOptions: db.ListOptions{Page: 1, PageSize: 50},
RepoID: repo1.ID,
SHA: sha1,
@@ -38,25 +38,25 @@ func TestGetCommitStatuses(t *testing.T) {
assert.Equal(t, "ci/awesomeness", statuses[0].Context)
assert.Equal(t, commitstatus.CommitStatusPending, statuses[0].State)
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[0].APIURL(db.DefaultContext))
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[0].APIURL(t.Context()))
assert.Equal(t, "cov/awesomeness", statuses[1].Context)
assert.Equal(t, commitstatus.CommitStatusWarning, statuses[1].State)
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[1].APIURL(db.DefaultContext))
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[1].APIURL(t.Context()))
assert.Equal(t, "cov/awesomeness", statuses[2].Context)
assert.Equal(t, commitstatus.CommitStatusSuccess, statuses[2].State)
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[2].APIURL(db.DefaultContext))
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[2].APIURL(t.Context()))
assert.Equal(t, "ci/awesomeness", statuses[3].Context)
assert.Equal(t, commitstatus.CommitStatusFailure, statuses[3].State)
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[3].APIURL(db.DefaultContext))
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[3].APIURL(t.Context()))
assert.Equal(t, "deploy/awesomeness", statuses[4].Context)
assert.Equal(t, commitstatus.CommitStatusError, statuses[4].State)
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[4].APIURL(db.DefaultContext))
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/statuses/1234123412341234123412341234123412341234", statuses[4].APIURL(t.Context()))
statuses, maxResults, err = db.FindAndCount[git_model.CommitStatus](db.DefaultContext, &git_model.CommitStatusOptions{
statuses, maxResults, err = db.FindAndCount[git_model.CommitStatus](t.Context(), &git_model.CommitStatusOptions{
ListOptions: db.ListOptions{Page: 2, PageSize: 50},
RepoID: repo1.ID,
SHA: sha1,
@@ -194,7 +194,7 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
assert.NoError(t, err)
defer func() {
_, err := db.DeleteByBean(db.DefaultContext, &git_model.CommitStatus{
_, err := db.DeleteByBean(t.Context(), &git_model.CommitStatus{
RepoID: repo2.ID,
CreatorID: user2.ID,
SHA: commit.ID.String(),
@@ -202,7 +202,7 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
assert.NoError(t, err)
}()
err = git_model.NewCommitStatus(db.DefaultContext, git_model.NewCommitStatusOptions{
err = git_model.NewCommitStatus(t.Context(), git_model.NewCommitStatusOptions{
Repo: repo2,
Creator: user2,
SHA: commit.ID,
@@ -214,7 +214,7 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
})
assert.NoError(t, err)
err = git_model.NewCommitStatus(db.DefaultContext, git_model.NewCommitStatusOptions{
err = git_model.NewCommitStatus(t.Context(), git_model.NewCommitStatusOptions{
Repo: repo2,
Creator: user2,
SHA: commit.ID,
@@ -226,7 +226,7 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
})
assert.NoError(t, err)
contexts, err := git_model.FindRepoRecentCommitStatusContexts(db.DefaultContext, repo2.ID, time.Hour)
contexts, err := git_model.FindRepoRecentCommitStatusContexts(t.Context(), repo2.ID, time.Hour)
assert.NoError(t, err)
if assert.Len(t, contexts, 1) {
assert.Equal(t, "compliance/lint-backend", contexts[0])
@@ -238,7 +238,7 @@ func TestCommitStatusesHideActionsURL(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
run := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: 791, RepoID: repo.ID})
assert.NoError(t, run.LoadAttributes(db.DefaultContext))
assert.NoError(t, run.LoadAttributes(t.Context()))
statuses := []*git_model.CommitStatus{
{
@@ -251,7 +251,7 @@ func TestCommitStatusesHideActionsURL(t *testing.T) {
},
}
git_model.CommitStatusesHideActionsURL(db.DefaultContext, statuses)
git_model.CommitStatusesHideActionsURL(t.Context(), statuses)
assert.Empty(t, statuses[0].TargetURL)
assert.Equal(t, "https://mycicd.org/1", statuses[1].TargetURL)
}
@@ -263,7 +263,7 @@ func TestGetCountLatestCommitStatus(t *testing.T) {
sha1 := "1234123412341234123412341234123412341234" // the mocked commit ID in test fixtures
commitStatuses, err := git_model.GetLatestCommitStatus(db.DefaultContext, repo1.ID, sha1, db.ListOptions{
commitStatuses, err := git_model.GetLatestCommitStatus(t.Context(), repo1.ID, sha1, db.ListOptions{
Page: 1,
PageSize: 2,
})
@@ -274,7 +274,7 @@ func TestGetCountLatestCommitStatus(t *testing.T) {
assert.Equal(t, commitstatus.CommitStatusError, commitStatuses[1].State)
assert.Equal(t, "deploy/awesomeness", commitStatuses[1].Context)
count, err := git_model.CountLatestCommitStatus(db.DefaultContext, repo1.ID, sha1)
count, err := git_model.CountLatestCommitStatus(t.Context(), repo1.ID, sha1)
assert.NoError(t, err)
assert.EqualValues(t, 3, count)
}

View File

@@ -105,17 +105,17 @@ func TestUpdateProtectBranchPriorities(t *testing.T) {
}
for _, pb := range protectedBranches {
_, err := db.GetEngine(db.DefaultContext).Insert(pb)
_, err := db.GetEngine(t.Context()).Insert(pb)
assert.NoError(t, err)
}
// Test updating priorities
newPriorities := []int64{protectedBranches[2].ID, protectedBranches[0].ID, protectedBranches[1].ID}
err := UpdateProtectBranchPriorities(db.DefaultContext, repo, newPriorities)
err := UpdateProtectBranchPriorities(t.Context(), repo, newPriorities)
assert.NoError(t, err)
// Verify new priorities
pbs, err := FindRepoProtectedBranchRules(db.DefaultContext, repo.ID)
pbs, err := FindRepoProtectedBranchRules(t.Context(), repo.ID)
assert.NoError(t, err)
expectedPriorities := map[string]int64{
@@ -133,7 +133,7 @@ func TestNewProtectBranchPriority(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
err := UpdateProtectBranch(db.DefaultContext, repo, &ProtectedBranch{
err := UpdateProtectBranch(t.Context(), repo, &ProtectedBranch{
RepoID: repo.ID,
RuleName: "branch-1",
Priority: 1,
@@ -146,10 +146,10 @@ func TestNewProtectBranchPriority(t *testing.T) {
// Priority intentionally omitted
}
err = UpdateProtectBranch(db.DefaultContext, repo, newPB, WhitelistOptions{})
err = UpdateProtectBranch(t.Context(), repo, newPB, WhitelistOptions{})
assert.NoError(t, err)
savedPB2, err := GetFirstMatchProtectedBranchRule(db.DefaultContext, repo.ID, "branch-2")
savedPB2, err := GetFirstMatchProtectedBranchRule(t.Context(), repo.ID, "branch-2")
assert.NoError(t, err)
assert.Equal(t, int64(2), savedPB2.Priority)
}

View File

@@ -6,7 +6,6 @@ package git_test
import (
"testing"
"code.gitea.io/gitea/models/db"
git_model "code.gitea.io/gitea/models/git"
"code.gitea.io/gitea/models/unittest"
@@ -17,29 +16,29 @@ func TestIsUserAllowed(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pt := &git_model.ProtectedTag{}
allowed, err := git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
allowed, err := git_model.IsUserAllowedModifyTag(t.Context(), pt, 1)
assert.NoError(t, err)
assert.False(t, allowed)
pt = &git_model.ProtectedTag{
AllowlistUserIDs: []int64{1},
}
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 1)
assert.NoError(t, err)
assert.True(t, allowed)
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2)
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 2)
assert.NoError(t, err)
assert.False(t, allowed)
pt = &git_model.ProtectedTag{
AllowlistTeamIDs: []int64{1},
}
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 1)
assert.NoError(t, err)
assert.False(t, allowed)
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2)
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 2)
assert.NoError(t, err)
assert.True(t, allowed)
@@ -47,11 +46,11 @@ func TestIsUserAllowed(t *testing.T) {
AllowlistUserIDs: []int64{1},
AllowlistTeamIDs: []int64{1},
}
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 1)
assert.NoError(t, err)
assert.True(t, allowed)
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2)
allowed, err = git_model.IsUserAllowedModifyTag(t.Context(), pt, 2)
assert.NoError(t, err)
assert.True(t, allowed)
}
@@ -135,7 +134,7 @@ func TestIsUserAllowedToControlTag(t *testing.T) {
}
for n, c := range cases {
isAllowed, err := git_model.IsUserAllowedToControlTag(db.DefaultContext, protectedTags, c.name, c.userid)
isAllowed, err := git_model.IsUserAllowedToControlTag(t.Context(), protectedTags, c.name, c.userid)
assert.NoError(t, err)
assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n)
}
@@ -157,7 +156,7 @@ func TestIsUserAllowedToControlTag(t *testing.T) {
}
for n, c := range cases {
isAllowed, err := git_model.IsUserAllowedToControlTag(db.DefaultContext, protectedTags, c.name, c.userid)
isAllowed, err := git_model.IsUserAllowedToControlTag(t.Context(), protectedTags, c.name, c.userid)
assert.NoError(t, err)
assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n)
}

View File

@@ -6,7 +6,6 @@ package issues_test
import (
"testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -18,35 +17,35 @@ func TestUpdateAssignee(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
// Fake issue with assignees
issue, err := issues_model.GetIssueByID(db.DefaultContext, 1)
issue, err := issues_model.GetIssueByID(t.Context(), 1)
assert.NoError(t, err)
err = issue.LoadAttributes(db.DefaultContext)
err = issue.LoadAttributes(t.Context())
assert.NoError(t, err)
// Assign multiple users
user2, err := user_model.GetUserByID(db.DefaultContext, 2)
user2, err := user_model.GetUserByID(t.Context(), 2)
assert.NoError(t, err)
_, _, err = issues_model.ToggleIssueAssignee(db.DefaultContext, issue, &user_model.User{ID: 1}, user2.ID)
_, _, err = issues_model.ToggleIssueAssignee(t.Context(), issue, &user_model.User{ID: 1}, user2.ID)
assert.NoError(t, err)
org3, err := user_model.GetUserByID(db.DefaultContext, 3)
org3, err := user_model.GetUserByID(t.Context(), 3)
assert.NoError(t, err)
_, _, err = issues_model.ToggleIssueAssignee(db.DefaultContext, issue, &user_model.User{ID: 1}, org3.ID)
_, _, err = issues_model.ToggleIssueAssignee(t.Context(), issue, &user_model.User{ID: 1}, org3.ID)
assert.NoError(t, err)
user1, err := user_model.GetUserByID(db.DefaultContext, 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him
user1, err := user_model.GetUserByID(t.Context(), 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him
assert.NoError(t, err)
_, _, err = issues_model.ToggleIssueAssignee(db.DefaultContext, issue, &user_model.User{ID: 1}, user1.ID)
_, _, err = issues_model.ToggleIssueAssignee(t.Context(), issue, &user_model.User{ID: 1}, user1.ID)
assert.NoError(t, err)
// Check if he got removed
isAssigned, err := issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user1)
isAssigned, err := issues_model.IsUserAssignedToIssue(t.Context(), issue, user1)
assert.NoError(t, err)
assert.False(t, isAssigned)
// Check if they're all there
err = issue.LoadAssignees(db.DefaultContext)
err = issue.LoadAssignees(t.Context())
assert.NoError(t, err)
var expectedAssignees []*user_model.User
@@ -57,12 +56,12 @@ func TestUpdateAssignee(t *testing.T) {
}
// Check if the user is assigned
isAssigned, err = issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user2)
isAssigned, err = issues_model.IsUserAssignedToIssue(t.Context(), issue, user2)
assert.NoError(t, err)
assert.True(t, isAssigned)
// This user should not be assigned
isAssigned, err = issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, &user_model.User{ID: 4})
isAssigned, err = issues_model.IsUserAssignedToIssue(t.Context(), issue, &user_model.User{ID: 4})
assert.NoError(t, err)
assert.False(t, isAssigned)
}
@@ -73,22 +72,22 @@ func TestMakeIDsFromAPIAssigneesToAdd(t *testing.T) {
_ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
_ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
IDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{""})
IDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(t.Context(), "", []string{""})
assert.NoError(t, err)
assert.Equal(t, []int64{}, IDs)
_, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{"none_existing_user"})
_, err = issues_model.MakeIDsFromAPIAssigneesToAdd(t.Context(), "", []string{"none_existing_user"})
assert.Error(t, err)
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user1", []string{"user1"})
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(t.Context(), "user1", []string{"user1"})
assert.NoError(t, err)
assert.Equal(t, []int64{1}, IDs)
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user2", []string{""})
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(t.Context(), "user2", []string{""})
assert.NoError(t, err)
assert.Equal(t, []int64{2}, IDs)
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{"user1", "user2"})
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(t.Context(), "", []string{"user1", "user2"})
assert.NoError(t, err)
assert.Equal(t, []int64{1, 2}, IDs)
}

View File

@@ -24,7 +24,7 @@ func TestCreateComment(t *testing.T) {
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
now := time.Now().Unix()
comment, err := issues_model.CreateComment(db.DefaultContext, &issues_model.CreateCommentOptions{
comment, err := issues_model.CreateComment(t.Context(), &issues_model.CreateCommentOptions{
Type: issues_model.CommentTypeComment,
Doer: doer,
Repo: repo,
@@ -52,9 +52,9 @@ func Test_UpdateCommentAttachment(t *testing.T) {
attachment := repo_model.Attachment{
Name: "test.txt",
}
assert.NoError(t, db.Insert(db.DefaultContext, &attachment))
assert.NoError(t, db.Insert(t.Context(), &attachment))
err := issues_model.UpdateCommentAttachments(db.DefaultContext, comment, []string{attachment.UUID})
err := issues_model.UpdateCommentAttachments(t.Context(), comment, []string{attachment.UUID})
assert.NoError(t, err)
attachment2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Attachment{ID: attachment.ID})
@@ -68,7 +68,7 @@ func TestFetchCodeComments(t *testing.T) {
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
res, err := issues_model.FetchCodeComments(db.DefaultContext, issue, user, false)
res, err := issues_model.FetchCodeComments(t.Context(), issue, user, false)
assert.NoError(t, err)
assert.Contains(t, res, "README.md")
assert.Contains(t, res["README.md"], int64(4))
@@ -76,7 +76,7 @@ func TestFetchCodeComments(t *testing.T) {
assert.Equal(t, int64(4), res["README.md"][4][0].ID)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
res, err = issues_model.FetchCodeComments(db.DefaultContext, issue, user2, false)
res, err = issues_model.FetchCodeComments(t.Context(), issue, user2, false)
assert.NoError(t, err)
assert.Len(t, res, 1)
}
@@ -92,7 +92,7 @@ func TestAsCommentType(t *testing.T) {
func TestMigrate_InsertIssueComments(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
_ = issue.LoadRepo(db.DefaultContext)
_ = issue.LoadRepo(t.Context())
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID})
reaction := &issues_model.Reaction{
Type: "heart",
@@ -107,7 +107,7 @@ func TestMigrate_InsertIssueComments(t *testing.T) {
Reactions: []*issues_model.Reaction{reaction},
}
err := issues_model.InsertIssueComments(db.DefaultContext, []*issues_model.Comment{comment})
err := issues_model.InsertIssueComments(t.Context(), []*issues_model.Comment{comment})
assert.NoError(t, err)
issueModified := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
@@ -120,7 +120,7 @@ func Test_UpdateIssueNumComments(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
assert.NoError(t, issues_model.UpdateIssueNumComments(db.DefaultContext, issue2.ID))
assert.NoError(t, issues_model.UpdateIssueNumComments(t.Context(), issue2.ID))
issue2 = unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
assert.Equal(t, 1, issue2.NumComments)
}

View File

@@ -17,7 +17,7 @@ import (
func TestContentHistory(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
dbCtx := db.DefaultContext
dbCtx := t.Context()
timeStampNow := timeutil.TimeStampNow()
_ = issues_model.SaveIssueContentHistory(dbCtx, 1, 10, 0, timeStampNow, "i-a", true)
@@ -82,18 +82,18 @@ func TestContentHistory(t *testing.T) {
func TestHasIssueContentHistoryForCommentOnly(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
_ = db.TruncateBeans(db.DefaultContext, &issues_model.ContentHistory{})
_ = db.TruncateBeans(t.Context(), &issues_model.ContentHistory{})
hasHistory1, _ := issues_model.HasIssueContentHistory(db.DefaultContext, 10, 0)
hasHistory1, _ := issues_model.HasIssueContentHistory(t.Context(), 10, 0)
assert.False(t, hasHistory1)
hasHistory2, _ := issues_model.HasIssueContentHistory(db.DefaultContext, 10, 100)
hasHistory2, _ := issues_model.HasIssueContentHistory(t.Context(), 10, 100)
assert.False(t, hasHistory2)
_ = issues_model.SaveIssueContentHistory(db.DefaultContext, 1, 10, 100, timeutil.TimeStampNow(), "c-a", true)
_ = issues_model.SaveIssueContentHistory(db.DefaultContext, 1, 10, 100, timeutil.TimeStampNow().Add(5), "c-b", false)
_ = issues_model.SaveIssueContentHistory(t.Context(), 1, 10, 100, timeutil.TimeStampNow(), "c-a", true)
_ = issues_model.SaveIssueContentHistory(t.Context(), 1, 10, 100, timeutil.TimeStampNow().Add(5), "c-b", false)
hasHistory1, _ = issues_model.HasIssueContentHistory(db.DefaultContext, 10, 0)
hasHistory1, _ = issues_model.HasIssueContentHistory(t.Context(), 10, 0)
assert.False(t, hasHistory1)
hasHistory2, _ = issues_model.HasIssueContentHistory(db.DefaultContext, 10, 100)
hasHistory2, _ = issues_model.HasIssueContentHistory(t.Context(), 10, 100)
assert.True(t, hasHistory2)
}

View File

@@ -6,7 +6,6 @@ package issues_test
import (
"testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -18,56 +17,56 @@ func TestCreateIssueDependency(t *testing.T) {
// Prepare
assert.NoError(t, unittest.PrepareTestDatabase())
user1, err := user_model.GetUserByID(db.DefaultContext, 1)
user1, err := user_model.GetUserByID(t.Context(), 1)
assert.NoError(t, err)
issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1)
issue1, err := issues_model.GetIssueByID(t.Context(), 1)
assert.NoError(t, err)
issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2)
issue2, err := issues_model.GetIssueByID(t.Context(), 2)
assert.NoError(t, err)
// Create a dependency and check if it was successful
err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2)
err = issues_model.CreateIssueDependency(t.Context(), user1, issue1, issue2)
assert.NoError(t, err)
// Do it again to see if it will check if the dependency already exists
err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2)
err = issues_model.CreateIssueDependency(t.Context(), user1, issue1, issue2)
assert.Error(t, err)
assert.True(t, issues_model.IsErrDependencyExists(err))
// Check for circular dependencies
err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue2, issue1)
err = issues_model.CreateIssueDependency(t.Context(), user1, issue2, issue1)
assert.Error(t, err)
assert.True(t, issues_model.IsErrCircularDependency(err))
_ = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{Type: issues_model.CommentTypeAddDependency, PosterID: user1.ID, IssueID: issue1.ID})
// Check if dependencies left is correct
left, err := issues_model.IssueNoDependenciesLeft(db.DefaultContext, issue1)
left, err := issues_model.IssueNoDependenciesLeft(t.Context(), issue1)
assert.NoError(t, err)
assert.False(t, left)
// Close #2 and check again
_, err = issues_model.CloseIssue(db.DefaultContext, issue2, user1)
_, err = issues_model.CloseIssue(t.Context(), issue2, user1)
assert.NoError(t, err)
issue2Closed, err := issues_model.GetIssueByID(db.DefaultContext, 2)
issue2Closed, err := issues_model.GetIssueByID(t.Context(), 2)
assert.NoError(t, err)
assert.True(t, issue2Closed.IsClosed)
left, err = issues_model.IssueNoDependenciesLeft(db.DefaultContext, issue1)
left, err = issues_model.IssueNoDependenciesLeft(t.Context(), issue1)
assert.NoError(t, err)
assert.True(t, left)
// Test removing the dependency
err = issues_model.RemoveIssueDependency(db.DefaultContext, user1, issue1, issue2, issues_model.DependencyTypeBlockedBy)
err = issues_model.RemoveIssueDependency(t.Context(), user1, issue1, issue2, issues_model.DependencyTypeBlockedBy)
assert.NoError(t, err)
_, err = issues_model.ReopenIssue(db.DefaultContext, issue2, user1)
_, err = issues_model.ReopenIssue(t.Context(), issue2, user1)
assert.NoError(t, err)
issue2Reopened, err := issues_model.GetIssueByID(db.DefaultContext, 2)
issue2Reopened, err := issues_model.GetIssueByID(t.Context(), 2)
assert.NoError(t, err)
assert.False(t, issue2Reopened.IsClosed)
}

View File

@@ -6,7 +6,6 @@ package issues_test
import (
"testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -22,7 +21,7 @@ func TestNewIssueLabelsScope(t *testing.T) {
label2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{label1, label2}, doer))
assert.NoError(t, issues_model.NewIssueLabels(t.Context(), issue, []*issues_model.Label{label1, label2}, doer))
assert.Len(t, issue.Labels, 1)
assert.Equal(t, label2.ID, issue.Labels[0].ID)

View File

@@ -6,7 +6,6 @@ package issues_test
import (
"testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
@@ -23,7 +22,7 @@ func TestIssueList_LoadRepositories(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}),
}
repos, err := issueList.LoadRepositories(db.DefaultContext)
repos, err := issueList.LoadRepositories(t.Context())
assert.NoError(t, err)
assert.Len(t, repos, 2)
for _, issue := range issueList {
@@ -39,7 +38,7 @@ func TestIssueList_LoadAttributes(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}),
}
assert.NoError(t, issueList.LoadAttributes(db.DefaultContext))
assert.NoError(t, issueList.LoadAttributes(t.Context()))
for _, issue := range issueList {
assert.Equal(t, issue.RepoID, issue.Repo.ID)
for _, label := range issue.Labels {

View File

@@ -34,7 +34,7 @@ func TestIssue_ReplaceLabels(t *testing.T) {
for i, labelID := range labelIDs {
labels[i] = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID, RepoID: repo.ID})
}
assert.NoError(t, issues_model.ReplaceIssueLabels(db.DefaultContext, issue, labels, doer))
assert.NoError(t, issues_model.ReplaceIssueLabels(t.Context(), issue, labels, doer))
unittest.AssertCount(t, &issues_model.IssueLabel{IssueID: issueID}, len(expectedLabelIDs))
for _, labelID := range expectedLabelIDs {
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issueID, LabelID: labelID})
@@ -54,7 +54,7 @@ func TestIssue_ReplaceLabels(t *testing.T) {
func Test_GetIssueIDsByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ids, err := issues_model.GetIssueIDsByRepoID(db.DefaultContext, 1)
ids, err := issues_model.GetIssueIDsByRepoID(t.Context(), 1)
assert.NoError(t, err)
assert.Len(t, ids, 5)
}
@@ -62,16 +62,16 @@ func Test_GetIssueIDsByRepoID(t *testing.T) {
func TestIssueAPIURL(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
err := issue.LoadAttributes(db.DefaultContext)
err := issue.LoadAttributes(t.Context())
assert.NoError(t, err)
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/issues/1", issue.APIURL(db.DefaultContext))
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/issues/1", issue.APIURL(t.Context()))
}
func TestGetIssuesByIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(expectedIssueIDs, nonExistentIssueIDs []int64) {
issues, err := issues_model.GetIssuesByIDs(db.DefaultContext, append(expectedIssueIDs, nonExistentIssueIDs...), true)
issues, err := issues_model.GetIssuesByIDs(t.Context(), append(expectedIssueIDs, nonExistentIssueIDs...), true)
assert.NoError(t, err)
actualIssueIDs := make([]int64, len(issues))
for i, issue := range issues {
@@ -88,9 +88,9 @@ func TestGetParticipantIDsByIssue(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
checkParticipants := func(issueID int64, userIDs []int) {
issue, err := issues_model.GetIssueByID(db.DefaultContext, issueID)
issue, err := issues_model.GetIssueByID(t.Context(), issueID)
assert.NoError(t, err)
participants, err := issue.GetParticipantIDsByIssue(db.DefaultContext)
participants, err := issue.GetParticipantIDsByIssue(t.Context())
if assert.NoError(t, err) {
participantsIDs := make([]int, len(participants))
for i, uid := range participants {
@@ -122,7 +122,7 @@ func TestIssue_ClearLabels(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID})
assert.NoError(t, issues_model.ClearIssueLabels(db.DefaultContext, issue, doer))
assert.NoError(t, issues_model.ClearIssueLabels(t.Context(), issue, doer))
unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: test.issueID})
}
}
@@ -138,7 +138,7 @@ func TestUpdateIssueCols(t *testing.T) {
issue.Content = "This should have no effect"
now := time.Now().Unix()
assert.NoError(t, issues_model.UpdateIssueCols(db.DefaultContext, issue, "name"))
assert.NoError(t, issues_model.UpdateIssueCols(t.Context(), issue, "name"))
then := time.Now().Unix()
updatedIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issue.ID})
@@ -198,7 +198,7 @@ func TestIssues(t *testing.T) {
[]int64{2},
},
} {
issues, err := issues_model.Issues(db.DefaultContext, &test.Opts)
issues, err := issues_model.Issues(t.Context(), &test.Opts)
assert.NoError(t, err)
if assert.Len(t, issues, len(test.ExpectedIssueIDs)) {
for i, issue := range issues {
@@ -210,9 +210,9 @@ func TestIssues(t *testing.T) {
func TestIssue_loadTotalTimes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ms, err := issues_model.GetIssueByID(db.DefaultContext, 2)
ms, err := issues_model.GetIssueByID(t.Context(), 2)
assert.NoError(t, err)
assert.NoError(t, ms.LoadTotalTimes(db.DefaultContext))
assert.NoError(t, ms.LoadTotalTimes(t.Context()))
assert.Equal(t, int64(3682), ms.TotalTrackedTime)
}
@@ -229,10 +229,10 @@ func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *is
Title: title,
Content: content,
}
err := issues_model.NewIssue(db.DefaultContext, repo, &issue, nil, nil)
err := issues_model.NewIssue(t.Context(), repo, &issue, nil, nil)
assert.NoError(t, err)
has, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Get(&newIssue)
has, err := db.GetEngine(t.Context()).ID(issue.ID).Get(&newIssue)
assert.NoError(t, err)
assert.True(t, has)
assert.Equal(t, issue.Title, newIssue.Title)
@@ -249,11 +249,11 @@ func TestIssue_InsertIssue(t *testing.T) {
// there are 5 issues and max index is 5 on repository 1, so this one should 6
issue := testInsertIssue(t, "my issue1", "special issue's comments?", 6)
_, err := db.DeleteByID[issues_model.Issue](db.DefaultContext, issue.ID)
_, err := db.DeleteByID[issues_model.Issue](t.Context(), issue.ID)
assert.NoError(t, err)
issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7)
_, err = db.DeleteByID[issues_model.Issue](db.DefaultContext, issue.ID)
_, err = db.DeleteByID[issues_model.Issue](t.Context(), issue.ID)
assert.NoError(t, err)
}
@@ -265,7 +265,7 @@ func TestIssue_ResolveMentions(t *testing.T) {
r := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: o.ID, LowerName: repo})
issue := &issues_model.Issue{RepoID: r.ID}
d := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: doer})
resolved, err := issues_model.ResolveIssueMentionsByVisibility(db.DefaultContext, issue, d, mentions)
resolved, err := issues_model.ResolveIssueMentionsByVisibility(t.Context(), issue, d, mentions)
assert.NoError(t, err)
ids := make([]int64, len(resolved))
for i, user := range resolved {
@@ -345,7 +345,7 @@ func TestCorrectIssueStats(t *testing.T) {
// Now we will call the GetIssueStats with these IDs and if working,
// get the correct stats back.
issueStats, err := issues_model.GetIssueStats(db.DefaultContext, &issues_model.IssuesOptions{
issueStats, err := issues_model.GetIssueStats(t.Context(), &issues_model.IssuesOptions{
RepoIDs: []int64{1},
IssueIDs: ids,
})
@@ -361,7 +361,7 @@ func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}),
}
assert.NoError(t, miles.LoadTotalTrackedTimes(db.DefaultContext))
assert.NoError(t, miles.LoadTotalTrackedTimes(t.Context()))
assert.Equal(t, int64(3682), miles[0].TotalTrackedTime)
}
@@ -370,14 +370,14 @@ func TestLoadTotalTrackedTime(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1})
assert.NoError(t, milestone.LoadTotalTrackedTime(db.DefaultContext))
assert.NoError(t, milestone.LoadTotalTrackedTime(t.Context()))
assert.Equal(t, int64(3682), milestone.TotalTrackedTime)
}
func TestCountIssues(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
count, err := issues_model.CountIssues(db.DefaultContext, &issues_model.IssuesOptions{})
count, err := issues_model.CountIssues(t.Context(), &issues_model.IssuesOptions{})
assert.NoError(t, err)
assert.EqualValues(t, 22, count)
}
@@ -392,7 +392,7 @@ func TestIssueLoadAttributes(t *testing.T) {
}
for _, issue := range issueList {
assert.NoError(t, issue.LoadAttributes(db.DefaultContext))
assert.NoError(t, issue.LoadAttributes(t.Context()))
assert.Equal(t, issue.RepoID, issue.Repo.ID)
for _, label := range issue.Labels {
assert.Equal(t, issue.RepoID, label.RepoID)
@@ -453,7 +453,7 @@ func assertCreateIssues(t *testing.T, isPull bool) {
Labels: []*issues_model.Label{label},
Reactions: []*issues_model.Reaction{reaction},
}
err := issues_model.InsertIssues(db.DefaultContext, is)
err := issues_model.InsertIssues(t.Context(), is)
assert.NoError(t, err)
i := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: title})

View File

@@ -28,8 +28,8 @@ func Test_NewIssueUsers(t *testing.T) {
}
// artificially insert new issue
require.NoError(t, db.Insert(db.DefaultContext, newIssue))
require.NoError(t, issues_model.NewIssueUsers(db.DefaultContext, repo, newIssue))
require.NoError(t, db.Insert(t.Context(), newIssue))
require.NoError(t, issues_model.NewIssueUsers(t.Context(), repo, newIssue))
// issue_user table should now have entries for new issue
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID})
@@ -40,13 +40,13 @@ func TestUpdateIssueUserByRead(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
assert.NoError(t, issues_model.UpdateIssueUserByRead(db.DefaultContext, 4, issue.ID))
assert.NoError(t, issues_model.UpdateIssueUserByRead(t.Context(), 4, issue.ID))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1")
assert.NoError(t, issues_model.UpdateIssueUserByRead(db.DefaultContext, 4, issue.ID))
assert.NoError(t, issues_model.UpdateIssueUserByRead(t.Context(), 4, issue.ID))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1")
assert.NoError(t, issues_model.UpdateIssueUserByRead(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID))
assert.NoError(t, issues_model.UpdateIssueUserByRead(t.Context(), unittest.NonexistentID, unittest.NonexistentID))
}
func TestUpdateIssueUsersByMentions(t *testing.T) {
@@ -54,7 +54,7 @@ func TestUpdateIssueUsersByMentions(t *testing.T) {
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
uids := []int64{2, 5}
assert.NoError(t, issues_model.UpdateIssueUsersByMentions(db.DefaultContext, issue.ID, uids))
assert.NoError(t, issues_model.UpdateIssueUsersByMentions(t.Context(), issue.ID, uids))
for _, uid := range uids {
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1")
}

View File

@@ -16,11 +16,11 @@ import (
func TestCreateOrUpdateIssueWatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(db.DefaultContext, 3, 1, true))
assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(t.Context(), 3, 1, true))
iw := unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 3, IssueID: 1})
assert.True(t, iw.IsWatching)
assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(db.DefaultContext, 1, 1, false))
assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(t.Context(), 1, 1, false))
iw = unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 1, IssueID: 1})
assert.False(t, iw.IsWatching)
}
@@ -28,16 +28,16 @@ func TestCreateOrUpdateIssueWatch(t *testing.T) {
func TestGetIssueWatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
_, exists, err := issues_model.GetIssueWatch(db.DefaultContext, 9, 1)
_, exists, err := issues_model.GetIssueWatch(t.Context(), 9, 1)
assert.True(t, exists)
assert.NoError(t, err)
iw, exists, err := issues_model.GetIssueWatch(db.DefaultContext, 2, 2)
iw, exists, err := issues_model.GetIssueWatch(t.Context(), 2, 2)
assert.True(t, exists)
assert.NoError(t, err)
assert.False(t, iw.IsWatching)
_, exists, err = issues_model.GetIssueWatch(db.DefaultContext, 3, 1)
_, exists, err = issues_model.GetIssueWatch(t.Context(), 3, 1)
assert.False(t, exists)
assert.NoError(t, err)
}
@@ -45,22 +45,22 @@ func TestGetIssueWatch(t *testing.T) {
func TestGetIssueWatchers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
iws, err := issues_model.GetIssueWatchers(db.DefaultContext, 1, db.ListOptions{})
iws, err := issues_model.GetIssueWatchers(t.Context(), 1, db.ListOptions{})
assert.NoError(t, err)
// Watcher is inactive, thus 0
assert.Empty(t, iws)
iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 2, db.ListOptions{})
iws, err = issues_model.GetIssueWatchers(t.Context(), 2, db.ListOptions{})
assert.NoError(t, err)
// Watcher is explicit not watching
assert.Empty(t, iws)
iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 5, db.ListOptions{})
iws, err = issues_model.GetIssueWatchers(t.Context(), 5, db.ListOptions{})
assert.NoError(t, err)
// Issue has no Watchers
assert.Empty(t, iws)
iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 7, db.ListOptions{})
iws, err = issues_model.GetIssueWatchers(t.Context(), 7, db.ListOptions{})
assert.NoError(t, err)
// Issue has one watcher
assert.Len(t, iws, 1)

View File

@@ -83,7 +83,7 @@ func TestXRef_NeuterCrossReferences(t *testing.T) {
d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
i.Title = "title2, no mentions"
assert.NoError(t, issues_model.ChangeIssueTitle(db.DefaultContext, i, d, title))
assert.NoError(t, issues_model.ChangeIssueTitle(t.Context(), i, d, title))
ref = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0})
assert.Equal(t, issues_model.CommentTypeIssueRef, ref.Type)
@@ -98,7 +98,7 @@ func TestXRef_ResolveCrossReferences(t *testing.T) {
i1 := testCreateIssue(t, 1, 2, "title1", "content1", false)
i2 := testCreateIssue(t, 1, 2, "title2", "content2", false)
i3 := testCreateIssue(t, 1, 2, "title3", "content3", false)
_, err := issues_model.CloseIssue(db.DefaultContext, i3, d)
_, err := issues_model.CloseIssue(t.Context(), i3, d)
assert.NoError(t, err)
pr := testCreatePR(t, 1, 2, "titlepr", fmt.Sprintf("closes #%d", i1.Index))
@@ -118,7 +118,7 @@ func TestXRef_ResolveCrossReferences(t *testing.T) {
c4 := testCreateComment(t, 2, pr.Issue.ID, fmt.Sprintf("closes #%d", i3.Index))
r4 := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{IssueID: i3.ID, RefIssueID: pr.Issue.ID, RefCommentID: c4.ID})
refs, err := pr.ResolveCrossReferences(db.DefaultContext)
refs, err := pr.ResolveCrossReferences(t.Context())
assert.NoError(t, err)
assert.Len(t, refs, 3)
assert.Equal(t, rp.ID, refs[0].ID, "bad ref rp: %+v", refs[0])
@@ -130,7 +130,7 @@ func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispu
r := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo})
d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer})
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(t.Context())
assert.NoError(t, err)
defer committer.Close()
@@ -163,7 +163,7 @@ func testCreatePR(t *testing.T, repo, doer int64, title, content string) *issues
d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer})
i := &issues_model.Issue{RepoID: r.ID, PosterID: d.ID, Poster: d, Title: title, Content: content, IsPull: true}
pr := &issues_model.PullRequest{HeadRepoID: repo, BaseRepoID: repo, HeadBranch: "head", BaseBranch: "base", Status: issues_model.PullRequestStatusMergeable}
assert.NoError(t, issues_model.NewPullRequest(db.DefaultContext, r, i, nil, nil, pr))
assert.NoError(t, issues_model.NewPullRequest(t.Context(), r, i, nil, nil, pr))
pr.Issue = i
return pr
}
@@ -173,7 +173,7 @@ func testCreateComment(t *testing.T, doer, issue int64, content string) *issues_
i := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issue})
c := &issues_model.Comment{Type: issues_model.CommentTypeComment, PosterID: doer, Poster: d, IssueID: issue, Issue: i, Content: content}
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(t.Context())
assert.NoError(t, err)
defer committer.Close()
err = db.Insert(ctx, c)

View File

@@ -61,15 +61,15 @@ func TestNewLabels(t *testing.T) {
{RepoID: 4, Name: "labelName4", Color: "ABCDEF"},
{RepoID: 5, Name: "labelName5", Color: "DEF"},
}
assert.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: ""}))
assert.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "#45G"}))
assert.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "#12345G"}))
assert.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "45G"}))
assert.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "12345G"}))
assert.Error(t, issues_model.NewLabel(t.Context(), &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: ""}))
assert.Error(t, issues_model.NewLabel(t.Context(), &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "#45G"}))
assert.Error(t, issues_model.NewLabel(t.Context(), &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "#12345G"}))
assert.Error(t, issues_model.NewLabel(t.Context(), &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "45G"}))
assert.Error(t, issues_model.NewLabel(t.Context(), &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "12345G"}))
for _, label := range labels {
unittest.AssertNotExistsBean(t, label)
}
assert.NoError(t, issues_model.NewLabels(db.DefaultContext, labels...))
assert.NoError(t, issues_model.NewLabels(t.Context(), labels...))
for _, label := range labels {
unittest.AssertExistsAndLoadBean(t, label, unittest.Cond("id = ?", label.ID))
}
@@ -78,31 +78,31 @@ func TestNewLabels(t *testing.T) {
func TestGetLabelByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
label, err := issues_model.GetLabelByID(db.DefaultContext, 1)
label, err := issues_model.GetLabelByID(t.Context(), 1)
assert.NoError(t, err)
assert.EqualValues(t, 1, label.ID)
_, err = issues_model.GetLabelByID(db.DefaultContext, unittest.NonexistentID)
_, err = issues_model.GetLabelByID(t.Context(), unittest.NonexistentID)
assert.True(t, issues_model.IsErrLabelNotExist(err))
}
func TestGetLabelInRepoByName(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
label, err := issues_model.GetLabelInRepoByName(db.DefaultContext, 1, "label1")
label, err := issues_model.GetLabelInRepoByName(t.Context(), 1, "label1")
assert.NoError(t, err)
assert.EqualValues(t, 1, label.ID)
assert.Equal(t, "label1", label.Name)
_, err = issues_model.GetLabelInRepoByName(db.DefaultContext, 1, "")
_, err = issues_model.GetLabelInRepoByName(t.Context(), 1, "")
assert.True(t, issues_model.IsErrRepoLabelNotExist(err))
_, err = issues_model.GetLabelInRepoByName(db.DefaultContext, unittest.NonexistentID, "nonexistent")
_, err = issues_model.GetLabelInRepoByName(t.Context(), unittest.NonexistentID, "nonexistent")
assert.True(t, issues_model.IsErrRepoLabelNotExist(err))
}
func TestGetLabelInRepoByNames(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
labelIDs, err := issues_model.GetLabelIDsInRepoByNames(db.DefaultContext, 1, []string{"label1", "label2"})
labelIDs, err := issues_model.GetLabelIDsInRepoByNames(t.Context(), 1, []string{"label1", "label2"})
assert.NoError(t, err)
assert.Len(t, labelIDs, 2)
@@ -114,7 +114,7 @@ func TestGetLabelInRepoByNames(t *testing.T) {
func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
// label3 doesn't exists.. See labels.yml
labelIDs, err := issues_model.GetLabelIDsInRepoByNames(db.DefaultContext, 1, []string{"label1", "label2", "label3"})
labelIDs, err := issues_model.GetLabelIDsInRepoByNames(t.Context(), 1, []string{"label1", "label2", "label3"})
assert.NoError(t, err)
assert.Len(t, labelIDs, 2)
@@ -126,20 +126,20 @@ func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) {
func TestGetLabelInRepoByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
label, err := issues_model.GetLabelInRepoByID(db.DefaultContext, 1, 1)
label, err := issues_model.GetLabelInRepoByID(t.Context(), 1, 1)
assert.NoError(t, err)
assert.EqualValues(t, 1, label.ID)
_, err = issues_model.GetLabelInRepoByID(db.DefaultContext, 1, -1)
_, err = issues_model.GetLabelInRepoByID(t.Context(), 1, -1)
assert.True(t, issues_model.IsErrRepoLabelNotExist(err))
_, err = issues_model.GetLabelInRepoByID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)
_, err = issues_model.GetLabelInRepoByID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
assert.True(t, issues_model.IsErrRepoLabelNotExist(err))
}
func TestGetLabelsInRepoByIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
labels, err := issues_model.GetLabelsInRepoByIDs(db.DefaultContext, 1, []int64{1, 2, unittest.NonexistentID})
labels, err := issues_model.GetLabelsInRepoByIDs(t.Context(), 1, []int64{1, 2, unittest.NonexistentID})
assert.NoError(t, err)
if assert.Len(t, labels, 2) {
assert.EqualValues(t, 1, labels[0].ID)
@@ -150,7 +150,7 @@ func TestGetLabelsInRepoByIDs(t *testing.T) {
func TestGetLabelsByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) {
labels, err := issues_model.GetLabelsByRepoID(db.DefaultContext, repoID, sortType, db.ListOptions{})
labels, err := issues_model.GetLabelsByRepoID(t.Context(), repoID, sortType, db.ListOptions{})
assert.NoError(t, err)
assert.Len(t, labels, len(expectedIssueIDs))
for i, label := range labels {
@@ -167,46 +167,46 @@ func TestGetLabelsByRepoID(t *testing.T) {
func TestGetLabelInOrgByName(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
label, err := issues_model.GetLabelInOrgByName(db.DefaultContext, 3, "orglabel3")
label, err := issues_model.GetLabelInOrgByName(t.Context(), 3, "orglabel3")
assert.NoError(t, err)
assert.EqualValues(t, 3, label.ID)
assert.Equal(t, "orglabel3", label.Name)
_, err = issues_model.GetLabelInOrgByName(db.DefaultContext, 3, "")
_, err = issues_model.GetLabelInOrgByName(t.Context(), 3, "")
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
_, err = issues_model.GetLabelInOrgByName(db.DefaultContext, 0, "orglabel3")
_, err = issues_model.GetLabelInOrgByName(t.Context(), 0, "orglabel3")
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
_, err = issues_model.GetLabelInOrgByName(db.DefaultContext, -1, "orglabel3")
_, err = issues_model.GetLabelInOrgByName(t.Context(), -1, "orglabel3")
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
_, err = issues_model.GetLabelInOrgByName(db.DefaultContext, unittest.NonexistentID, "nonexistent")
_, err = issues_model.GetLabelInOrgByName(t.Context(), unittest.NonexistentID, "nonexistent")
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
}
func TestGetLabelInOrgByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
label, err := issues_model.GetLabelInOrgByID(db.DefaultContext, 3, 3)
label, err := issues_model.GetLabelInOrgByID(t.Context(), 3, 3)
assert.NoError(t, err)
assert.EqualValues(t, 3, label.ID)
_, err = issues_model.GetLabelInOrgByID(db.DefaultContext, 3, -1)
_, err = issues_model.GetLabelInOrgByID(t.Context(), 3, -1)
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
_, err = issues_model.GetLabelInOrgByID(db.DefaultContext, 0, 3)
_, err = issues_model.GetLabelInOrgByID(t.Context(), 0, 3)
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
_, err = issues_model.GetLabelInOrgByID(db.DefaultContext, -1, 3)
_, err = issues_model.GetLabelInOrgByID(t.Context(), -1, 3)
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
_, err = issues_model.GetLabelInOrgByID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)
_, err = issues_model.GetLabelInOrgByID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
}
func TestGetLabelsInOrgByIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
labels, err := issues_model.GetLabelsInOrgByIDs(db.DefaultContext, 3, []int64{3, 4, unittest.NonexistentID})
labels, err := issues_model.GetLabelsInOrgByIDs(t.Context(), 3, []int64{3, 4, unittest.NonexistentID})
assert.NoError(t, err)
if assert.Len(t, labels, 2) {
assert.EqualValues(t, 3, labels[0].ID)
@@ -217,7 +217,7 @@ func TestGetLabelsInOrgByIDs(t *testing.T) {
func TestGetLabelsByOrgID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) {
labels, err := issues_model.GetLabelsByOrgID(db.DefaultContext, orgID, sortType, db.ListOptions{})
labels, err := issues_model.GetLabelsByOrgID(t.Context(), orgID, sortType, db.ListOptions{})
assert.NoError(t, err)
assert.Len(t, labels, len(expectedIssueIDs))
for i, label := range labels {
@@ -229,10 +229,10 @@ func TestGetLabelsByOrgID(t *testing.T) {
testSuccess(3, "reversealphabetically", []int64{4, 3})
testSuccess(3, "default", []int64{3, 4})
_, err := issues_model.GetLabelsByOrgID(db.DefaultContext, 0, "leastissues", db.ListOptions{})
_, err := issues_model.GetLabelsByOrgID(t.Context(), 0, "leastissues", db.ListOptions{})
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
_, err = issues_model.GetLabelsByOrgID(db.DefaultContext, -1, "leastissues", db.ListOptions{})
_, err = issues_model.GetLabelsByOrgID(t.Context(), -1, "leastissues", db.ListOptions{})
assert.True(t, issues_model.IsErrOrgLabelNotExist(err))
}
@@ -240,13 +240,13 @@ func TestGetLabelsByOrgID(t *testing.T) {
func TestGetLabelsByIssueID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
labels, err := issues_model.GetLabelsByIssueID(db.DefaultContext, 1)
labels, err := issues_model.GetLabelsByIssueID(t.Context(), 1)
assert.NoError(t, err)
if assert.Len(t, labels, 1) {
assert.EqualValues(t, 1, labels[0].ID)
}
labels, err = issues_model.GetLabelsByIssueID(db.DefaultContext, unittest.NonexistentID)
labels, err = issues_model.GetLabelsByIssueID(t.Context(), unittest.NonexistentID)
assert.NoError(t, err)
assert.Empty(t, labels)
}
@@ -265,7 +265,7 @@ func TestUpdateLabel(t *testing.T) {
}
label.Color = update.Color
label.Name = update.Name
assert.NoError(t, issues_model.UpdateLabel(db.DefaultContext, update))
assert.NoError(t, issues_model.UpdateLabel(t.Context(), update))
newLabel := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1})
assert.Equal(t, label.ID, newLabel.ID)
assert.Equal(t, label.Color, newLabel.Color)
@@ -278,21 +278,21 @@ func TestUpdateLabel(t *testing.T) {
func TestDeleteLabel(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1})
assert.NoError(t, issues_model.DeleteLabel(db.DefaultContext, label.RepoID, label.ID))
assert.NoError(t, issues_model.DeleteLabel(t.Context(), label.RepoID, label.ID))
unittest.AssertNotExistsBean(t, &issues_model.Label{ID: label.ID, RepoID: label.RepoID})
assert.NoError(t, issues_model.DeleteLabel(db.DefaultContext, label.RepoID, label.ID))
assert.NoError(t, issues_model.DeleteLabel(t.Context(), label.RepoID, label.ID))
unittest.AssertNotExistsBean(t, &issues_model.Label{ID: label.ID})
assert.NoError(t, issues_model.DeleteLabel(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID))
assert.NoError(t, issues_model.DeleteLabel(t.Context(), unittest.NonexistentID, unittest.NonexistentID))
unittest.CheckConsistencyFor(t, &issues_model.Label{}, &repo_model.Repository{})
}
func TestHasIssueLabel(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.True(t, issues_model.HasIssueLabel(db.DefaultContext, 1, 1))
assert.False(t, issues_model.HasIssueLabel(db.DefaultContext, 1, 2))
assert.False(t, issues_model.HasIssueLabel(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID))
assert.True(t, issues_model.HasIssueLabel(t.Context(), 1, 1))
assert.False(t, issues_model.HasIssueLabel(t.Context(), 1, 2))
assert.False(t, issues_model.HasIssueLabel(t.Context(), unittest.NonexistentID, unittest.NonexistentID))
}
func TestNewIssueLabel(t *testing.T) {
@@ -303,7 +303,7 @@ func TestNewIssueLabel(t *testing.T) {
// add new IssueLabel
prevNumIssues := label.NumIssues
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, label, doer))
assert.NoError(t, issues_model.NewIssueLabel(t.Context(), issue, label, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{
Type: issues_model.CommentTypeLabel,
@@ -316,7 +316,7 @@ func TestNewIssueLabel(t *testing.T) {
assert.Equal(t, prevNumIssues+1, label.NumIssues)
// re-add existing IssueLabel
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, label, doer))
assert.NoError(t, issues_model.NewIssueLabel(t.Context(), issue, label, doer))
unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{})
}
@@ -330,19 +330,19 @@ func TestNewIssueExclusiveLabel(t *testing.T) {
exclusiveLabelB := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8})
// coexisting regular and exclusive label
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, otherLabel, doer))
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelA, doer))
assert.NoError(t, issues_model.NewIssueLabel(t.Context(), issue, otherLabel, doer))
assert.NoError(t, issues_model.NewIssueLabel(t.Context(), issue, exclusiveLabelA, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
// exclusive label replaces existing one
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelB, doer))
assert.NoError(t, issues_model.NewIssueLabel(t.Context(), issue, exclusiveLabelB, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID})
unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
// exclusive label replaces existing one again
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelA, doer))
assert.NoError(t, issues_model.NewIssueLabel(t.Context(), issue, exclusiveLabelA, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID})
@@ -355,7 +355,7 @@ func TestNewIssueLabels(t *testing.T) {
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 5})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{label1, label2}, doer))
assert.NoError(t, issues_model.NewIssueLabels(t.Context(), issue, []*issues_model.Label{label1, label2}, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label1.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{
Type: issues_model.CommentTypeLabel,
@@ -373,7 +373,7 @@ func TestNewIssueLabels(t *testing.T) {
assert.Equal(t, 1, label2.NumClosedIssues)
// corner case: test empty slice
assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{}, doer))
assert.NoError(t, issues_model.NewIssueLabels(t.Context(), issue, []*issues_model.Label{}, doer))
unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{})
}
@@ -394,7 +394,7 @@ func TestDeleteIssueLabel(t *testing.T) {
}
}
ctx, committer, err := db.TxContext(db.DefaultContext)
ctx, committer, err := db.TxContext(t.Context())
defer committer.Close()
assert.NoError(t, err)
assert.NoError(t, issues_model.DeleteIssueLabel(ctx, issue, label, doer))

View File

@@ -27,12 +27,12 @@ func TestMilestone_State(t *testing.T) {
func TestGetMilestoneByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
milestone, err := issues_model.GetMilestoneByRepoID(db.DefaultContext, 1, 1)
milestone, err := issues_model.GetMilestoneByRepoID(t.Context(), 1, 1)
assert.NoError(t, err)
assert.EqualValues(t, 1, milestone.ID)
assert.EqualValues(t, 1, milestone.RepoID)
_, err = issues_model.GetMilestoneByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)
_, err = issues_model.GetMilestoneByRepoID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
assert.True(t, issues_model.IsErrMilestoneNotExist(err))
}
@@ -45,7 +45,7 @@ func TestGetMilestonesByRepoID(t *testing.T) {
isClosed = optional.Some(state == api.StateClosed)
}
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
milestones, err := db.Find[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
milestones, err := db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
RepoID: repo.ID,
IsClosed: isClosed,
})
@@ -82,7 +82,7 @@ func TestGetMilestonesByRepoID(t *testing.T) {
test(3, api.StateClosed)
test(3, api.StateAll)
milestones, err := db.Find[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
milestones, err := db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
RepoID: unittest.NonexistentID,
IsClosed: optional.Some(false),
})
@@ -95,7 +95,7 @@ func TestGetMilestones(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
test := func(sortType string, sortCond func(*issues_model.Milestone) int) {
for _, page := range []int{0, 1} {
milestones, err := db.Find[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
milestones, err := db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
ListOptions: db.ListOptions{
Page: page,
PageSize: setting.UI.IssuePagingNum,
@@ -112,7 +112,7 @@ func TestGetMilestones(t *testing.T) {
}
assert.True(t, sort.IntsAreSorted(values))
milestones, err = db.Find[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
milestones, err = db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
ListOptions: db.ListOptions{
Page: page,
PageSize: setting.UI.IssuePagingNum,
@@ -155,7 +155,7 @@ func TestCountRepoMilestones(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
RepoID: repoID,
})
assert.NoError(t, err)
@@ -165,7 +165,7 @@ func TestCountRepoMilestones(t *testing.T) {
test(2)
test(3)
count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
RepoID: unittest.NonexistentID,
})
assert.NoError(t, err)
@@ -176,7 +176,7 @@ func TestCountRepoClosedMilestones(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
RepoID: repoID,
IsClosed: optional.Some(true),
})
@@ -187,7 +187,7 @@ func TestCountRepoClosedMilestones(t *testing.T) {
test(2)
test(3)
count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
count, err := db.Count[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
RepoID: unittest.NonexistentID,
IsClosed: optional.Some(true),
})
@@ -204,7 +204,7 @@ func TestCountMilestonesByRepoIDs(t *testing.T) {
repo1OpenCount, repo1ClosedCount := milestonesCount(1)
repo2OpenCount, repo2ClosedCount := milestonesCount(2)
openCounts, err := issues_model.CountMilestonesMap(db.DefaultContext, issues_model.FindMilestoneOptions{
openCounts, err := issues_model.CountMilestonesMap(t.Context(), issues_model.FindMilestoneOptions{
RepoIDs: []int64{1, 2},
IsClosed: optional.Some(false),
})
@@ -212,7 +212,7 @@ func TestCountMilestonesByRepoIDs(t *testing.T) {
assert.EqualValues(t, repo1OpenCount, openCounts[1])
assert.EqualValues(t, repo2OpenCount, openCounts[2])
closedCounts, err := issues_model.CountMilestonesMap(db.DefaultContext,
closedCounts, err := issues_model.CountMilestonesMap(t.Context(),
issues_model.FindMilestoneOptions{
RepoIDs: []int64{1, 2},
IsClosed: optional.Some(true),
@@ -228,7 +228,7 @@ func TestGetMilestonesByRepoIDs(t *testing.T) {
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
test := func(sortType string, sortCond func(*issues_model.Milestone) int) {
for _, page := range []int{0, 1} {
openMilestones, err := db.Find[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
openMilestones, err := db.Find[issues_model.Milestone](t.Context(), issues_model.FindMilestoneOptions{
ListOptions: db.ListOptions{
Page: page,
PageSize: setting.UI.IssuePagingNum,
@@ -245,7 +245,7 @@ func TestGetMilestonesByRepoIDs(t *testing.T) {
}
assert.True(t, sort.IntsAreSorted(values))
closedMilestones, err := db.Find[issues_model.Milestone](db.DefaultContext,
closedMilestones, err := db.Find[issues_model.Milestone](t.Context(),
issues_model.FindMilestoneOptions{
ListOptions: db.ListOptions{
Page: page,
@@ -292,7 +292,7 @@ func TestNewMilestone(t *testing.T) {
Content: "milestoneContent",
}
assert.NoError(t, issues_model.NewMilestone(db.DefaultContext, milestone))
assert.NoError(t, issues_model.NewMilestone(t.Context(), milestone))
unittest.AssertExistsAndLoadBean(t, milestone)
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{})
}
@@ -301,22 +301,22 @@ func TestChangeMilestoneStatus(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1})
assert.NoError(t, issues_model.ChangeMilestoneStatus(db.DefaultContext, milestone, true))
assert.NoError(t, issues_model.ChangeMilestoneStatus(t.Context(), milestone, true))
unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}, "is_closed=1")
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{})
assert.NoError(t, issues_model.ChangeMilestoneStatus(db.DefaultContext, milestone, false))
assert.NoError(t, issues_model.ChangeMilestoneStatus(t.Context(), milestone, false))
unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}, "is_closed=0")
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{})
}
func TestDeleteMilestoneByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, issues_model.DeleteMilestoneByRepoID(db.DefaultContext, 1, 1))
assert.NoError(t, issues_model.DeleteMilestoneByRepoID(t.Context(), 1, 1))
unittest.AssertNotExistsBean(t, &issues_model.Milestone{ID: 1})
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: 1})
assert.NoError(t, issues_model.DeleteMilestoneByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID))
assert.NoError(t, issues_model.DeleteMilestoneByRepoID(t.Context(), unittest.NonexistentID, unittest.NonexistentID))
}
func TestUpdateMilestone(t *testing.T) {
@@ -325,7 +325,7 @@ func TestUpdateMilestone(t *testing.T) {
milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1})
milestone.Name = " newMilestoneName "
milestone.Content = "newMilestoneContent"
assert.NoError(t, issues_model.UpdateMilestone(db.DefaultContext, milestone, milestone.IsClosed))
assert.NoError(t, issues_model.UpdateMilestone(t.Context(), milestone, milestone.IsClosed))
milestone = unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1})
assert.Equal(t, "newMilestoneName", milestone.Name)
unittest.CheckConsistencyFor(t, &issues_model.Milestone{})
@@ -338,16 +338,16 @@ func TestUpdateMilestoneCounters(t *testing.T) {
issue.IsClosed = true
issue.ClosedUnix = timeutil.TimeStampNow()
_, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue)
_, err := db.GetEngine(t.Context()).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue)
assert.NoError(t, err)
assert.NoError(t, issues_model.UpdateMilestoneCounters(db.DefaultContext, issue.MilestoneID))
assert.NoError(t, issues_model.UpdateMilestoneCounters(t.Context(), issue.MilestoneID))
unittest.CheckConsistencyFor(t, &issues_model.Milestone{})
issue.IsClosed = false
issue.ClosedUnix = 0
_, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue)
_, err = db.GetEngine(t.Context()).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue)
assert.NoError(t, err)
assert.NoError(t, issues_model.UpdateMilestoneCounters(db.DefaultContext, issue.MilestoneID))
assert.NoError(t, issues_model.UpdateMilestoneCounters(t.Context(), issue.MilestoneID))
unittest.CheckConsistencyFor(t, &issues_model.Milestone{})
}
@@ -360,7 +360,7 @@ func TestMigrate_InsertMilestones(t *testing.T) {
RepoID: repo.ID,
Name: name,
}
err := issues_model.InsertMilestones(db.DefaultContext, ms)
err := issues_model.InsertMilestones(t.Context(), ms)
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, ms)
repoModified := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID})

View File

@@ -6,7 +6,6 @@ package issues_test
import (
"testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest"
@@ -20,13 +19,13 @@ func TestPullRequestList_LoadAttributes(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}),
unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}),
}
assert.NoError(t, prs.LoadAttributes(db.DefaultContext))
assert.NoError(t, prs.LoadAttributes(t.Context()))
for _, pr := range prs {
assert.NotNil(t, pr.Issue)
assert.Equal(t, pr.IssueID, pr.Issue.ID)
}
assert.NoError(t, issues_model.PullRequestList([]*issues_model.PullRequest{}).LoadAttributes(db.DefaultContext))
assert.NoError(t, issues_model.PullRequestList([]*issues_model.PullRequest{}).LoadAttributes(t.Context()))
}
func TestPullRequestList_LoadReviewCommentsCounts(t *testing.T) {
@@ -36,7 +35,7 @@ func TestPullRequestList_LoadReviewCommentsCounts(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}),
unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}),
}
reviewComments, err := prs.LoadReviewCommentsCounts(db.DefaultContext)
reviewComments, err := prs.LoadReviewCommentsCounts(t.Context())
assert.NoError(t, err)
assert.Len(t, reviewComments, 2)
for _, pr := range prs {
@@ -51,7 +50,7 @@ func TestPullRequestList_LoadReviews(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}),
unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}),
}
reviewList, err := prs.LoadReviews(db.DefaultContext)
reviewList, err := prs.LoadReviews(t.Context())
assert.NoError(t, err)
// 1, 7, 8, 9, 10, 22
assert.Len(t, reviewList, 6)

View File

@@ -20,7 +20,7 @@ import (
func TestPullRequest_LoadAttributes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadAttributes(db.DefaultContext))
assert.NoError(t, pr.LoadAttributes(t.Context()))
assert.NotNil(t, pr.Merger)
assert.Equal(t, pr.MergerID, pr.Merger.ID)
}
@@ -28,10 +28,10 @@ func TestPullRequest_LoadAttributes(t *testing.T) {
func TestPullRequest_LoadIssue(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadIssue(db.DefaultContext))
assert.NoError(t, pr.LoadIssue(t.Context()))
assert.NotNil(t, pr.Issue)
assert.Equal(t, int64(2), pr.Issue.ID)
assert.NoError(t, pr.LoadIssue(db.DefaultContext))
assert.NoError(t, pr.LoadIssue(t.Context()))
assert.NotNil(t, pr.Issue)
assert.Equal(t, int64(2), pr.Issue.ID)
}
@@ -39,10 +39,10 @@ func TestPullRequest_LoadIssue(t *testing.T) {
func TestPullRequest_LoadBaseRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext))
assert.NoError(t, pr.LoadBaseRepo(t.Context()))
assert.NotNil(t, pr.BaseRepo)
assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID)
assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext))
assert.NoError(t, pr.LoadBaseRepo(t.Context()))
assert.NotNil(t, pr.BaseRepo)
assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID)
}
@@ -50,7 +50,7 @@ func TestPullRequest_LoadBaseRepo(t *testing.T) {
func TestPullRequest_LoadHeadRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pr.LoadHeadRepo(db.DefaultContext))
assert.NoError(t, pr.LoadHeadRepo(t.Context()))
assert.NotNil(t, pr.HeadRepo)
assert.Equal(t, pr.HeadRepoID, pr.HeadRepo.ID)
}
@@ -61,7 +61,7 @@ func TestPullRequest_LoadHeadRepo(t *testing.T) {
func TestPullRequestsNewest(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{
prs, count, err := issues_model.PullRequests(t.Context(), 1, &issues_model.PullRequestsOptions{
ListOptions: db.ListOptions{
Page: 1,
},
@@ -91,16 +91,16 @@ func TestPullRequests_Closed_RecentSortType(t *testing.T) {
}
assert.NoError(t, unittest.PrepareTestDatabase())
_, err := db.Exec(db.DefaultContext, "UPDATE issue SET closed_unix = 1707270001, updated_unix = 1707270001, is_closed = true WHERE id = 2")
_, err := db.Exec(t.Context(), "UPDATE issue SET closed_unix = 1707270001, updated_unix = 1707270001, is_closed = true WHERE id = 2")
require.NoError(t, err)
_, err = db.Exec(db.DefaultContext, "UPDATE issue SET closed_unix = 1707271000, updated_unix = 1707279999, is_closed = true WHERE id = 3")
_, err = db.Exec(t.Context(), "UPDATE issue SET closed_unix = 1707271000, updated_unix = 1707279999, is_closed = true WHERE id = 3")
require.NoError(t, err)
_, err = db.Exec(db.DefaultContext, "UPDATE issue SET closed_unix = 1707279999, updated_unix = 1707275555, is_closed = true WHERE id = 11")
_, err = db.Exec(t.Context(), "UPDATE issue SET closed_unix = 1707279999, updated_unix = 1707275555, is_closed = true WHERE id = 11")
require.NoError(t, err)
for _, test := range tests {
t.Run(test.sortType, func(t *testing.T) {
prs, _, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{
prs, _, err := issues_model.PullRequests(t.Context(), 1, &issues_model.PullRequestsOptions{
ListOptions: db.ListOptions{
Page: 1,
},
@@ -122,33 +122,33 @@ func TestLoadRequestedReviewers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pull := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
assert.NoError(t, pull.LoadIssue(db.DefaultContext))
assert.NoError(t, pull.LoadIssue(t.Context()))
issue := pull.Issue
assert.NoError(t, issue.LoadRepo(db.DefaultContext))
assert.NoError(t, issue.LoadRepo(t.Context()))
assert.Empty(t, pull.RequestedReviewers)
user1, err := user_model.GetUserByID(db.DefaultContext, 1)
user1, err := user_model.GetUserByID(t.Context(), 1)
assert.NoError(t, err)
comment, err := issues_model.AddReviewRequest(db.DefaultContext, issue, user1, &user_model.User{})
comment, err := issues_model.AddReviewRequest(t.Context(), issue, user1, &user_model.User{})
assert.NoError(t, err)
assert.NotNil(t, comment)
assert.NoError(t, pull.LoadRequestedReviewers(db.DefaultContext))
assert.NoError(t, pull.LoadRequestedReviewers(t.Context()))
assert.Len(t, pull.RequestedReviewers, 6)
comment, err = issues_model.RemoveReviewRequest(db.DefaultContext, issue, user1, &user_model.User{})
comment, err = issues_model.RemoveReviewRequest(t.Context(), issue, user1, &user_model.User{})
assert.NoError(t, err)
assert.NotNil(t, comment)
pull.RequestedReviewers = nil
assert.NoError(t, pull.LoadRequestedReviewers(db.DefaultContext))
assert.NoError(t, pull.LoadRequestedReviewers(t.Context()))
assert.Empty(t, pull.RequestedReviewers)
}
func TestPullRequestsOldest(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{
prs, count, err := issues_model.PullRequests(t.Context(), 1, &issues_model.PullRequestsOptions{
ListOptions: db.ListOptions{
Page: 1,
},
@@ -166,11 +166,11 @@ func TestPullRequestsOldest(t *testing.T) {
func TestGetUnmergedPullRequest(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr, err := issues_model.GetUnmergedPullRequest(db.DefaultContext, 1, 1, "branch2", "master", issues_model.PullRequestFlowGithub)
pr, err := issues_model.GetUnmergedPullRequest(t.Context(), 1, 1, "branch2", "master", issues_model.PullRequestFlowGithub)
assert.NoError(t, err)
assert.Equal(t, int64(2), pr.ID)
_, err = issues_model.GetUnmergedPullRequest(db.DefaultContext, 1, 9223372036854775807, "branch1", "master", issues_model.PullRequestFlowGithub)
_, err = issues_model.GetUnmergedPullRequest(t.Context(), 1, 9223372036854775807, "branch1", "master", issues_model.PullRequestFlowGithub)
assert.Error(t, err)
assert.True(t, issues_model.IsErrPullRequestNotExist(err))
}
@@ -178,18 +178,18 @@ func TestGetUnmergedPullRequest(t *testing.T) {
func TestHasUnmergedPullRequestsByHeadInfo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
exist, err := issues_model.HasUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "branch2")
exist, err := issues_model.HasUnmergedPullRequestsByHeadInfo(t.Context(), 1, "branch2")
assert.NoError(t, err)
assert.True(t, exist)
exist, err = issues_model.HasUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "not_exist_branch")
exist, err = issues_model.HasUnmergedPullRequestsByHeadInfo(t.Context(), 1, "not_exist_branch")
assert.NoError(t, err)
assert.False(t, exist)
}
func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
prs, err := issues_model.GetUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "branch2")
prs, err := issues_model.GetUnmergedPullRequestsByHeadInfo(t.Context(), 1, "branch2")
assert.NoError(t, err)
assert.Len(t, prs, 1)
for _, pr := range prs {
@@ -200,7 +200,7 @@ func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) {
func TestGetUnmergedPullRequestsByBaseInfo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
prs, err := issues_model.GetUnmergedPullRequestsByBaseInfo(db.DefaultContext, 1, "master")
prs, err := issues_model.GetUnmergedPullRequestsByBaseInfo(t.Context(), 1, "master")
assert.NoError(t, err)
assert.Len(t, prs, 1)
pr := prs[0]
@@ -211,39 +211,39 @@ func TestGetUnmergedPullRequestsByBaseInfo(t *testing.T) {
func TestGetPullRequestByIndex(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr, err := issues_model.GetPullRequestByIndex(db.DefaultContext, 1, 2)
pr, err := issues_model.GetPullRequestByIndex(t.Context(), 1, 2)
assert.NoError(t, err)
assert.Equal(t, int64(1), pr.BaseRepoID)
assert.Equal(t, int64(2), pr.Index)
_, err = issues_model.GetPullRequestByIndex(db.DefaultContext, 9223372036854775807, 9223372036854775807)
_, err = issues_model.GetPullRequestByIndex(t.Context(), 9223372036854775807, 9223372036854775807)
assert.Error(t, err)
assert.True(t, issues_model.IsErrPullRequestNotExist(err))
_, err = issues_model.GetPullRequestByIndex(db.DefaultContext, 1, 0)
_, err = issues_model.GetPullRequestByIndex(t.Context(), 1, 0)
assert.Error(t, err)
assert.True(t, issues_model.IsErrPullRequestNotExist(err))
}
func TestGetPullRequestByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr, err := issues_model.GetPullRequestByID(db.DefaultContext, 1)
pr, err := issues_model.GetPullRequestByID(t.Context(), 1)
assert.NoError(t, err)
assert.Equal(t, int64(1), pr.ID)
assert.Equal(t, int64(2), pr.IssueID)
_, err = issues_model.GetPullRequestByID(db.DefaultContext, 9223372036854775807)
_, err = issues_model.GetPullRequestByID(t.Context(), 9223372036854775807)
assert.Error(t, err)
assert.True(t, issues_model.IsErrPullRequestNotExist(err))
}
func TestGetPullRequestByIssueID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr, err := issues_model.GetPullRequestByIssueID(db.DefaultContext, 2)
pr, err := issues_model.GetPullRequestByIssueID(t.Context(), 2)
assert.NoError(t, err)
assert.Equal(t, int64(2), pr.IssueID)
_, err = issues_model.GetPullRequestByIssueID(db.DefaultContext, 9223372036854775807)
_, err = issues_model.GetPullRequestByIssueID(t.Context(), 9223372036854775807)
assert.Error(t, err)
assert.True(t, issues_model.IsErrPullRequestNotExist(err))
}
@@ -255,7 +255,7 @@ func TestPullRequest_UpdateCols(t *testing.T) {
BaseBranch: "baseBranch",
HeadBranch: "headBranch",
}
assert.NoError(t, pr.UpdateCols(db.DefaultContext, "head_branch"))
assert.NoError(t, pr.UpdateCols(t.Context(), "head_branch"))
pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.Equal(t, "master", pr.BaseBranch)
@@ -269,50 +269,50 @@ func TestPullRequest_IsWorkInProgress(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
pr.LoadIssue(db.DefaultContext)
pr.LoadIssue(t.Context())
assert.False(t, pr.IsWorkInProgress(db.DefaultContext))
assert.False(t, pr.IsWorkInProgress(t.Context()))
pr.Issue.Title = "WIP: " + pr.Issue.Title
assert.True(t, pr.IsWorkInProgress(db.DefaultContext))
assert.True(t, pr.IsWorkInProgress(t.Context()))
pr.Issue.Title = "[wip]: " + pr.Issue.Title
assert.True(t, pr.IsWorkInProgress(db.DefaultContext))
assert.True(t, pr.IsWorkInProgress(t.Context()))
}
func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
pr.LoadIssue(db.DefaultContext)
pr.LoadIssue(t.Context())
assert.Empty(t, pr.GetWorkInProgressPrefix(db.DefaultContext))
assert.Empty(t, pr.GetWorkInProgressPrefix(t.Context()))
original := pr.Issue.Title
pr.Issue.Title = "WIP: " + original
assert.Equal(t, "WIP:", pr.GetWorkInProgressPrefix(db.DefaultContext))
assert.Equal(t, "WIP:", pr.GetWorkInProgressPrefix(t.Context()))
pr.Issue.Title = "[wip] " + original
assert.Equal(t, "[wip]", pr.GetWorkInProgressPrefix(db.DefaultContext))
assert.Equal(t, "[wip]", pr.GetWorkInProgressPrefix(t.Context()))
}
func TestDeleteOrphanedObjects(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
countBefore, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{})
countBefore, err := db.GetEngine(t.Context()).Count(&issues_model.PullRequest{})
assert.NoError(t, err)
_, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003})
_, err = db.GetEngine(t.Context()).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003})
assert.NoError(t, err)
orphaned, err := db.CountOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id")
orphaned, err := db.CountOrphanedObjects(t.Context(), "pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err)
assert.EqualValues(t, 3, orphaned)
err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id")
err = db.DeleteOrphanedObjects(t.Context(), "pull_request", "issue", "pull_request.issue_id=issue.id")
assert.NoError(t, err)
countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{})
countAfter, err := db.GetEngine(t.Context()).Count(&issues_model.PullRequest{})
assert.NoError(t, err)
assert.Equal(t, countBefore, countAfter)
}
@@ -345,20 +345,20 @@ func TestGetApprovers(t *testing.T) {
// Official reviews are already deduplicated. Allow unofficial reviews
// to assert that there are no duplicated approvers.
setting.Repository.PullRequest.DefaultMergeMessageOfficialApproversOnly = false
approvers := pr.GetApprovers(db.DefaultContext)
approvers := pr.GetApprovers(t.Context())
expected := "Reviewed-by: User Five <user5@example.com>\nReviewed-by: Org Six <org6@example.com>\n"
assert.Equal(t, expected, approvers)
}
func TestGetPullRequestByMergedCommit(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pr, err := issues_model.GetPullRequestByMergedCommit(db.DefaultContext, 1, "1a8823cd1a9549fde083f992f6b9b87a7ab74fb3")
pr, err := issues_model.GetPullRequestByMergedCommit(t.Context(), 1, "1a8823cd1a9549fde083f992f6b9b87a7ab74fb3")
assert.NoError(t, err)
assert.EqualValues(t, 1, pr.ID)
_, err = issues_model.GetPullRequestByMergedCommit(db.DefaultContext, 0, "1a8823cd1a9549fde083f992f6b9b87a7ab74fb3")
_, err = issues_model.GetPullRequestByMergedCommit(t.Context(), 0, "1a8823cd1a9549fde083f992f6b9b87a7ab74fb3")
assert.ErrorAs(t, err, &issues_model.ErrPullRequestNotExist{})
_, err = issues_model.GetPullRequestByMergedCommit(db.DefaultContext, 1, "")
_, err = issues_model.GetPullRequestByMergedCommit(t.Context(), 1, "")
assert.ErrorAs(t, err, &issues_model.ErrPullRequestNotExist{})
}
@@ -382,7 +382,7 @@ func TestMigrate_InsertPullRequests(t *testing.T) {
Issue: i,
}
err := issues_model.InsertPullRequests(db.DefaultContext, p)
err := issues_model.InsertPullRequests(t.Context(), p)
assert.NoError(t, err)
_ = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{IssueID: i.ID})

View File

@@ -6,7 +6,6 @@ package issues_test
import (
"testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
@@ -17,12 +16,12 @@ import (
func TestGetReviewByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
review, err := issues_model.GetReviewByID(db.DefaultContext, 1)
review, err := issues_model.GetReviewByID(t.Context(), 1)
assert.NoError(t, err)
assert.Equal(t, "Demo Review", review.Content)
assert.Equal(t, issues_model.ReviewTypeApprove, review.Type)
_, err = issues_model.GetReviewByID(db.DefaultContext, 23892)
_, err = issues_model.GetReviewByID(t.Context(), 23892)
assert.Error(t, err)
assert.True(t, issues_model.IsErrReviewNotExist(err), "IsErrReviewNotExist")
}
@@ -30,23 +29,23 @@ func TestGetReviewByID(t *testing.T) {
func TestReview_LoadAttributes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
review := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 1})
assert.NoError(t, review.LoadAttributes(db.DefaultContext))
assert.NoError(t, review.LoadAttributes(t.Context()))
assert.NotNil(t, review.Issue)
assert.NotNil(t, review.Reviewer)
invalidReview1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 2})
assert.Error(t, invalidReview1.LoadAttributes(db.DefaultContext))
assert.Error(t, invalidReview1.LoadAttributes(t.Context()))
invalidReview2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 3})
assert.Error(t, invalidReview2.LoadAttributes(db.DefaultContext))
assert.Error(t, invalidReview2.LoadAttributes(t.Context()))
}
func TestReview_LoadCodeComments(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
review := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 4})
assert.NoError(t, review.LoadAttributes(db.DefaultContext))
assert.NoError(t, review.LoadCodeComments(db.DefaultContext))
assert.NoError(t, review.LoadAttributes(t.Context()))
assert.NoError(t, review.LoadCodeComments(t.Context()))
assert.Len(t, review.CodeComments, 1)
assert.Equal(t, int64(4), review.CodeComments["README.md"][int64(4)][0].Line)
}
@@ -62,7 +61,7 @@ func TestReviewType_Icon(t *testing.T) {
func TestFindReviews(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
reviews, err := issues_model.FindReviews(db.DefaultContext, issues_model.FindReviewOptions{
reviews, err := issues_model.FindReviews(t.Context(), issues_model.FindReviewOptions{
Types: []issues_model.ReviewType{issues_model.ReviewTypeApprove},
IssueID: 2,
ReviewerID: 1,
@@ -74,7 +73,7 @@ func TestFindReviews(t *testing.T) {
func TestFindLatestReviews(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
reviews, err := issues_model.FindLatestReviews(db.DefaultContext, issues_model.FindReviewOptions{
reviews, err := issues_model.FindLatestReviews(t.Context(), issues_model.FindReviewOptions{
Types: []issues_model.ReviewType{issues_model.ReviewTypeApprove},
IssueID: 11,
})
@@ -89,14 +88,14 @@ func TestGetCurrentReview(t *testing.T) {
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
review, err := issues_model.GetCurrentReview(db.DefaultContext, user, issue)
review, err := issues_model.GetCurrentReview(t.Context(), user, issue)
assert.NoError(t, err)
assert.NotNil(t, review)
assert.Equal(t, issues_model.ReviewTypePending, review.Type)
assert.Equal(t, "Pending Review", review.Content)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 7})
review2, err := issues_model.GetCurrentReview(db.DefaultContext, user2, issue)
review2, err := issues_model.GetCurrentReview(t.Context(), user2, issue)
assert.Error(t, err)
assert.True(t, issues_model.IsErrReviewNotExist(err))
assert.Nil(t, review2)
@@ -108,7 +107,7 @@ func TestCreateReview(t *testing.T) {
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
review, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{
review, err := issues_model.CreateReview(t.Context(), issues_model.CreateReviewOptions{
Content: "New Review",
Type: issues_model.ReviewTypePending,
Issue: issue,
@@ -162,11 +161,11 @@ func TestGetReviewersByIssueID(t *testing.T) {
},
)
allReviews, migratedReviews, err := issues_model.GetReviewsByIssueID(db.DefaultContext, issue.ID)
allReviews, migratedReviews, err := issues_model.GetReviewsByIssueID(t.Context(), issue.ID)
assert.NoError(t, err)
assert.Empty(t, migratedReviews)
for _, review := range allReviews {
assert.NoError(t, review.LoadReviewer(db.DefaultContext))
assert.NoError(t, review.LoadReviewer(t.Context()))
}
if assert.Len(t, allReviews, 5) {
for i, review := range allReviews {
@@ -187,46 +186,46 @@ func TestDismissReview(t *testing.T) {
assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.Dismissed)
assert.NoError(t, issues_model.DismissReview(db.DefaultContext, rejectReviewExample, true))
assert.NoError(t, issues_model.DismissReview(t.Context(), rejectReviewExample, true))
rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
assert.True(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed)
assert.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, true))
assert.NoError(t, issues_model.DismissReview(t.Context(), requestReviewExample, true))
rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
assert.True(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.Dismissed)
assert.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, true))
assert.NoError(t, issues_model.DismissReview(t.Context(), requestReviewExample, true))
rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
assert.True(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.Dismissed)
assert.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, false))
assert.NoError(t, issues_model.DismissReview(t.Context(), requestReviewExample, false))
rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
assert.True(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.Dismissed)
assert.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, false))
assert.NoError(t, issues_model.DismissReview(t.Context(), requestReviewExample, false))
rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
assert.True(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.Dismissed)
assert.NoError(t, issues_model.DismissReview(db.DefaultContext, rejectReviewExample, false))
assert.NoError(t, issues_model.DismissReview(t.Context(), rejectReviewExample, false))
assert.False(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.Dismissed)
assert.NoError(t, issues_model.DismissReview(db.DefaultContext, approveReviewExample, true))
assert.NoError(t, issues_model.DismissReview(t.Context(), approveReviewExample, true))
assert.False(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed)
assert.True(t, approveReviewExample.Dismissed)
@@ -238,7 +237,7 @@ func TestDeleteReview(t *testing.T) {
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
review1, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{
review1, err := issues_model.CreateReview(t.Context(), issues_model.CreateReviewOptions{
Content: "Official rejection",
Type: issues_model.ReviewTypeReject,
Official: false,
@@ -247,7 +246,7 @@ func TestDeleteReview(t *testing.T) {
})
assert.NoError(t, err)
review2, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{
review2, err := issues_model.CreateReview(t.Context(), issues_model.CreateReviewOptions{
Content: "Official approval",
Type: issues_model.ReviewTypeApprove,
Official: true,
@@ -256,13 +255,13 @@ func TestDeleteReview(t *testing.T) {
})
assert.NoError(t, err)
assert.NoError(t, issues_model.DeleteReview(db.DefaultContext, review2))
assert.NoError(t, issues_model.DeleteReview(t.Context(), review2))
_, err = issues_model.GetReviewByID(db.DefaultContext, review2.ID)
_, err = issues_model.GetReviewByID(t.Context(), review2.ID)
assert.Error(t, err)
assert.True(t, issues_model.IsErrReviewNotExist(err), "IsErrReviewNotExist")
review1, err = issues_model.GetReviewByID(db.DefaultContext, review1.ID)
review1, err = issues_model.GetReviewByID(t.Context(), review1.ID)
assert.NoError(t, err)
assert.True(t, review1.Official)
}
@@ -273,7 +272,7 @@ func TestDeleteDismissedReview(t *testing.T) {
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID})
review, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{
review, err := issues_model.CreateReview(t.Context(), issues_model.CreateReviewOptions{
Content: "reject",
Type: issues_model.ReviewTypeReject,
Official: false,
@@ -281,8 +280,8 @@ func TestDeleteDismissedReview(t *testing.T) {
Reviewer: user,
})
assert.NoError(t, err)
assert.NoError(t, issues_model.DismissReview(db.DefaultContext, review, true))
comment, err := issues_model.CreateComment(db.DefaultContext, &issues_model.CreateCommentOptions{
assert.NoError(t, issues_model.DismissReview(t.Context(), review, true))
comment, err := issues_model.CreateComment(t.Context(), &issues_model.CreateCommentOptions{
Type: issues_model.CommentTypeDismissReview,
Doer: user,
Repo: repo,
@@ -292,7 +291,7 @@ func TestDeleteDismissedReview(t *testing.T) {
})
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: comment.ID})
assert.NoError(t, issues_model.DeleteReview(db.DefaultContext, review))
assert.NoError(t, issues_model.DeleteReview(t.Context(), review))
unittest.AssertNotExistsBean(t, &issues_model.Comment{ID: comment.ID})
}
@@ -300,11 +299,11 @@ func TestAddReviewRequest(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
pull := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.NoError(t, pull.LoadIssue(db.DefaultContext))
assert.NoError(t, pull.LoadIssue(t.Context()))
issue := pull.Issue
assert.NoError(t, issue.LoadRepo(db.DefaultContext))
assert.NoError(t, issue.LoadRepo(t.Context()))
reviewer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
_, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{
_, err := issues_model.CreateReview(t.Context(), issues_model.CreateReviewOptions{
Issue: issue,
Reviewer: reviewer,
Type: issues_model.ReviewTypeReject,
@@ -312,16 +311,16 @@ func TestAddReviewRequest(t *testing.T) {
assert.NoError(t, err)
pull.HasMerged = false
assert.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged"))
assert.NoError(t, pull.UpdateCols(t.Context(), "has_merged"))
issue.IsClosed = true
_, err = issues_model.AddReviewRequest(db.DefaultContext, issue, reviewer, &user_model.User{})
_, err = issues_model.AddReviewRequest(t.Context(), issue, reviewer, &user_model.User{})
assert.Error(t, err)
assert.True(t, issues_model.IsErrReviewRequestOnClosedPR(err))
pull.HasMerged = true
assert.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged"))
assert.NoError(t, pull.UpdateCols(t.Context(), "has_merged"))
issue.IsClosed = false
_, err = issues_model.AddReviewRequest(db.DefaultContext, issue, reviewer, &user_model.User{})
_, err = issues_model.AddReviewRequest(t.Context(), issue, reviewer, &user_model.User{})
assert.Error(t, err)
assert.True(t, issues_model.IsErrReviewRequestOnClosedPR(err))
}

View File

@@ -6,7 +6,6 @@ package issues_test
import (
"testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -20,32 +19,32 @@ func TestCancelStopwatch(t *testing.T) {
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
issue1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
ok, err := issues_model.CancelStopwatch(db.DefaultContext, user1, issue1)
ok, err := issues_model.CancelStopwatch(t.Context(), user1, issue1)
assert.NoError(t, err)
assert.True(t, ok)
unittest.AssertNotExistsBean(t, &issues_model.Stopwatch{UserID: user1.ID, IssueID: issue1.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{Type: issues_model.CommentTypeCancelTracking, PosterID: user1.ID, IssueID: issue1.ID})
ok, err = issues_model.CancelStopwatch(db.DefaultContext, user1, issue1)
ok, err = issues_model.CancelStopwatch(t.Context(), user1, issue1)
assert.NoError(t, err)
assert.False(t, ok)
}
func TestStopwatchExists(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.True(t, issues_model.StopwatchExists(db.DefaultContext, 1, 1))
assert.False(t, issues_model.StopwatchExists(db.DefaultContext, 1, 2))
assert.True(t, issues_model.StopwatchExists(t.Context(), 1, 1))
assert.False(t, issues_model.StopwatchExists(t.Context(), 1, 2))
}
func TestHasUserStopwatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
exists, sw, _, err := issues_model.HasUserStopwatch(db.DefaultContext, 1)
exists, sw, _, err := issues_model.HasUserStopwatch(t.Context(), 1)
assert.NoError(t, err)
assert.True(t, exists)
assert.Equal(t, int64(1), sw.ID)
exists, _, _, err = issues_model.HasUserStopwatch(db.DefaultContext, 3)
exists, _, _, err = issues_model.HasUserStopwatch(t.Context(), 3)
assert.NoError(t, err)
assert.False(t, exists)
}
@@ -58,16 +57,16 @@ func TestCreateOrStopIssueStopwatch(t *testing.T) {
issue3 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3})
// create a new stopwatch
ok, err := issues_model.CreateIssueStopwatch(db.DefaultContext, user4, issue1)
ok, err := issues_model.CreateIssueStopwatch(t.Context(), user4, issue1)
assert.NoError(t, err)
assert.True(t, ok)
unittest.AssertExistsAndLoadBean(t, &issues_model.Stopwatch{UserID: user4.ID, IssueID: issue1.ID})
// should not create a second stopwatch for the same issue
ok, err = issues_model.CreateIssueStopwatch(db.DefaultContext, user4, issue1)
ok, err = issues_model.CreateIssueStopwatch(t.Context(), user4, issue1)
assert.NoError(t, err)
assert.False(t, ok)
// on a different issue, it will finish the existing stopwatch and create a new one
ok, err = issues_model.CreateIssueStopwatch(db.DefaultContext, user4, issue3)
ok, err = issues_model.CreateIssueStopwatch(t.Context(), user4, issue3)
assert.NoError(t, err)
assert.True(t, ok)
unittest.AssertNotExistsBean(t, &issues_model.Stopwatch{UserID: user4.ID, IssueID: issue1.ID})
@@ -76,12 +75,12 @@ func TestCreateOrStopIssueStopwatch(t *testing.T) {
// user2 already has a stopwatch in test fixture
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
ok, err = issues_model.FinishIssueStopwatch(db.DefaultContext, user2, issue2)
ok, err = issues_model.FinishIssueStopwatch(t.Context(), user2, issue2)
assert.NoError(t, err)
assert.True(t, ok)
unittest.AssertNotExistsBean(t, &issues_model.Stopwatch{UserID: user2.ID, IssueID: issue2.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.TrackedTime{UserID: user2.ID, IssueID: issue2.ID})
ok, err = issues_model.FinishIssueStopwatch(db.DefaultContext, user2, issue2)
ok, err = issues_model.FinishIssueStopwatch(t.Context(), user2, issue2)
assert.NoError(t, err)
assert.False(t, ok)
}

View File

@@ -7,7 +7,6 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -19,14 +18,14 @@ import (
func TestAddTime(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org3, err := user_model.GetUserByID(db.DefaultContext, 3)
org3, err := user_model.GetUserByID(t.Context(), 3)
assert.NoError(t, err)
issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1)
issue1, err := issues_model.GetIssueByID(t.Context(), 1)
assert.NoError(t, err)
// 3661 = 1h 1min 1s
trackedTime, err := issues_model.AddTime(db.DefaultContext, org3, issue1, 3661, time.Now())
trackedTime, err := issues_model.AddTime(t.Context(), org3, issue1, 3661, time.Now())
assert.NoError(t, err)
assert.Equal(t, int64(3), trackedTime.UserID)
assert.Equal(t, int64(1), trackedTime.IssueID)
@@ -43,39 +42,39 @@ func TestGetTrackedTimes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
// by Issue
times, err := issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 1})
times, err := issues_model.GetTrackedTimes(t.Context(), &issues_model.FindTrackedTimesOptions{IssueID: 1})
assert.NoError(t, err)
assert.Len(t, times, 1)
assert.Equal(t, int64(400), times[0].Time)
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: -1})
times, err = issues_model.GetTrackedTimes(t.Context(), &issues_model.FindTrackedTimesOptions{IssueID: -1})
assert.NoError(t, err)
assert.Empty(t, times)
// by User
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{UserID: 1})
times, err = issues_model.GetTrackedTimes(t.Context(), &issues_model.FindTrackedTimesOptions{UserID: 1})
assert.NoError(t, err)
assert.Len(t, times, 3)
assert.Equal(t, int64(400), times[0].Time)
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{UserID: 3})
times, err = issues_model.GetTrackedTimes(t.Context(), &issues_model.FindTrackedTimesOptions{UserID: 3})
assert.NoError(t, err)
assert.Empty(t, times)
// by Repo
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{RepositoryID: 2})
times, err = issues_model.GetTrackedTimes(t.Context(), &issues_model.FindTrackedTimesOptions{RepositoryID: 2})
assert.NoError(t, err)
assert.Len(t, times, 3)
assert.Equal(t, int64(1), times[0].Time)
issue, err := issues_model.GetIssueByID(db.DefaultContext, times[0].IssueID)
issue, err := issues_model.GetIssueByID(t.Context(), times[0].IssueID)
assert.NoError(t, err)
assert.Equal(t, int64(2), issue.RepoID)
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{RepositoryID: 1})
times, err = issues_model.GetTrackedTimes(t.Context(), &issues_model.FindTrackedTimesOptions{RepositoryID: 1})
assert.NoError(t, err)
assert.Len(t, times, 5)
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{RepositoryID: 10})
times, err = issues_model.GetTrackedTimes(t.Context(), &issues_model.FindTrackedTimesOptions{RepositoryID: 10})
assert.NoError(t, err)
assert.Empty(t, times)
}
@@ -83,7 +82,7 @@ func TestGetTrackedTimes(t *testing.T) {
func TestTotalTimesForEachUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
total, err := issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 1})
total, err := issues_model.TotalTimesForEachUser(t.Context(), &issues_model.FindTrackedTimesOptions{IssueID: 1})
assert.NoError(t, err)
assert.Len(t, total, 1)
for user, time := range total {
@@ -91,7 +90,7 @@ func TestTotalTimesForEachUser(t *testing.T) {
assert.EqualValues(t, 400, time)
}
total, err = issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 2})
total, err = issues_model.TotalTimesForEachUser(t.Context(), &issues_model.FindTrackedTimesOptions{IssueID: 2})
assert.NoError(t, err)
assert.Len(t, total, 2)
for user, time := range total {
@@ -104,7 +103,7 @@ func TestTotalTimesForEachUser(t *testing.T) {
}
}
total, err = issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 5})
total, err = issues_model.TotalTimesForEachUser(t.Context(), &issues_model.FindTrackedTimesOptions{IssueID: 5})
assert.NoError(t, err)
assert.Len(t, total, 1)
for user, time := range total {
@@ -112,7 +111,7 @@ func TestTotalTimesForEachUser(t *testing.T) {
assert.EqualValues(t, 1, time)
}
total, err = issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 4})
total, err = issues_model.TotalTimesForEachUser(t.Context(), &issues_model.FindTrackedTimesOptions{IssueID: 4})
assert.NoError(t, err)
assert.Len(t, total, 2)
}
@@ -120,15 +119,15 @@ func TestTotalTimesForEachUser(t *testing.T) {
func TestGetIssueTotalTrackedTime(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ttt, err := issues_model.GetIssueTotalTrackedTime(db.DefaultContext, &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.Some(false))
ttt, err := issues_model.GetIssueTotalTrackedTime(t.Context(), &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.Some(false))
assert.NoError(t, err)
assert.EqualValues(t, 3682, ttt)
ttt, err = issues_model.GetIssueTotalTrackedTime(db.DefaultContext, &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.Some(true))
ttt, err = issues_model.GetIssueTotalTrackedTime(t.Context(), &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.Some(true))
assert.NoError(t, err)
assert.EqualValues(t, 0, ttt)
ttt, err = issues_model.GetIssueTotalTrackedTime(db.DefaultContext, &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.None[bool]())
ttt, err = issues_model.GetIssueTotalTrackedTime(t.Context(), &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.None[bool]())
assert.NoError(t, err)
assert.EqualValues(t, 3682, ttt)
}

View File

@@ -6,7 +6,6 @@ package v1_22
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/migrations/base"
"code.gitea.io/gitea/models/project"
@@ -32,12 +31,12 @@ func Test_CheckProjectColumnsConsistency(t *testing.T) {
assert.True(t, defaultColumn.Default)
// check if multiple defaults, previous were removed and last will be kept
expectDefaultColumn, err := project.GetColumn(db.DefaultContext, 2)
expectDefaultColumn, err := project.GetColumn(t.Context(), 2)
assert.NoError(t, err)
assert.Equal(t, int64(2), expectDefaultColumn.ProjectID)
assert.False(t, expectDefaultColumn.Default)
expectNonDefaultColumn, err := project.GetColumn(db.DefaultContext, 3)
expectNonDefaultColumn, err := project.GetColumn(t.Context(), 3)
assert.NoError(t, err)
assert.Equal(t, int64(2), expectNonDefaultColumn.ProjectID)
assert.True(t, expectNonDefaultColumn.Default)

View File

@@ -25,15 +25,15 @@ func TestOrgList(t *testing.T) {
}
func testCountOrganizations(t *testing.T) {
expected, err := db.GetEngine(db.DefaultContext).Where("type=?", user_model.UserTypeOrganization).Count(&organization.Organization{})
expected, err := db.GetEngine(t.Context()).Where("type=?", user_model.UserTypeOrganization).Count(&organization.Organization{})
assert.NoError(t, err)
cnt, err := db.Count[organization.Organization](db.DefaultContext, organization.FindOrgOptions{IncludeVisibility: structs.VisibleTypePrivate})
cnt, err := db.Count[organization.Organization](t.Context(), organization.FindOrgOptions{IncludeVisibility: structs.VisibleTypePrivate})
assert.NoError(t, err)
assert.Equal(t, expected, cnt)
}
func testFindOrgs(t *testing.T) {
orgs, err := db.Find[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
orgs, err := db.Find[organization.Organization](t.Context(), organization.FindOrgOptions{
UserID: 4,
IncludeVisibility: structs.VisibleTypePrivate,
})
@@ -42,13 +42,13 @@ func testFindOrgs(t *testing.T) {
assert.EqualValues(t, 3, orgs[0].ID)
}
orgs, err = db.Find[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
orgs, err = db.Find[organization.Organization](t.Context(), organization.FindOrgOptions{
UserID: 4,
})
assert.NoError(t, err)
assert.Empty(t, orgs)
total, err := db.Count[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
total, err := db.Count[organization.Organization](t.Context(), organization.FindOrgOptions{
UserID: 4,
IncludeVisibility: structs.VisibleTypePrivate,
})
@@ -57,7 +57,7 @@ func testFindOrgs(t *testing.T) {
}
func testGetUserOrgsList(t *testing.T) {
orgs, err := organization.GetUserOrgsList(db.DefaultContext, &user_model.User{ID: 4})
orgs, err := organization.GetUserOrgsList(t.Context(), &user_model.User{ID: 4})
assert.NoError(t, err)
if assert.Len(t, orgs, 1) {
assert.EqualValues(t, 3, orgs[0].ID)
@@ -67,10 +67,10 @@ func testGetUserOrgsList(t *testing.T) {
}
func testLoadOrgListTeams(t *testing.T) {
orgs, err := organization.GetUserOrgsList(db.DefaultContext, &user_model.User{ID: 4})
orgs, err := organization.GetUserOrgsList(t.Context(), &user_model.User{ID: 4})
assert.NoError(t, err)
assert.Len(t, orgs, 1)
teamsMap, err := organization.OrgList(orgs).LoadTeams(db.DefaultContext)
teamsMap, err := organization.OrgList(orgs).LoadTeams(t.Context())
assert.NoError(t, err)
assert.Len(t, teamsMap, 1)
assert.Len(t, teamsMap[3], 5)

View File

@@ -34,7 +34,7 @@ func TestUser_IsOwnedBy(t *testing.T) {
{2, 3, false},
} {
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID})
isOwner, err := org.IsOwnedBy(db.DefaultContext, testCase.UserID)
isOwner, err := org.IsOwnedBy(t.Context(), testCase.UserID)
assert.NoError(t, err)
assert.Equal(t, testCase.ExpectedOwner, isOwner)
}
@@ -55,7 +55,7 @@ func TestUser_IsOrgMember(t *testing.T) {
{2, 3, false},
} {
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID})
isMember, err := org.IsOrgMember(db.DefaultContext, testCase.UserID)
isMember, err := org.IsOrgMember(t.Context(), testCase.UserID)
assert.NoError(t, err)
assert.Equal(t, testCase.ExpectedMember, isMember)
}
@@ -64,35 +64,35 @@ func TestUser_IsOrgMember(t *testing.T) {
func TestUser_GetTeam(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
team, err := org.GetTeam(db.DefaultContext, "team1")
team, err := org.GetTeam(t.Context(), "team1")
assert.NoError(t, err)
assert.Equal(t, org.ID, team.OrgID)
assert.Equal(t, "team1", team.LowerName)
_, err = org.GetTeam(db.DefaultContext, "does not exist")
_, err = org.GetTeam(t.Context(), "does not exist")
assert.True(t, organization.IsErrTeamNotExist(err))
nonOrg := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 2})
_, err = nonOrg.GetTeam(db.DefaultContext, "team")
_, err = nonOrg.GetTeam(t.Context(), "team")
assert.True(t, organization.IsErrTeamNotExist(err))
}
func TestUser_GetOwnerTeam(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
team, err := org.GetOwnerTeam(db.DefaultContext)
team, err := org.GetOwnerTeam(t.Context())
assert.NoError(t, err)
assert.Equal(t, org.ID, team.OrgID)
nonOrg := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 2})
_, err = nonOrg.GetOwnerTeam(db.DefaultContext)
_, err = nonOrg.GetOwnerTeam(t.Context())
assert.True(t, organization.IsErrTeamNotExist(err))
}
func TestUser_GetTeams(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
teams, err := org.LoadTeams(db.DefaultContext)
teams, err := org.LoadTeams(t.Context())
assert.NoError(t, err)
if assert.Len(t, teams, 5) {
assert.Equal(t, int64(1), teams[0].ID)
@@ -106,7 +106,7 @@ func TestUser_GetTeams(t *testing.T) {
func TestUser_GetMembers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
members, _, err := org.GetMembers(db.DefaultContext, &user_model.User{IsAdmin: true})
members, _, err := org.GetMembers(t.Context(), &user_model.User{IsAdmin: true})
assert.NoError(t, err)
if assert.Len(t, members, 3) {
assert.Equal(t, int64(2), members[0].ID)
@@ -118,22 +118,22 @@ func TestUser_GetMembers(t *testing.T) {
func TestGetOrgByName(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org, err := organization.GetOrgByName(db.DefaultContext, "org3")
org, err := organization.GetOrgByName(t.Context(), "org3")
assert.NoError(t, err)
assert.EqualValues(t, 3, org.ID)
assert.Equal(t, "org3", org.Name)
_, err = organization.GetOrgByName(db.DefaultContext, "user2") // user2 is an individual
_, err = organization.GetOrgByName(t.Context(), "user2") // user2 is an individual
assert.True(t, organization.IsErrOrgNotExist(err))
_, err = organization.GetOrgByName(db.DefaultContext, "") // corner case
_, err = organization.GetOrgByName(t.Context(), "") // corner case
assert.True(t, organization.IsErrOrgNotExist(err))
}
func TestIsOrganizationOwner(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(orgID, userID int64, expected bool) {
isOwner, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, userID)
isOwner, err := organization.IsOrganizationOwner(t.Context(), orgID, userID)
assert.NoError(t, err)
assert.Equal(t, expected, isOwner)
}
@@ -147,7 +147,7 @@ func TestIsOrganizationOwner(t *testing.T) {
func TestIsOrganizationMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(orgID, userID int64, expected bool) {
isMember, err := organization.IsOrganizationMember(db.DefaultContext, orgID, userID)
isMember, err := organization.IsOrganizationMember(t.Context(), orgID, userID)
assert.NoError(t, err)
assert.Equal(t, expected, isMember)
}
@@ -162,7 +162,7 @@ func TestIsOrganizationMember(t *testing.T) {
func TestIsPublicMembership(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(orgID, userID int64, expected bool) {
isMember, err := organization.IsPublicMembership(db.DefaultContext, orgID, userID)
isMember, err := organization.IsPublicMembership(t.Context(), orgID, userID)
assert.NoError(t, err)
assert.Equal(t, expected, isMember)
}
@@ -226,11 +226,11 @@ func TestRestrictedUserOrgMembers(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
count, err := organization.CountOrgMembers(db.DefaultContext, tc.opts)
count, err := organization.CountOrgMembers(t.Context(), tc.opts)
assert.NoError(t, err)
assert.EqualValues(t, len(tc.expectedUIDs), count)
members, err := organization.GetOrgUsersByOrgID(db.DefaultContext, tc.opts)
members, err := organization.GetOrgUsersByOrgID(t.Context(), tc.opts)
assert.NoError(t, err)
memberUIDs := make([]int64, 0, len(members))
for _, member := range members {
@@ -250,7 +250,7 @@ func TestGetOrgUsersByOrgID(t *testing.T) {
OrgID: 3,
}
assert.False(t, opts.PublicOnly())
orgUsers, err := organization.GetOrgUsersByOrgID(db.DefaultContext, opts)
orgUsers, err := organization.GetOrgUsersByOrgID(t.Context(), opts)
assert.NoError(t, err)
sort.Slice(orgUsers, func(i, j int) bool {
return orgUsers[i].ID < orgUsers[j].ID
@@ -274,11 +274,11 @@ func TestGetOrgUsersByOrgID(t *testing.T) {
opts = &organization.FindOrgMembersOpts{OrgID: 3}
assert.True(t, opts.PublicOnly())
orgUsers, err = organization.GetOrgUsersByOrgID(db.DefaultContext, opts)
orgUsers, err = organization.GetOrgUsersByOrgID(t.Context(), opts)
assert.NoError(t, err)
assert.Len(t, orgUsers, 2)
orgUsers, err = organization.GetOrgUsersByOrgID(db.DefaultContext, &organization.FindOrgMembersOpts{
orgUsers, err = organization.GetOrgUsersByOrgID(t.Context(), &organization.FindOrgMembersOpts{
ListOptions: db.ListOptions{},
OrgID: unittest.NonexistentID,
})
@@ -290,7 +290,7 @@ func TestChangeOrgUserStatus(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(orgID, userID int64, public bool) {
assert.NoError(t, organization.ChangeOrgUserStatus(db.DefaultContext, orgID, userID, public))
assert.NoError(t, organization.ChangeOrgUserStatus(t.Context(), orgID, userID, public))
orgUser := unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{OrgID: orgID, UID: userID})
assert.Equal(t, public, orgUser.IsPublic)
}
@@ -298,14 +298,14 @@ func TestChangeOrgUserStatus(t *testing.T) {
testSuccess(3, 2, false)
testSuccess(3, 2, false)
testSuccess(3, 4, true)
assert.NoError(t, organization.ChangeOrgUserStatus(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID, true))
assert.NoError(t, organization.ChangeOrgUserStatus(t.Context(), unittest.NonexistentID, unittest.NonexistentID, true))
}
func TestUser_GetUserTeamIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
testSuccess := func(userID int64, expected []int64) {
teamIDs, err := org.GetUserTeamIDs(db.DefaultContext, userID)
teamIDs, err := org.GetUserTeamIDs(t.Context(), userID)
assert.NoError(t, err)
assert.Equal(t, expected, teamIDs)
}
@@ -318,9 +318,9 @@ func TestAccessibleReposEnv_CountRepos(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
testSuccess := func(userID, expectedCount int64) {
env, err := repo_model.AccessibleReposEnv(db.DefaultContext, org, userID)
env, err := repo_model.AccessibleReposEnv(t.Context(), org, userID)
assert.NoError(t, err)
count, err := env.CountRepos(db.DefaultContext)
count, err := env.CountRepos(t.Context())
assert.NoError(t, err)
assert.Equal(t, expectedCount, count)
}
@@ -332,9 +332,9 @@ func TestAccessibleReposEnv_RepoIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
testSuccess := func(userID int64, expectedRepoIDs []int64) {
env, err := repo_model.AccessibleReposEnv(db.DefaultContext, org, userID)
env, err := repo_model.AccessibleReposEnv(t.Context(), org, userID)
assert.NoError(t, err)
repoIDs, err := env.RepoIDs(db.DefaultContext)
repoIDs, err := env.RepoIDs(t.Context())
assert.NoError(t, err)
assert.Equal(t, expectedRepoIDs, repoIDs)
}
@@ -346,9 +346,9 @@ func TestAccessibleReposEnv_MirrorRepos(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
testSuccess := func(userID int64, expectedRepoIDs []int64) {
env, err := repo_model.AccessibleReposEnv(db.DefaultContext, org, userID)
env, err := repo_model.AccessibleReposEnv(t.Context(), org, userID)
assert.NoError(t, err)
repos, err := env.MirrorRepos(db.DefaultContext)
repos, err := env.MirrorRepos(t.Context())
assert.NoError(t, err)
expectedRepos := make(repo_model.RepositoryList, len(expectedRepoIDs))
for i, repoID := range expectedRepoIDs {
@@ -373,12 +373,12 @@ func TestHasOrgVisibleTypePublic(t *testing.T) {
}
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner))
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner)
test2 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), org3)
test3 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), nil)
test1 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), owner)
test2 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), org3)
test3 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), nil)
assert.True(t, test1) // owner of org
assert.True(t, test2) // user not a part of org
assert.True(t, test3) // logged out user
@@ -396,12 +396,12 @@ func TestHasOrgVisibleTypeLimited(t *testing.T) {
}
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner))
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner)
test2 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), org3)
test3 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), nil)
test1 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), owner)
test2 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), org3)
test3 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), nil)
assert.True(t, test1) // owner of org
assert.True(t, test2) // user not a part of org
assert.False(t, test3) // logged out user
@@ -419,12 +419,12 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) {
}
unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization})
assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner))
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner)
test2 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), org3)
test3 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), nil)
test1 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), owner)
test2 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), org3)
test3 := organization.HasOrgOrUserVisible(t.Context(), org.AsUser(), nil)
assert.True(t, test1) // owner of org
assert.False(t, test2) // user not a part of org
assert.False(t, test3) // logged out user
@@ -433,7 +433,7 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) {
func TestGetUsersWhoCanCreateOrgRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
users, err := organization.GetUsersWhoCanCreateOrgRepo(db.DefaultContext, 3)
users, err := organization.GetUsersWhoCanCreateOrgRepo(t.Context(), 3)
assert.NoError(t, err)
assert.Len(t, users, 2)
var ids []int64
@@ -442,7 +442,7 @@ func TestGetUsersWhoCanCreateOrgRepo(t *testing.T) {
}
assert.ElementsMatch(t, ids, []int64{2, 28})
users, err = organization.GetUsersWhoCanCreateOrgRepo(db.DefaultContext, 7)
users, err = organization.GetUsersWhoCanCreateOrgRepo(t.Context(), 7)
assert.NoError(t, err)
assert.Len(t, users, 1)
assert.NotNil(t, users[5])
@@ -455,15 +455,15 @@ func TestUser_RemoveOrgRepo(t *testing.T) {
// remove a repo that does belong to org
unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{RepoID: repo.ID, OrgID: org.ID})
assert.NoError(t, organization.RemoveOrgRepo(db.DefaultContext, org.ID, repo.ID))
assert.NoError(t, organization.RemoveOrgRepo(t.Context(), org.ID, repo.ID))
unittest.AssertNotExistsBean(t, &organization.TeamRepo{RepoID: repo.ID, OrgID: org.ID})
unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID}) // repo should still exist
// remove a repo that does not belong to org
assert.NoError(t, organization.RemoveOrgRepo(db.DefaultContext, org.ID, repo.ID))
assert.NoError(t, organization.RemoveOrgRepo(t.Context(), org.ID, repo.ID))
unittest.AssertNotExistsBean(t, &organization.TeamRepo{RepoID: repo.ID, OrgID: org.ID})
assert.NoError(t, organization.RemoveOrgRepo(db.DefaultContext, org.ID, unittest.NonexistentID))
assert.NoError(t, organization.RemoveOrgRepo(t.Context(), org.ID, unittest.NonexistentID))
unittest.CheckConsistencyFor(t,
&user_model.User{ID: org.ID},
@@ -482,7 +482,7 @@ func TestCreateOrganization(t *testing.T) {
}
unittest.AssertNotExistsBean(t, &user_model.User{Name: newOrgName, Type: user_model.UserTypeOrganization})
assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner))
assert.NoError(t, organization.CreateOrganization(t.Context(), org, owner))
org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
ownerTeam := unittest.AssertExistsAndLoadBean(t,
@@ -502,7 +502,7 @@ func TestCreateOrganization2(t *testing.T) {
}
unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
err := organization.CreateOrganization(db.DefaultContext, org, owner)
err := organization.CreateOrganization(t.Context(), org, owner)
assert.Error(t, err)
assert.True(t, organization.IsErrUserNotAllowedCreateOrg(err))
unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
@@ -516,7 +516,7 @@ func TestCreateOrganization3(t *testing.T) {
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
org := &organization.Organization{Name: "org3"} // should already exist
unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: org.Name}) // sanity check
err := organization.CreateOrganization(db.DefaultContext, org, owner)
err := organization.CreateOrganization(t.Context(), org, owner)
assert.Error(t, err)
assert.True(t, user_model.IsErrUserAlreadyExist(err))
unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{})
@@ -527,7 +527,7 @@ func TestCreateOrganization4(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
err := organization.CreateOrganization(db.DefaultContext, &organization.Organization{Name: "assets"}, owner)
err := organization.CreateOrganization(t.Context(), &organization.Organization{Name: "assets"}, owner)
assert.Error(t, err)
assert.True(t, db.IsErrNameReserved(err))
unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{})

View File

@@ -7,7 +7,6 @@ import (
"fmt"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -37,9 +36,9 @@ func TestUserIsPublicMember(t *testing.T) {
}
func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) {
user, err := user_model.GetUserByID(db.DefaultContext, uid)
user, err := user_model.GetUserByID(t.Context(), uid)
assert.NoError(t, err)
is, err := organization.IsPublicMembership(db.DefaultContext, orgID, user.ID)
is, err := organization.IsPublicMembership(t.Context(), orgID, user.ID)
assert.NoError(t, err)
assert.Equal(t, expected, is)
}
@@ -65,9 +64,9 @@ func TestIsUserOrgOwner(t *testing.T) {
}
func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) {
user, err := user_model.GetUserByID(db.DefaultContext, uid)
user, err := user_model.GetUserByID(t.Context(), uid)
assert.NoError(t, err)
is, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, user.ID)
is, err := organization.IsOrganizationOwner(t.Context(), orgID, user.ID)
assert.NoError(t, err)
assert.Equal(t, expected, is)
}
@@ -92,9 +91,9 @@ func TestUserListIsPublicMember(t *testing.T) {
}
func testUserListIsPublicMember(t *testing.T, orgID int64, expected map[int64]bool) {
org, err := organization.GetOrgByID(db.DefaultContext, orgID)
org, err := organization.GetOrgByID(t.Context(), orgID)
assert.NoError(t, err)
_, membersIsPublic, err := org.GetMembers(db.DefaultContext, &user_model.User{IsAdmin: true})
_, membersIsPublic, err := org.GetMembers(t.Context(), &user_model.User{IsAdmin: true})
assert.NoError(t, err)
assert.Equal(t, expected, membersIsPublic)
}
@@ -119,11 +118,11 @@ func TestUserListIsUserOrgOwner(t *testing.T) {
}
func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bool) {
org, err := organization.GetOrgByID(db.DefaultContext, orgID)
org, err := organization.GetOrgByID(t.Context(), orgID)
assert.NoError(t, err)
members, _, err := org.GetMembers(db.DefaultContext, &user_model.User{IsAdmin: true})
members, _, err := org.GetMembers(t.Context(), &user_model.User{IsAdmin: true})
assert.NoError(t, err)
assert.Equal(t, expected, organization.IsUserOrgOwner(db.DefaultContext, members, orgID))
assert.Equal(t, expected, organization.IsUserOrgOwner(t.Context(), members, orgID))
}
func TestAddOrgUser(t *testing.T) {
@@ -134,7 +133,7 @@ func TestAddOrgUser(t *testing.T) {
if unittest.GetBean(t, &organization.OrgUser{OrgID: orgID, UID: userID}) == nil {
expectedNumMembers++
}
assert.NoError(t, organization.AddOrgUser(db.DefaultContext, orgID, userID))
assert.NoError(t, organization.AddOrgUser(t.Context(), orgID, userID))
ou := &organization.OrgUser{OrgID: orgID, UID: userID}
unittest.AssertExistsAndLoadBean(t, ou)
assert.Equal(t, isPublic, ou.IsPublic)

View File

@@ -4,6 +4,7 @@
package organization
import (
"context"
"sort"
"code.gitea.io/gitea/models/db"
@@ -16,8 +17,8 @@ type WorktimeSumByRepos struct {
SumTime int64
}
func GetWorktimeByRepos(org *Organization, unitFrom, unixTo int64) (results []WorktimeSumByRepos, err error) {
err = db.GetEngine(db.DefaultContext).
func GetWorktimeByRepos(ctx context.Context, org *Organization, unitFrom, unixTo int64) (results []WorktimeSumByRepos, err error) {
err = db.GetEngine(ctx).
Select("repository.name AS repo_name, SUM(tracked_time.time) AS sum_time").
Table("tracked_time").
Join("INNER", "issue", "tracked_time.issue_id = issue.id").
@@ -41,8 +42,8 @@ type WorktimeSumByMilestones struct {
HideRepoName bool
}
func GetWorktimeByMilestones(org *Organization, unitFrom, unixTo int64) (results []WorktimeSumByMilestones, err error) {
err = db.GetEngine(db.DefaultContext).
func GetWorktimeByMilestones(ctx context.Context, org *Organization, unitFrom, unixTo int64) (results []WorktimeSumByMilestones, err error) {
err = db.GetEngine(ctx).
Select("repository.name AS repo_name, milestone.name AS milestone_name, milestone.id AS milestone_id, milestone.deadline_unix as milestone_deadline, SUM(tracked_time.time) AS sum_time").
Table("tracked_time").
Join("INNER", "issue", "tracked_time.issue_id = issue.id").
@@ -85,8 +86,8 @@ type WorktimeSumByMembers struct {
SumTime int64
}
func GetWorktimeByMembers(org *Organization, unitFrom, unixTo int64) (results []WorktimeSumByMembers, err error) {
err = db.GetEngine(db.DefaultContext).
func GetWorktimeByMembers(ctx context.Context, org *Organization, unitFrom, unixTo int64) (results []WorktimeSumByMembers, err error) {
err = db.GetEngine(ctx).
Select("`user`.name AS user_name, SUM(tracked_time.time) AS sum_time").
Table("tracked_time").
Join("INNER", "issue", "tracked_time.issue_id = issue.id").

View File

@@ -6,7 +6,6 @@ package organization_test
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -23,26 +22,26 @@ func TestTeamInvite(t *testing.T) {
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
// user 2 already added to team 2, should result in error
_, err := organization.CreateTeamInvite(db.DefaultContext, user2, team, user2.Email)
_, err := organization.CreateTeamInvite(t.Context(), user2, team, user2.Email)
assert.Error(t, err)
})
t.Run("CreateAndRemove", func(t *testing.T) {
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
invite, err := organization.CreateTeamInvite(db.DefaultContext, user1, team, "org3@example.com")
invite, err := organization.CreateTeamInvite(t.Context(), user1, team, "org3@example.com")
assert.NotNil(t, invite)
assert.NoError(t, err)
// Shouldn't allow duplicate invite
_, err = organization.CreateTeamInvite(db.DefaultContext, user1, team, "org3@example.com")
_, err = organization.CreateTeamInvite(t.Context(), user1, team, "org3@example.com")
assert.Error(t, err)
// should remove invite
assert.NoError(t, organization.RemoveInviteByID(db.DefaultContext, invite.ID, invite.TeamID))
assert.NoError(t, organization.RemoveInviteByID(t.Context(), invite.ID, invite.TeamID))
// invite should not exist
_, err = organization.GetInviteByToken(db.DefaultContext, invite.Token)
_, err = organization.GetInviteByToken(t.Context(), invite.Token)
assert.Error(t, err)
})
}

View File

@@ -6,7 +6,6 @@ package organization_test
import (
"testing"
"code.gitea.io/gitea/models/db"
org_model "code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/unittest"
@@ -17,7 +16,7 @@ func Test_GetTeamsByIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
// 1 owner team, 2 normal team
teams, err := org_model.GetTeamsByIDs(db.DefaultContext, []int64{1, 2})
teams, err := org_model.GetTeamsByIDs(t.Context(), []int64{1, 2})
assert.NoError(t, err)
assert.Len(t, teams, 2)
assert.Equal(t, "Owners", teams[1].Name)

View File

@@ -6,7 +6,6 @@ package organization_test
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/organization"
"code.gitea.io/gitea/models/perm"
"code.gitea.io/gitea/models/repo"
@@ -22,7 +21,7 @@ func TestGetTeamsWithAccessToRepoUnit(t *testing.T) {
org41 := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 41})
repo61 := unittest.AssertExistsAndLoadBean(t, &repo.Repository{ID: 61})
teams, err := organization.GetTeamsWithAccessToAnyRepoUnit(db.DefaultContext, org41.ID, repo61.ID, perm.AccessModeRead, unit.TypePullRequests)
teams, err := organization.GetTeamsWithAccessToAnyRepoUnit(t.Context(), org41.ID, repo61.ID, perm.AccessModeRead, unit.TypePullRequests)
assert.NoError(t, err)
if assert.Len(t, teams, 2) {
assert.EqualValues(t, 21, teams[0].ID)

View File

@@ -28,14 +28,14 @@ func TestTeam_IsMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1})
assert.True(t, team.IsMember(db.DefaultContext, 2))
assert.False(t, team.IsMember(db.DefaultContext, 4))
assert.False(t, team.IsMember(db.DefaultContext, unittest.NonexistentID))
assert.True(t, team.IsMember(t.Context(), 2))
assert.False(t, team.IsMember(t.Context(), 4))
assert.False(t, team.IsMember(t.Context(), unittest.NonexistentID))
team = unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2})
assert.True(t, team.IsMember(db.DefaultContext, 2))
assert.True(t, team.IsMember(db.DefaultContext, 4))
assert.False(t, team.IsMember(db.DefaultContext, unittest.NonexistentID))
assert.True(t, team.IsMember(t.Context(), 2))
assert.True(t, team.IsMember(t.Context(), 4))
assert.False(t, team.IsMember(t.Context(), unittest.NonexistentID))
}
func TestTeam_GetRepositories(t *testing.T) {
@@ -43,7 +43,7 @@ func TestTeam_GetRepositories(t *testing.T) {
test := func(teamID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
repos, err := repo_model.GetTeamRepositories(db.DefaultContext, &repo_model.SearchTeamRepoOptions{
repos, err := repo_model.GetTeamRepositories(t.Context(), &repo_model.SearchTeamRepoOptions{
TeamID: team.ID,
})
assert.NoError(t, err)
@@ -61,7 +61,7 @@ func TestTeam_GetMembers(t *testing.T) {
test := func(teamID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
assert.NoError(t, team.LoadMembers(db.DefaultContext))
assert.NoError(t, team.LoadMembers(t.Context()))
assert.Len(t, team.Members, team.NumMembers)
for _, member := range team.Members {
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID})
@@ -75,7 +75,7 @@ func TestGetTeam(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(orgID int64, name string) {
team, err := organization.GetTeam(db.DefaultContext, orgID, name)
team, err := organization.GetTeam(t.Context(), orgID, name)
assert.NoError(t, err)
assert.Equal(t, orgID, team.OrgID)
assert.Equal(t, name, team.Name)
@@ -83,9 +83,9 @@ func TestGetTeam(t *testing.T) {
testSuccess(3, "Owners")
testSuccess(3, "team1")
_, err := organization.GetTeam(db.DefaultContext, 3, "nonexistent")
_, err := organization.GetTeam(t.Context(), 3, "nonexistent")
assert.Error(t, err)
_, err = organization.GetTeam(db.DefaultContext, unittest.NonexistentID, "Owners")
_, err = organization.GetTeam(t.Context(), unittest.NonexistentID, "Owners")
assert.Error(t, err)
}
@@ -93,7 +93,7 @@ func TestGetTeamByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(teamID int64) {
team, err := organization.GetTeamByID(db.DefaultContext, teamID)
team, err := organization.GetTeamByID(t.Context(), teamID)
assert.NoError(t, err)
assert.Equal(t, teamID, team.ID)
}
@@ -102,14 +102,14 @@ func TestGetTeamByID(t *testing.T) {
testSuccess(3)
testSuccess(4)
_, err := organization.GetTeamByID(db.DefaultContext, unittest.NonexistentID)
_, err := organization.GetTeamByID(t.Context(), unittest.NonexistentID)
assert.Error(t, err)
}
func TestIsTeamMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(orgID, teamID, userID int64, expected bool) {
isMember, err := organization.IsTeamMember(db.DefaultContext, orgID, teamID, userID)
isMember, err := organization.IsTeamMember(t.Context(), orgID, teamID, userID)
assert.NoError(t, err)
assert.Equal(t, expected, isMember)
}
@@ -130,7 +130,7 @@ func TestGetTeamMembers(t *testing.T) {
test := func(teamID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
members, err := organization.GetTeamMembers(db.DefaultContext, &organization.SearchMembersOptions{
members, err := organization.GetTeamMembers(t.Context(), &organization.SearchMembersOptions{
TeamID: teamID,
})
assert.NoError(t, err)
@@ -146,7 +146,7 @@ func TestGetTeamMembers(t *testing.T) {
func TestGetUserTeams(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(userID int64) {
teams, _, err := organization.SearchTeam(db.DefaultContext, &organization.SearchTeamOptions{UserID: userID})
teams, _, err := organization.SearchTeam(t.Context(), &organization.SearchTeamOptions{UserID: userID})
assert.NoError(t, err)
for _, team := range teams {
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{TeamID: team.ID, UID: userID})
@@ -160,7 +160,7 @@ func TestGetUserTeams(t *testing.T) {
func TestGetUserOrgTeams(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(orgID, userID int64) {
teams, err := organization.GetUserOrgTeams(db.DefaultContext, orgID, userID)
teams, err := organization.GetUserOrgTeams(t.Context(), orgID, userID)
assert.NoError(t, err)
for _, team := range teams {
assert.Equal(t, orgID, team.OrgID)
@@ -177,7 +177,7 @@ func TestHasTeamRepo(t *testing.T) {
test := func(teamID, repoID int64, expected bool) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
assert.Equal(t, expected, organization.HasTeamRepo(db.DefaultContext, team.OrgID, teamID, repoID))
assert.Equal(t, expected, organization.HasTeamRepo(t.Context(), team.OrgID, teamID, repoID))
}
test(1, 1, false)
test(1, 3, true)
@@ -192,7 +192,7 @@ func TestUsersInTeamsCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(teamIDs, userIDs []int64, expected int64) {
count, err := organization.UsersInTeamsCount(db.DefaultContext, teamIDs, userIDs)
count, err := organization.UsersInTeamsCount(t.Context(), teamIDs, userIDs)
assert.NoError(t, err)
assert.Equal(t, expected, count)
}

View File

@@ -6,7 +6,6 @@ package packages_test
import (
"testing"
"code.gitea.io/gitea/models/db"
packages_model "code.gitea.io/gitea/models/packages"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -27,7 +26,7 @@ func TestHasOwnerPackages(t *testing.T) {
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
p, err := packages_model.TryInsertPackage(db.DefaultContext, &packages_model.Package{
p, err := packages_model.TryInsertPackage(t.Context(), &packages_model.Package{
OwnerID: owner.ID,
LowerName: "package",
})
@@ -35,11 +34,11 @@ func TestHasOwnerPackages(t *testing.T) {
assert.NoError(t, err)
// A package without package versions gets automatically cleaned up and should return false
has, err := packages_model.HasOwnerPackages(db.DefaultContext, owner.ID)
has, err := packages_model.HasOwnerPackages(t.Context(), owner.ID)
assert.False(t, has)
assert.NoError(t, err)
pv, err := packages_model.GetOrInsertVersion(db.DefaultContext, &packages_model.PackageVersion{
pv, err := packages_model.GetOrInsertVersion(t.Context(), &packages_model.PackageVersion{
PackageID: p.ID,
LowerVersion: "internal",
IsInternal: true,
@@ -48,11 +47,11 @@ func TestHasOwnerPackages(t *testing.T) {
assert.NoError(t, err)
// A package with an internal package version gets automatically cleaned up and should return false
has, err = packages_model.HasOwnerPackages(db.DefaultContext, owner.ID)
has, err = packages_model.HasOwnerPackages(t.Context(), owner.ID)
assert.False(t, has)
assert.NoError(t, err)
pv, err = packages_model.GetOrInsertVersion(db.DefaultContext, &packages_model.PackageVersion{
pv, err = packages_model.GetOrInsertVersion(t.Context(), &packages_model.PackageVersion{
PackageID: p.ID,
LowerVersion: "normal",
IsInternal: false,
@@ -61,7 +60,7 @@ func TestHasOwnerPackages(t *testing.T) {
assert.NoError(t, err)
// A package with a normal package version should return true
has, err = packages_model.HasOwnerPackages(db.DefaultContext, owner.ID)
has, err = packages_model.HasOwnerPackages(t.Context(), owner.ID)
assert.True(t, has)
assert.NoError(t, err)
}

View File

@@ -35,34 +35,34 @@ func TestAccessLevel(t *testing.T) {
// org. owned private repo
repo24 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 24})
level, err := access_model.AccessLevel(db.DefaultContext, user2, repo1)
level, err := access_model.AccessLevel(t.Context(), user2, repo1)
assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeOwner, level)
level, err = access_model.AccessLevel(db.DefaultContext, user2, repo3)
level, err = access_model.AccessLevel(t.Context(), user2, repo3)
assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeOwner, level)
level, err = access_model.AccessLevel(db.DefaultContext, user5, repo1)
level, err = access_model.AccessLevel(t.Context(), user5, repo1)
assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeRead, level)
level, err = access_model.AccessLevel(db.DefaultContext, user5, repo3)
level, err = access_model.AccessLevel(t.Context(), user5, repo3)
assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeNone, level)
// restricted user has no access to a public repo
level, err = access_model.AccessLevel(db.DefaultContext, user29, repo1)
level, err = access_model.AccessLevel(t.Context(), user29, repo1)
assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeNone, level)
// ... unless he's a collaborator
level, err = access_model.AccessLevel(db.DefaultContext, user29, repo4)
level, err = access_model.AccessLevel(t.Context(), user29, repo4)
assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeWrite, level)
// ... or a team member
level, err = access_model.AccessLevel(db.DefaultContext, user29, repo24)
level, err = access_model.AccessLevel(t.Context(), user29, repo24)
assert.NoError(t, err)
assert.Equal(t, perm_model.AccessModeRead, level)
}
@@ -79,17 +79,17 @@ func TestHasAccess(t *testing.T) {
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
assert.True(t, repo2.IsPrivate)
has, err := access_model.HasAnyUnitAccess(db.DefaultContext, user1.ID, repo1)
has, err := access_model.HasAnyUnitAccess(t.Context(), user1.ID, repo1)
assert.NoError(t, err)
assert.True(t, has)
_, err = access_model.HasAnyUnitAccess(db.DefaultContext, user1.ID, repo2)
_, err = access_model.HasAnyUnitAccess(t.Context(), user1.ID, repo2)
assert.NoError(t, err)
_, err = access_model.HasAnyUnitAccess(db.DefaultContext, user2.ID, repo1)
_, err = access_model.HasAnyUnitAccess(t.Context(), user2.ID, repo1)
assert.NoError(t, err)
_, err = access_model.HasAnyUnitAccess(db.DefaultContext, user2.ID, repo2)
_, err = access_model.HasAnyUnitAccess(t.Context(), user2.ID, repo2)
assert.NoError(t, err)
}
@@ -97,14 +97,14 @@ func TestRepository_RecalculateAccesses(t *testing.T) {
// test with organization repo
assert.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
assert.NoError(t, repo1.LoadOwner(db.DefaultContext))
assert.NoError(t, repo1.LoadOwner(t.Context()))
_, err := db.GetEngine(db.DefaultContext).Delete(&repo_model.Collaboration{UserID: 2, RepoID: 3})
_, err := db.GetEngine(t.Context()).Delete(&repo_model.Collaboration{UserID: 2, RepoID: 3})
assert.NoError(t, err)
assert.NoError(t, access_model.RecalculateAccesses(db.DefaultContext, repo1))
assert.NoError(t, access_model.RecalculateAccesses(t.Context(), repo1))
access := &access_model.Access{UserID: 2, RepoID: 3}
has, err := db.GetEngine(db.DefaultContext).Get(access)
has, err := db.GetEngine(t.Context()).Get(access)
assert.NoError(t, err)
assert.True(t, has)
assert.Equal(t, perm_model.AccessModeOwner, access.Mode)
@@ -114,13 +114,13 @@ func TestRepository_RecalculateAccesses2(t *testing.T) {
// test with non-organization repo
assert.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
assert.NoError(t, repo1.LoadOwner(db.DefaultContext))
assert.NoError(t, repo1.LoadOwner(t.Context()))
_, err := db.GetEngine(db.DefaultContext).Delete(&repo_model.Collaboration{UserID: 4, RepoID: 4})
_, err := db.GetEngine(t.Context()).Delete(&repo_model.Collaboration{UserID: 4, RepoID: 4})
assert.NoError(t, err)
assert.NoError(t, access_model.RecalculateAccesses(db.DefaultContext, repo1))
assert.NoError(t, access_model.RecalculateAccesses(t.Context(), repo1))
has, err := db.GetEngine(db.DefaultContext).Get(&access_model.Access{UserID: 4, RepoID: 4})
has, err := db.GetEngine(t.Context()).Get(&access_model.Access{UserID: 4, RepoID: 4})
assert.NoError(t, err)
assert.False(t, has)
}

View File

@@ -7,7 +7,6 @@ import (
"fmt"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert"
@@ -16,29 +15,29 @@ import (
func TestGetDefaultColumn(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
projectWithoutDefault, err := GetProjectByID(db.DefaultContext, 5)
projectWithoutDefault, err := GetProjectByID(t.Context(), 5)
assert.NoError(t, err)
// check if default column was added
column, err := projectWithoutDefault.MustDefaultColumn(db.DefaultContext)
column, err := projectWithoutDefault.MustDefaultColumn(t.Context())
assert.NoError(t, err)
assert.Equal(t, int64(5), column.ProjectID)
assert.Equal(t, "Done", column.Title)
projectWithMultipleDefaults, err := GetProjectByID(db.DefaultContext, 6)
projectWithMultipleDefaults, err := GetProjectByID(t.Context(), 6)
assert.NoError(t, err)
// check if multiple defaults were removed
column, err = projectWithMultipleDefaults.MustDefaultColumn(db.DefaultContext)
column, err = projectWithMultipleDefaults.MustDefaultColumn(t.Context())
assert.NoError(t, err)
assert.Equal(t, int64(6), column.ProjectID)
assert.Equal(t, int64(9), column.ID) // there are 2 default columns in the test data, use the latest one
// set 8 as default column
assert.NoError(t, SetDefaultColumn(db.DefaultContext, column.ProjectID, 8))
assert.NoError(t, SetDefaultColumn(t.Context(), column.ProjectID, 8))
// then 9 will become a non-default column
column, err = GetColumn(db.DefaultContext, 9)
column, err = GetColumn(t.Context(), 9)
assert.NoError(t, err)
assert.Equal(t, int64(6), column.ProjectID)
assert.False(t, column.Default)
@@ -49,25 +48,25 @@ func Test_moveIssuesToAnotherColumn(t *testing.T) {
column1 := unittest.AssertExistsAndLoadBean(t, &Column{ID: 1, ProjectID: 1})
issues, err := column1.GetIssues(db.DefaultContext)
issues, err := column1.GetIssues(t.Context())
assert.NoError(t, err)
assert.Len(t, issues, 1)
assert.EqualValues(t, 1, issues[0].ID)
column2 := unittest.AssertExistsAndLoadBean(t, &Column{ID: 2, ProjectID: 1})
issues, err = column2.GetIssues(db.DefaultContext)
issues, err = column2.GetIssues(t.Context())
assert.NoError(t, err)
assert.Len(t, issues, 1)
assert.EqualValues(t, 3, issues[0].ID)
err = column1.moveIssuesToAnotherColumn(db.DefaultContext, column2)
err = column1.moveIssuesToAnotherColumn(t.Context(), column2)
assert.NoError(t, err)
issues, err = column1.GetIssues(db.DefaultContext)
issues, err = column1.GetIssues(t.Context())
assert.NoError(t, err)
assert.Empty(t, issues)
issues, err = column2.GetIssues(db.DefaultContext)
issues, err = column2.GetIssues(t.Context())
assert.NoError(t, err)
assert.Len(t, issues, 2)
assert.EqualValues(t, 3, issues[0].ID)
@@ -80,21 +79,21 @@ func Test_MoveColumnsOnProject(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
project1 := unittest.AssertExistsAndLoadBean(t, &Project{ID: 1})
columns, err := project1.GetColumns(db.DefaultContext)
columns, err := project1.GetColumns(t.Context())
assert.NoError(t, err)
assert.Len(t, columns, 3)
assert.EqualValues(t, 0, columns[0].Sorting) // even if there is no default sorting, the code should also work
assert.EqualValues(t, 0, columns[1].Sorting)
assert.EqualValues(t, 0, columns[2].Sorting)
err = MoveColumnsOnProject(db.DefaultContext, project1, map[int64]int64{
err = MoveColumnsOnProject(t.Context(), project1, map[int64]int64{
0: columns[1].ID,
1: columns[2].ID,
2: columns[0].ID,
})
assert.NoError(t, err)
columnsAfter, err := project1.GetColumns(db.DefaultContext)
columnsAfter, err := project1.GetColumns(t.Context())
assert.NoError(t, err)
assert.Len(t, columnsAfter, 3)
assert.Equal(t, columns[1].ID, columnsAfter[0].ID)
@@ -106,18 +105,18 @@ func Test_NewColumn(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
project1 := unittest.AssertExistsAndLoadBean(t, &Project{ID: 1})
columns, err := project1.GetColumns(db.DefaultContext)
columns, err := project1.GetColumns(t.Context())
assert.NoError(t, err)
assert.Len(t, columns, 3)
for i := range maxProjectColumns - 3 {
err := NewColumn(db.DefaultContext, &Column{
err := NewColumn(t.Context(), &Column{
Title: fmt.Sprintf("column-%d", i+4),
ProjectID: project1.ID,
})
assert.NoError(t, err)
}
err = NewColumn(db.DefaultContext, &Column{
err = NewColumn(t.Context(), &Column{
Title: "column-21",
ProjectID: project1.ID,
})

View File

@@ -34,13 +34,13 @@ func TestIsProjectTypeValid(t *testing.T) {
func TestGetProjects(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
projects, err := db.Find[Project](db.DefaultContext, SearchOptions{RepoID: 1})
projects, err := db.Find[Project](t.Context(), SearchOptions{RepoID: 1})
assert.NoError(t, err)
// 1 value for this repo exists in the fixtures
assert.Len(t, projects, 1)
projects, err = db.Find[Project](db.DefaultContext, SearchOptions{RepoID: 3})
projects, err = db.Find[Project](t.Context(), SearchOptions{RepoID: 3})
assert.NoError(t, err)
// 1 value for this repo exists in the fixtures
@@ -60,24 +60,24 @@ func TestProject(t *testing.T) {
CreatorID: 2,
}
assert.NoError(t, NewProject(db.DefaultContext, project))
assert.NoError(t, NewProject(t.Context(), project))
_, err := GetProjectByID(db.DefaultContext, project.ID)
_, err := GetProjectByID(t.Context(), project.ID)
assert.NoError(t, err)
// Update project
project.Title = "Updated title"
assert.NoError(t, UpdateProject(db.DefaultContext, project))
assert.NoError(t, UpdateProject(t.Context(), project))
projectFromDB, err := GetProjectByID(db.DefaultContext, project.ID)
projectFromDB, err := GetProjectByID(t.Context(), project.ID)
assert.NoError(t, err)
assert.Equal(t, project.Title, projectFromDB.Title)
assert.NoError(t, ChangeProjectStatus(db.DefaultContext, project, true))
assert.NoError(t, ChangeProjectStatus(t.Context(), project, true))
// Retrieve from DB afresh to check if it is truly closed
projectFromDB, err = GetProjectByID(db.DefaultContext, project.ID)
projectFromDB, err = GetProjectByID(t.Context(), project.ID)
assert.NoError(t, err)
assert.True(t, projectFromDB.IsClosed)
@@ -109,7 +109,7 @@ func TestProjectsSort(t *testing.T) {
}
for _, tt := range tests {
projects, count, err := db.FindAndCount[Project](db.DefaultContext, SearchOptions{
projects, count, err := db.FindAndCount[Project](t.Context(), SearchOptions{
OrderBy: GetSearchOrderByBySortType(tt.sortType),
})
assert.NoError(t, err)

View File

@@ -6,7 +6,6 @@ package repo_test
import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
@@ -16,15 +15,15 @@ import (
func TestIncreaseDownloadCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11")
attachment, err := repo_model.GetAttachmentByUUID(t.Context(), "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11")
assert.NoError(t, err)
assert.Equal(t, int64(0), attachment.DownloadCount)
// increase download count
err = attachment.IncreaseDownloadCount(db.DefaultContext)
err = attachment.IncreaseDownloadCount(t.Context())
assert.NoError(t, err)
attachment, err = repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11")
attachment, err = repo_model.GetAttachmentByUUID(t.Context(), "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11")
assert.NoError(t, err)
assert.Equal(t, int64(1), attachment.DownloadCount)
}
@@ -33,11 +32,11 @@ func TestGetByCommentOrIssueID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
// count of attachments from issue ID
attachments, err := repo_model.GetAttachmentsByIssueID(db.DefaultContext, 1)
attachments, err := repo_model.GetAttachmentsByIssueID(t.Context(), 1)
assert.NoError(t, err)
assert.Len(t, attachments, 1)
attachments, err = repo_model.GetAttachmentsByCommentID(db.DefaultContext, 1)
attachments, err = repo_model.GetAttachmentsByCommentID(t.Context(), 1)
assert.NoError(t, err)
assert.Len(t, attachments, 2)
}
@@ -45,18 +44,18 @@ func TestGetByCommentOrIssueID(t *testing.T) {
func TestDeleteAttachments(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
count, err := repo_model.DeleteAttachmentsByIssue(db.DefaultContext, 4, false)
count, err := repo_model.DeleteAttachmentsByIssue(t.Context(), 4, false)
assert.NoError(t, err)
assert.Equal(t, 2, count)
count, err = repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false)
count, err = repo_model.DeleteAttachmentsByComment(t.Context(), 2, false)
assert.NoError(t, err)
assert.Equal(t, 2, count)
err = repo_model.DeleteAttachment(db.DefaultContext, &repo_model.Attachment{ID: 8}, false)
err = repo_model.DeleteAttachment(t.Context(), &repo_model.Attachment{ID: 8}, false)
assert.NoError(t, err)
attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18")
attachment, err := repo_model.GetAttachmentByUUID(t.Context(), "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18")
assert.Error(t, err)
assert.True(t, repo_model.IsErrAttachmentNotExist(err))
assert.Nil(t, attachment)
@@ -65,7 +64,7 @@ func TestDeleteAttachments(t *testing.T) {
func TestGetAttachmentByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
attach, err := repo_model.GetAttachmentByID(db.DefaultContext, 1)
attach, err := repo_model.GetAttachmentByID(t.Context(), 1)
assert.NoError(t, err)
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID)
}
@@ -81,12 +80,12 @@ func TestAttachment_DownloadURL(t *testing.T) {
func TestUpdateAttachment(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
attach, err := repo_model.GetAttachmentByID(db.DefaultContext, 1)
attach, err := repo_model.GetAttachmentByID(t.Context(), 1)
assert.NoError(t, err)
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID)
attach.Name = "new_name"
assert.NoError(t, repo_model.UpdateAttachment(db.DefaultContext, attach))
assert.NoError(t, repo_model.UpdateAttachment(t.Context(), attach))
unittest.AssertExistsAndLoadBean(t, &repo_model.Attachment{Name: "new_name"})
}
@@ -94,7 +93,7 @@ func TestUpdateAttachment(t *testing.T) {
func TestGetAttachmentsByUUIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
attachList, err := repo_model.GetAttachmentsByUUIDs(db.DefaultContext, []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"})
attachList, err := repo_model.GetAttachmentsByUUIDs(t.Context(), []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)

View File

@@ -6,7 +6,6 @@ package repo
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
@@ -18,11 +17,11 @@ func TestRepoAvatarLink(t *testing.T) {
defer test.MockVariableValue(&setting.AppSubURL, "")()
repo := &Repository{ID: 1, Avatar: "avatar.png"}
link := repo.AvatarLink(db.DefaultContext)
link := repo.AvatarLink(t.Context())
assert.Equal(t, "https://localhost/repo-avatars/avatar.png", link)
setting.AppURL = "https://localhost/sub-path/"
setting.AppSubURL = "/sub-path"
link = repo.AvatarLink(db.DefaultContext)
link = repo.AvatarLink(t.Context())
assert.Equal(t, "https://localhost/sub-path/repo-avatars/avatar.png", link)
}

View File

@@ -19,9 +19,9 @@ func TestRepository_GetCollaborators(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
collaborators, _, err := repo_model.GetCollaborators(db.DefaultContext, &repo_model.FindCollaborationOptions{RepoID: repo.ID})
collaborators, _, err := repo_model.GetCollaborators(t.Context(), &repo_model.FindCollaborationOptions{RepoID: repo.ID})
assert.NoError(t, err)
expectedLen, err := db.GetEngine(db.DefaultContext).Count(&repo_model.Collaboration{RepoID: repoID})
expectedLen, err := db.GetEngine(t.Context()).Count(&repo_model.Collaboration{RepoID: repoID})
assert.NoError(t, err)
assert.Len(t, collaborators, int(expectedLen))
for _, collaborator := range collaborators {
@@ -37,14 +37,14 @@ func TestRepository_GetCollaborators(t *testing.T) {
// Test db.ListOptions
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 22})
collaborators1, _, err := repo_model.GetCollaborators(db.DefaultContext, &repo_model.FindCollaborationOptions{
collaborators1, _, err := repo_model.GetCollaborators(t.Context(), &repo_model.FindCollaborationOptions{
ListOptions: db.ListOptions{PageSize: 1, Page: 1},
RepoID: repo.ID,
})
assert.NoError(t, err)
assert.Len(t, collaborators1, 1)
collaborators2, _, err := repo_model.GetCollaborators(db.DefaultContext, &repo_model.FindCollaborationOptions{
collaborators2, _, err := repo_model.GetCollaborators(t.Context(), &repo_model.FindCollaborationOptions{
ListOptions: db.ListOptions{PageSize: 1, Page: 2},
RepoID: repo.ID,
})
@@ -59,7 +59,7 @@ func TestRepository_IsCollaborator(t *testing.T) {
test := func(repoID, userID int64, expected bool) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
actual, err := repo_model.IsCollaborator(db.DefaultContext, repo.ID, userID)
actual, err := repo_model.IsCollaborator(t.Context(), repo.ID, userID)
assert.NoError(t, err)
assert.Equal(t, expected, actual)
}
@@ -73,7 +73,7 @@ func TestRepository_ChangeCollaborationAccessMode(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessModeAdmin))
assert.NoError(t, repo_model.ChangeCollaborationAccessMode(t.Context(), repo, 4, perm.AccessModeAdmin))
collaboration := unittest.AssertExistsAndLoadBean(t, &repo_model.Collaboration{RepoID: repo.ID, UserID: 4})
assert.Equal(t, perm.AccessModeAdmin, collaboration.Mode)
@@ -81,12 +81,12 @@ func TestRepository_ChangeCollaborationAccessMode(t *testing.T) {
access := unittest.AssertExistsAndLoadBean(t, &access_model.Access{UserID: 4, RepoID: repo.ID})
assert.Equal(t, perm.AccessModeAdmin, access.Mode)
assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessModeAdmin))
assert.NoError(t, repo_model.ChangeCollaborationAccessMode(t.Context(), repo, 4, perm.AccessModeAdmin))
assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, unittest.NonexistentID, perm.AccessModeAdmin))
assert.NoError(t, repo_model.ChangeCollaborationAccessMode(t.Context(), repo, unittest.NonexistentID, perm.AccessModeAdmin))
// Discard invalid input.
assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessMode(-1)))
assert.NoError(t, repo_model.ChangeCollaborationAccessMode(t.Context(), repo, 4, perm.AccessMode(-1)))
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID})
}
@@ -97,31 +97,31 @@ func TestRepository_IsOwnerMemberCollaborator(t *testing.T) {
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
// Organisation owner.
actual, err := repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 2)
actual, err := repo_model.IsOwnerMemberCollaborator(t.Context(), repo1, 2)
assert.NoError(t, err)
assert.True(t, actual)
// Team member.
actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 4)
actual, err = repo_model.IsOwnerMemberCollaborator(t.Context(), repo1, 4)
assert.NoError(t, err)
assert.True(t, actual)
// Normal user.
actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 1)
actual, err = repo_model.IsOwnerMemberCollaborator(t.Context(), repo1, 1)
assert.NoError(t, err)
assert.False(t, actual)
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
// Collaborator.
actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo2, 4)
actual, err = repo_model.IsOwnerMemberCollaborator(t.Context(), repo2, 4)
assert.NoError(t, err)
assert.True(t, actual)
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 15})
// Repository owner.
actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo3, 2)
actual, err = repo_model.IsOwnerMemberCollaborator(t.Context(), repo3, 2)
assert.NoError(t, err)
assert.True(t, actual)
}
@@ -132,14 +132,14 @@ func TestRepo_GetCollaboration(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
// Existing collaboration.
collab, err := repo_model.GetCollaboration(db.DefaultContext, repo.ID, 4)
collab, err := repo_model.GetCollaboration(t.Context(), repo.ID, 4)
assert.NoError(t, err)
assert.NotNil(t, collab)
assert.EqualValues(t, 4, collab.UserID)
assert.EqualValues(t, 4, collab.RepoID)
// Non-existing collaboration.
collab, err = repo_model.GetCollaboration(db.DefaultContext, repo.ID, 1)
collab, err = repo_model.GetCollaboration(t.Context(), repo.ID, 1)
assert.NoError(t, err)
assert.Nil(t, collab)
}

View File

@@ -6,7 +6,6 @@ package repo_test
import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
@@ -17,17 +16,17 @@ func TestGetUserFork(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
// User13 has repo 11 forked from repo10
repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 10)
repo, err := repo_model.GetRepositoryByID(t.Context(), 10)
assert.NoError(t, err)
assert.NotNil(t, repo)
repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13)
repo, err = repo_model.GetUserFork(t.Context(), repo.ID, 13)
assert.NoError(t, err)
assert.NotNil(t, repo)
repo, err = repo_model.GetRepositoryByID(db.DefaultContext, 9)
repo, err = repo_model.GetRepositoryByID(t.Context(), 9)
assert.NoError(t, err)
assert.NotNil(t, repo)
repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13)
repo, err = repo_model.GetUserFork(t.Context(), repo.ID, 13)
assert.NoError(t, err)
assert.Nil(t, repo)
}

View File

@@ -20,26 +20,26 @@ func TestPushMirrorsIterate(t *testing.T) {
now := timeutil.TimeStampNow()
db.Insert(db.DefaultContext, &repo_model.PushMirror{
db.Insert(t.Context(), &repo_model.PushMirror{
RemoteName: "test-1",
LastUpdateUnix: now,
Interval: 1,
})
long, _ := time.ParseDuration("24h")
db.Insert(db.DefaultContext, &repo_model.PushMirror{
db.Insert(t.Context(), &repo_model.PushMirror{
RemoteName: "test-2",
LastUpdateUnix: now,
Interval: long,
})
db.Insert(db.DefaultContext, &repo_model.PushMirror{
db.Insert(t.Context(), &repo_model.PushMirror{
RemoteName: "test-3",
LastUpdateUnix: now,
Interval: 0,
})
repo_model.PushMirrorsIterate(db.DefaultContext, 1, func(idx int, bean any) error {
repo_model.PushMirrorsIterate(t.Context(), 1, func(idx int, bean any) error {
m, ok := bean.(*repo_model.PushMirror)
assert.True(t, ok)
assert.Equal(t, "test-1", m.RemoteName)

View File

@@ -6,7 +6,6 @@ package repo_test
import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
@@ -16,11 +15,11 @@ import (
func TestLookupRedirect(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repoID, err := repo_model.LookupRedirect(db.DefaultContext, 2, "oldrepo1")
repoID, err := repo_model.LookupRedirect(t.Context(), 2, "oldrepo1")
assert.NoError(t, err)
assert.EqualValues(t, 1, repoID)
_, err = repo_model.LookupRedirect(db.DefaultContext, unittest.NonexistentID, "doesnotexist")
_, err = repo_model.LookupRedirect(t.Context(), unittest.NonexistentID, "doesnotexist")
assert.True(t, repo_model.IsErrRedirectNotExist(err))
}
@@ -29,7 +28,7 @@ func TestNewRedirect(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
assert.NoError(t, repo_model.NewRedirect(db.DefaultContext, repo.OwnerID, repo.ID, repo.Name, "newreponame"))
assert.NoError(t, repo_model.NewRedirect(t.Context(), repo.OwnerID, repo.ID, repo.Name, "newreponame"))
unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
OwnerID: repo.OwnerID,
@@ -48,7 +47,7 @@ func TestNewRedirect2(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
assert.NoError(t, repo_model.NewRedirect(db.DefaultContext, repo.OwnerID, repo.ID, repo.Name, "oldrepo1"))
assert.NoError(t, repo_model.NewRedirect(t.Context(), repo.OwnerID, repo.ID, repo.Name, "oldrepo1"))
unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
OwnerID: repo.OwnerID,
@@ -67,7 +66,7 @@ func TestNewRedirect3(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
assert.NoError(t, repo_model.NewRedirect(db.DefaultContext, repo.OwnerID, repo.ID, repo.Name, "newreponame"))
assert.NoError(t, repo_model.NewRedirect(t.Context(), repo.OwnerID, repo.ID, repo.Name, "newreponame"))
unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
OwnerID: repo.OwnerID,

View File

@@ -6,7 +6,6 @@ package repo
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert"
@@ -22,14 +21,14 @@ func TestMigrate_InsertReleases(t *testing.T) {
Attachments: []*Attachment{a},
}
err := InsertReleases(db.DefaultContext, r)
err := InsertReleases(t.Context(), r)
assert.NoError(t, err)
}
func Test_FindTagsByCommitIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
sha1Rels, err := FindTagsByCommitIDs(db.DefaultContext, 1, "65f1bf27bc3bf70f64657658635e66094edbcb4d")
sha1Rels, err := FindTagsByCommitIDs(t.Context(), 1, "65f1bf27bc3bf70f64657658635e66094edbcb4d")
assert.NoError(t, err)
assert.Len(t, sha1Rels, 1)
rels := sha1Rels["65f1bf27bc3bf70f64657658635e66094edbcb4d"]

View File

@@ -184,7 +184,7 @@ func TestSearchRepository(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
// test search public repository on explore page
repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, repo_model.SearchRepoOptions{
repos, count, err := repo_model.SearchRepositoryByName(t.Context(), repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
Page: 1,
PageSize: 10,
@@ -199,7 +199,7 @@ func TestSearchRepository(t *testing.T) {
}
assert.Equal(t, int64(1), count)
repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, repo_model.SearchRepoOptions{
repos, count, err = repo_model.SearchRepositoryByName(t.Context(), repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
Page: 1,
PageSize: 10,
@@ -213,7 +213,7 @@ func TestSearchRepository(t *testing.T) {
assert.Len(t, repos, 2)
// test search private repository on explore page
repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, repo_model.SearchRepoOptions{
repos, count, err = repo_model.SearchRepositoryByName(t.Context(), repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
Page: 1,
PageSize: 10,
@@ -229,7 +229,7 @@ func TestSearchRepository(t *testing.T) {
}
assert.Equal(t, int64(1), count)
repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, repo_model.SearchRepoOptions{
repos, count, err = repo_model.SearchRepositoryByName(t.Context(), repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
Page: 1,
PageSize: 10,
@@ -244,14 +244,14 @@ func TestSearchRepository(t *testing.T) {
assert.Len(t, repos, 3)
// Test non existing owner
repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, repo_model.SearchRepoOptions{OwnerID: unittest.NonexistentID})
repos, count, err = repo_model.SearchRepositoryByName(t.Context(), repo_model.SearchRepoOptions{OwnerID: unittest.NonexistentID})
assert.NoError(t, err)
assert.Empty(t, repos)
assert.Equal(t, int64(0), count)
// Test search within description
repos, count, err = repo_model.SearchRepository(db.DefaultContext, repo_model.SearchRepoOptions{
repos, count, err = repo_model.SearchRepository(t.Context(), repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
Page: 1,
PageSize: 10,
@@ -268,7 +268,7 @@ func TestSearchRepository(t *testing.T) {
assert.Equal(t, int64(1), count)
// Test NOT search within description
repos, count, err = repo_model.SearchRepository(db.DefaultContext, repo_model.SearchRepoOptions{
repos, count, err = repo_model.SearchRepository(t.Context(), repo_model.SearchRepoOptions{
ListOptions: db.ListOptions{
Page: 1,
PageSize: 10,
@@ -286,7 +286,7 @@ func TestSearchRepository(t *testing.T) {
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts)
repos, count, err := repo_model.SearchRepositoryByName(t.Context(), testCase.opts)
assert.NoError(t, err)
assert.Equal(t, int64(testCase.count), count)
@@ -361,7 +361,7 @@ func TestCountRepository(t *testing.T) {
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
count, err := repo_model.CountRepository(db.DefaultContext, testCase.opts)
count, err := repo_model.CountRepository(t.Context(), testCase.opts)
assert.NoError(t, err)
assert.Equal(t, int64(testCase.count), count)
@@ -396,7 +396,7 @@ func TestSearchRepositoryByTopicName(t *testing.T) {
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
_, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts)
_, count, err := repo_model.SearchRepositoryByName(t.Context(), testCase.opts)
assert.NoError(t, err)
assert.Equal(t, int64(testCase.count), count)
})

View File

@@ -6,7 +6,6 @@ package repo
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unit"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -28,7 +27,7 @@ var (
func TestGetRepositoryCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx := db.DefaultContext
ctx := t.Context()
count, err1 := CountRepositories(ctx, countRepospts)
privateCount, err2 := CountRepositories(ctx, countReposptsPrivate)
publicCount, err3 := CountRepositories(ctx, countReposptsPublic)
@@ -42,7 +41,7 @@ func TestGetRepositoryCount(t *testing.T) {
func TestGetPublicRepositoryCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
count, err := CountRepositories(db.DefaultContext, countReposptsPublic)
count, err := CountRepositories(t.Context(), countReposptsPublic)
assert.NoError(t, err)
assert.Equal(t, int64(1), count)
}
@@ -50,7 +49,7 @@ func TestGetPublicRepositoryCount(t *testing.T) {
func TestGetPrivateRepositoryCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
count, err := CountRepositories(db.DefaultContext, countReposptsPrivate)
count, err := CountRepositories(t.Context(), countReposptsPrivate)
assert.NoError(t, err)
assert.Equal(t, int64(2), count)
}
@@ -68,11 +67,11 @@ func TestWatchRepo(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &Repository{ID: 3})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
assert.NoError(t, WatchRepo(db.DefaultContext, user, repo, true))
assert.NoError(t, WatchRepo(t.Context(), user, repo, true))
unittest.AssertExistsAndLoadBean(t, &Watch{RepoID: repo.ID, UserID: user.ID})
unittest.CheckConsistencyFor(t, &Repository{ID: repo.ID})
assert.NoError(t, WatchRepo(db.DefaultContext, user, repo, false))
assert.NoError(t, WatchRepo(t.Context(), user, repo, false))
unittest.AssertNotExistsBean(t, &Watch{RepoID: repo.ID, UserID: user.ID})
unittest.CheckConsistencyFor(t, &Repository{ID: repo.ID})
}
@@ -86,7 +85,7 @@ func TestMetas(t *testing.T) {
repo.Units = nil
metas := repo.ComposeCommentMetas(db.DefaultContext)
metas := repo.ComposeCommentMetas(t.Context())
assert.Equal(t, "testRepo", metas["repo"])
assert.Equal(t, "testOwner", metas["user"])
@@ -100,7 +99,7 @@ func TestMetas(t *testing.T) {
testSuccess := func(expectedStyle string) {
repo.Units = []*RepoUnit{&externalTracker}
repo.commonRenderingMetas = nil
metas := repo.ComposeCommentMetas(db.DefaultContext)
metas := repo.ComposeCommentMetas(t.Context())
assert.Equal(t, expectedStyle, metas["style"])
assert.Equal(t, "testRepo", metas["repo"])
assert.Equal(t, "testOwner", metas["user"])
@@ -118,10 +117,10 @@ func TestMetas(t *testing.T) {
externalTracker.ExternalTrackerConfig().ExternalTrackerStyle = markup.IssueNameStyleRegexp
testSuccess(markup.IssueNameStyleRegexp)
repo, err := GetRepositoryByID(db.DefaultContext, 3)
repo, err := GetRepositoryByID(t.Context(), 3)
assert.NoError(t, err)
metas = repo.ComposeCommentMetas(db.DefaultContext)
metas = repo.ComposeCommentMetas(t.Context())
assert.Contains(t, metas, "org")
assert.Contains(t, metas, "teams")
assert.Equal(t, "org3", metas["org"])
@@ -132,13 +131,13 @@ func TestGetRepositoryByURL(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
t.Run("InvalidPath", func(t *testing.T) {
repo, err := GetRepositoryByURL(db.DefaultContext, "something")
repo, err := GetRepositoryByURL(t.Context(), "something")
assert.Nil(t, repo)
assert.Error(t, err)
})
testRepo2 := func(t *testing.T, url string) {
repo, err := GetRepositoryByURL(db.DefaultContext, url)
repo, err := GetRepositoryByURL(t.Context(), url)
require.NoError(t, err)
assert.EqualValues(t, 2, repo.ID)
assert.EqualValues(t, 2, repo.OwnerID)
@@ -162,7 +161,7 @@ func TestGetRepositoryByURL(t *testing.T) {
testRepo2(t, "sshuser@try.gitea.io:user2/repo2.git")
testRelax := func(t *testing.T, url string) {
repo, err := GetRepositoryByURLRelax(db.DefaultContext, url)
repo, err := GetRepositoryByURLRelax(t.Context(), url)
require.NoError(t, err)
assert.Equal(t, int64(2), repo.ID)
assert.Equal(t, int64(2), repo.OwnerID)

View File

@@ -21,25 +21,25 @@ func TestStarRepo(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
assert.NoError(t, repo_model.StarRepo(db.DefaultContext, user, repo, true))
assert.NoError(t, repo_model.StarRepo(t.Context(), user, repo, true))
unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
assert.NoError(t, repo_model.StarRepo(db.DefaultContext, user, repo, true))
assert.NoError(t, repo_model.StarRepo(t.Context(), user, repo, true))
unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
assert.NoError(t, repo_model.StarRepo(db.DefaultContext, user, repo, false))
assert.NoError(t, repo_model.StarRepo(t.Context(), user, repo, false))
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
}
func TestIsStaring(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.True(t, repo_model.IsStaring(db.DefaultContext, 2, 4))
assert.False(t, repo_model.IsStaring(db.DefaultContext, 3, 4))
assert.True(t, repo_model.IsStaring(t.Context(), 2, 4))
assert.False(t, repo_model.IsStaring(t.Context(), 3, 4))
}
func TestRepository_GetStargazers(t *testing.T) {
// repo with stargazers
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0})
gazers, err := repo_model.GetStargazers(t.Context(), repo, db.ListOptions{Page: 0})
assert.NoError(t, err)
if assert.Len(t, gazers, 1) {
assert.Equal(t, int64(2), gazers[0].ID)
@@ -50,7 +50,7 @@ func TestRepository_GetStargazers2(t *testing.T) {
// repo with stargazers
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0})
gazers, err := repo_model.GetStargazers(t.Context(), repo, db.ListOptions{Page: 0})
assert.NoError(t, err)
assert.Empty(t, gazers)
}
@@ -62,14 +62,14 @@ func TestClearRepoStars(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
assert.NoError(t, repo_model.StarRepo(db.DefaultContext, user, repo, true))
assert.NoError(t, repo_model.StarRepo(t.Context(), user, repo, true))
unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
assert.NoError(t, repo_model.StarRepo(db.DefaultContext, user, repo, false))
assert.NoError(t, repo_model.StarRepo(t.Context(), user, repo, false))
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
assert.NoError(t, repo_model.ClearRepoStars(db.DefaultContext, repo.ID))
assert.NoError(t, repo_model.ClearRepoStars(t.Context(), repo.ID))
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: user.ID, RepoID: repo.ID})
gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0})
gazers, err := repo_model.GetStargazers(t.Context(), repo, db.ListOptions{Page: 0})
assert.NoError(t, err)
assert.Empty(t, gazers)
}

View File

@@ -19,47 +19,47 @@ func TestAddTopic(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
topics, err := db.Find[repo_model.Topic](db.DefaultContext, &repo_model.FindTopicOptions{})
topics, err := db.Find[repo_model.Topic](t.Context(), &repo_model.FindTopicOptions{})
assert.NoError(t, err)
assert.Len(t, topics, totalNrOfTopics)
topics, total, err := db.FindAndCount[repo_model.Topic](db.DefaultContext, &repo_model.FindTopicOptions{
topics, total, err := db.FindAndCount[repo_model.Topic](t.Context(), &repo_model.FindTopicOptions{
ListOptions: db.ListOptions{Page: 1, PageSize: 2},
})
assert.NoError(t, err)
assert.Len(t, topics, 2)
assert.EqualValues(t, 6, total)
topics, err = db.Find[repo_model.Topic](db.DefaultContext, &repo_model.FindTopicOptions{
topics, err = db.Find[repo_model.Topic](t.Context(), &repo_model.FindTopicOptions{
RepoID: 1,
})
assert.NoError(t, err)
assert.Len(t, topics, repo1NrOfTopics)
assert.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang"))
assert.NoError(t, repo_model.SaveTopics(t.Context(), 2, "golang"))
repo2NrOfTopics := 1
topics, err = db.Find[repo_model.Topic](db.DefaultContext, &repo_model.FindTopicOptions{})
topics, err = db.Find[repo_model.Topic](t.Context(), &repo_model.FindTopicOptions{})
assert.NoError(t, err)
assert.Len(t, topics, totalNrOfTopics)
topics, err = db.Find[repo_model.Topic](db.DefaultContext, &repo_model.FindTopicOptions{
topics, err = db.Find[repo_model.Topic](t.Context(), &repo_model.FindTopicOptions{
RepoID: 2,
})
assert.NoError(t, err)
assert.Len(t, topics, repo2NrOfTopics)
assert.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang", "gitea"))
assert.NoError(t, repo_model.SaveTopics(t.Context(), 2, "golang", "gitea"))
repo2NrOfTopics = 2
totalNrOfTopics++
topic, err := repo_model.GetTopicByName(db.DefaultContext, "gitea")
topic, err := repo_model.GetTopicByName(t.Context(), "gitea")
assert.NoError(t, err)
assert.Equal(t, 1, topic.RepoCount)
topics, err = db.Find[repo_model.Topic](db.DefaultContext, &repo_model.FindTopicOptions{})
topics, err = db.Find[repo_model.Topic](t.Context(), &repo_model.FindTopicOptions{})
assert.NoError(t, err)
assert.Len(t, topics, totalNrOfTopics)
topics, err = db.Find[repo_model.Topic](db.DefaultContext, &repo_model.FindTopicOptions{
topics, err = db.Find[repo_model.Topic](t.Context(), &repo_model.FindTopicOptions{
RepoID: 2,
})
assert.NoError(t, err)

View File

@@ -6,7 +6,6 @@ package repo_test
import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -19,21 +18,21 @@ func TestRepoAssignees(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
users, err := repo_model.GetRepoAssignees(db.DefaultContext, repo2)
users, err := repo_model.GetRepoAssignees(t.Context(), repo2)
assert.NoError(t, err)
assert.Len(t, users, 1)
assert.Equal(t, int64(2), users[0].ID)
repo21 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 21})
users, err = repo_model.GetRepoAssignees(db.DefaultContext, repo21)
users, err = repo_model.GetRepoAssignees(t.Context(), repo21)
assert.NoError(t, err)
if assert.Len(t, users, 4) {
assert.ElementsMatch(t, []int64{10, 15, 16, 18}, []int64{users[0].ID, users[1].ID, users[2].ID, users[3].ID})
}
// do not return deactivated users
assert.NoError(t, user_model.UpdateUserCols(db.DefaultContext, &user_model.User{ID: 15, IsActive: false}, "is_active"))
users, err = repo_model.GetRepoAssignees(db.DefaultContext, repo21)
assert.NoError(t, user_model.UpdateUserCols(t.Context(), &user_model.User{ID: 15, IsActive: false}, "is_active"))
users, err = repo_model.GetRepoAssignees(t.Context(), repo21)
assert.NoError(t, err)
if assert.Len(t, users, 3) {
assert.NotContains(t, []int64{users[0].ID, users[1].ID, users[2].ID}, 15)
@@ -45,12 +44,12 @@ func TestGetIssuePostersWithSearch(t *testing.T) {
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
users, err := repo_model.GetIssuePostersWithSearch(db.DefaultContext, repo2, false, "USER", false /* full name */)
users, err := repo_model.GetIssuePostersWithSearch(t.Context(), repo2, false, "USER", false /* full name */)
require.NoError(t, err)
require.Len(t, users, 1)
assert.Equal(t, "user2", users[0].Name)
users, err = repo_model.GetIssuePostersWithSearch(db.DefaultContext, repo2, false, "TW%O", true /* full name */)
users, err = repo_model.GetIssuePostersWithSearch(t.Context(), repo2, false, "TW%O", true /* full name */)
require.NoError(t, err)
require.Len(t, users, 1)
assert.Equal(t, "user2", users[0].Name)

View File

@@ -18,20 +18,20 @@ import (
func TestIsWatching(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.True(t, repo_model.IsWatching(db.DefaultContext, 1, 1))
assert.True(t, repo_model.IsWatching(db.DefaultContext, 4, 1))
assert.True(t, repo_model.IsWatching(db.DefaultContext, 11, 1))
assert.True(t, repo_model.IsWatching(t.Context(), 1, 1))
assert.True(t, repo_model.IsWatching(t.Context(), 4, 1))
assert.True(t, repo_model.IsWatching(t.Context(), 11, 1))
assert.False(t, repo_model.IsWatching(db.DefaultContext, 1, 5))
assert.False(t, repo_model.IsWatching(db.DefaultContext, 8, 1))
assert.False(t, repo_model.IsWatching(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID))
assert.False(t, repo_model.IsWatching(t.Context(), 1, 5))
assert.False(t, repo_model.IsWatching(t.Context(), 8, 1))
assert.False(t, repo_model.IsWatching(t.Context(), unittest.NonexistentID, unittest.NonexistentID))
}
func TestGetWatchers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
watches, err := repo_model.GetWatchers(db.DefaultContext, repo.ID)
watches, err := repo_model.GetWatchers(t.Context(), repo.ID)
assert.NoError(t, err)
// One watchers are inactive, thus minus 1
assert.Len(t, watches, repo.NumWatches-1)
@@ -39,7 +39,7 @@ func TestGetWatchers(t *testing.T) {
assert.Equal(t, repo.ID, watch.RepoID)
}
watches, err = repo_model.GetWatchers(db.DefaultContext, unittest.NonexistentID)
watches, err = repo_model.GetWatchers(t.Context(), unittest.NonexistentID)
assert.NoError(t, err)
assert.Empty(t, watches)
}
@@ -48,7 +48,7 @@ func TestRepository_GetWatchers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
watchers, err := repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
watchers, err := repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err)
assert.Len(t, watchers, repo.NumWatches)
for _, watcher := range watchers {
@@ -56,7 +56,7 @@ func TestRepository_GetWatchers(t *testing.T) {
}
repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 9})
watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err)
assert.Empty(t, watchers)
}
@@ -67,7 +67,7 @@ func TestWatchIfAuto(t *testing.T) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
user12 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 12})
watchers, err := repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
watchers, err := repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err)
assert.Len(t, watchers, repo.NumWatches)
@@ -76,46 +76,46 @@ func TestWatchIfAuto(t *testing.T) {
prevCount := repo.NumWatches
// Must not add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true))
watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 8, 1, true))
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err)
assert.Len(t, watchers, prevCount)
// Should not add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 10, 1, true))
watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 10, 1, true))
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err)
assert.Len(t, watchers, prevCount)
setting.Service.AutoWatchOnChanges = true
// Must not add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true))
watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 8, 1, true))
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err)
assert.Len(t, watchers, prevCount)
// Should not add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, false))
watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 12, 1, false))
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err)
assert.Len(t, watchers, prevCount)
// Should add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true))
watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 12, 1, true))
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err)
assert.Len(t, watchers, prevCount+1)
// Should remove watch, inhibit from adding auto
assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, user12, repo, false))
watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, repo_model.WatchRepo(t.Context(), user12, repo, false))
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err)
assert.Len(t, watchers, prevCount)
// Must not add watch
assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true))
watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, repo_model.WatchIfAuto(t.Context(), 12, 1, true))
watchers, err = repo_model.GetRepoWatchers(t.Context(), repo.ID, db.ListOptions{Page: 1})
assert.NoError(t, err)
assert.Len(t, watchers, prevCount)
}

View File

@@ -6,7 +6,6 @@ package models
import (
"testing"
"code.gitea.io/gitea/models/db"
issues_model "code.gitea.io/gitea/models/issues"
"code.gitea.io/gitea/models/unittest"
@@ -15,13 +14,13 @@ import (
func TestCheckRepoStats(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, CheckRepoStats(db.DefaultContext))
assert.NoError(t, CheckRepoStats(t.Context()))
}
func TestDoctorUserStarNum(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, DoctorUserStarNum(db.DefaultContext))
assert.NoError(t, DoctorUserStarNum(t.Context()))
}
func Test_repoStatsCorrectIssueNumComments(t *testing.T) {
@@ -31,7 +30,7 @@ func Test_repoStatsCorrectIssueNumComments(t *testing.T) {
assert.NotNil(t, issue2)
assert.Equal(t, 0, issue2.NumComments) // the fixture data is wrong, but we don't fix it here
assert.NoError(t, repoStatsCorrectIssueNumComments(db.DefaultContext, 2))
assert.NoError(t, repoStatsCorrectIssueNumComments(t.Context(), 2))
// reload the issue
issue2 = unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
assert.Equal(t, 1, issue2.NumComments)

View File

@@ -9,6 +9,7 @@ import (
"time"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/storage"
"code.gitea.io/gitea/modules/timeutil"
@@ -56,8 +57,7 @@ func CreateNotice(ctx context.Context, tp NoticeType, desc string, args ...any)
// CreateRepositoryNotice creates new system notice with type NoticeRepository.
func CreateRepositoryNotice(desc string, args ...any) error {
// Note we use the db.DefaultContext here rather than passing in a context as the context may be cancelled
return CreateNotice(db.DefaultContext, NoticeRepository, desc, args...)
return CreateNotice(graceful.GetManager().ShutdownContext(), NoticeRepository, desc, args...)
}
// RemoveAllWithNotice removes all directories in given path and
@@ -66,8 +66,7 @@ func RemoveAllWithNotice(ctx context.Context, 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)
// Note we use the db.DefaultContext here rather than passing in a context as the context may be cancelled
if err = CreateNotice(db.DefaultContext, NoticeRepository, desc); err != nil {
if err = CreateNotice(graceful.GetManager().ShutdownContext(), NoticeRepository, desc); err != nil {
log.Error("CreateRepositoryNotice: %v", err)
}
}
@@ -80,8 +79,7 @@ func RemoveStorageWithNotice(ctx context.Context, bucket storage.ObjectStorage,
desc := fmt.Sprintf("%s [%s]: %v", title, path, err)
log.Warn(title+" [%s]: %v", path, err)
// Note we use the db.DefaultContext here rather than passing in a context as the context may be cancelled
if err = CreateNotice(db.DefaultContext, NoticeRepository, desc); err != nil {
if err = CreateNotice(graceful.GetManager().ShutdownContext(), NoticeRepository, desc); err != nil {
log.Error("CreateRepositoryNotice: %v", err)
}
}

View File

@@ -29,7 +29,7 @@ func TestCreateNotice(t *testing.T) {
Description: "test description",
}
unittest.AssertNotExistsBean(t, noticeBean)
assert.NoError(t, system.CreateNotice(db.DefaultContext, noticeBean.Type, noticeBean.Description))
assert.NoError(t, system.CreateNotice(t.Context(), noticeBean.Type, noticeBean.Description))
unittest.AssertExistsAndLoadBean(t, noticeBean)
}
@@ -47,20 +47,20 @@ func TestCreateRepositoryNotice(t *testing.T) {
func TestCountNotices(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.Equal(t, int64(3), system.CountNotices(db.DefaultContext))
assert.Equal(t, int64(3), system.CountNotices(t.Context()))
}
func TestNotices(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
notices, err := system.Notices(db.DefaultContext, 1, 2)
notices, err := system.Notices(t.Context(), 1, 2)
assert.NoError(t, err)
if assert.Len(t, notices, 2) {
assert.Equal(t, int64(3), notices[0].ID)
assert.Equal(t, int64(2), notices[1].ID)
}
notices, err = system.Notices(db.DefaultContext, 2, 2)
notices, err = system.Notices(t.Context(), 2, 2)
assert.NoError(t, err)
if assert.Len(t, notices, 1) {
assert.Equal(t, int64(1), notices[0].ID)
@@ -74,7 +74,7 @@ func TestDeleteNotices(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
assert.NoError(t, system.DeleteNotices(db.DefaultContext, 1, 2))
assert.NoError(t, system.DeleteNotices(t.Context(), 1, 2))
unittest.AssertNotExistsBean(t, &system.Notice{ID: 1})
unittest.AssertNotExistsBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
@@ -87,7 +87,7 @@ func TestDeleteNotices2(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
assert.NoError(t, system.DeleteNotices(db.DefaultContext, 3, 2))
assert.NoError(t, system.DeleteNotices(t.Context(), 3, 2))
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
@@ -99,7 +99,7 @@ func TestDeleteNoticesByIDs(t *testing.T) {
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3})
err := db.DeleteByIDs[system.Notice](db.DefaultContext, 1, 3)
err := db.DeleteByIDs[system.Notice](t.Context(), 1, 3)
assert.NoError(t, err)
unittest.AssertNotExistsBean(t, &system.Notice{ID: 1})
unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2})

View File

@@ -17,34 +17,34 @@ func TestSettings(t *testing.T) {
keyName := "test.key"
assert.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, db.TruncateBeans(db.DefaultContext, &system.Setting{}))
assert.NoError(t, db.TruncateBeans(t.Context(), &system.Setting{}))
rev, settings, err := system.GetAllSettings(db.DefaultContext)
rev, settings, err := system.GetAllSettings(t.Context())
assert.NoError(t, err)
assert.Equal(t, 1, rev)
assert.Len(t, settings, 1) // there is only one "revision" key
err = system.SetSettings(db.DefaultContext, map[string]string{keyName: "true"})
err = system.SetSettings(t.Context(), map[string]string{keyName: "true"})
assert.NoError(t, err)
rev, settings, err = system.GetAllSettings(db.DefaultContext)
rev, settings, err = system.GetAllSettings(t.Context())
assert.NoError(t, err)
assert.Equal(t, 2, rev)
assert.Len(t, settings, 2)
assert.Equal(t, "true", settings[keyName])
err = system.SetSettings(db.DefaultContext, map[string]string{keyName: "false"})
err = system.SetSettings(t.Context(), map[string]string{keyName: "false"})
assert.NoError(t, err)
rev, settings, err = system.GetAllSettings(db.DefaultContext)
rev, settings, err = system.GetAllSettings(t.Context())
assert.NoError(t, err)
assert.Equal(t, 3, rev)
assert.Len(t, settings, 2)
assert.Equal(t, "false", settings[keyName])
// setting the same value should not trigger DuplicateKey error, and the "version" should be increased
err = system.SetSettings(db.DefaultContext, map[string]string{keyName: "false"})
err = system.SetSettings(t.Context(), map[string]string{keyName: "false"})
assert.NoError(t, err)
rev, settings, err = system.GetAllSettings(db.DefaultContext)
rev, settings, err = system.GetAllSettings(t.Context())
assert.NoError(t, err)
assert.Len(t, settings, 2)
assert.Equal(t, 4, rev)

View File

@@ -4,6 +4,7 @@
package unittest
import (
"context"
"reflect"
"strconv"
"strings"
@@ -22,10 +23,10 @@ const (
modelsCommentTypeComment = 0
)
var consistencyCheckMap = make(map[string]func(t assert.TestingT, bean any))
var consistencyCheckMap = make(map[string]func(t TestingT, bean any))
// CheckConsistencyFor test that all matching database entries are consistent
func CheckConsistencyFor(t require.TestingT, beansToCheck ...any) {
func CheckConsistencyFor(t TestingT, beansToCheck ...any) {
for _, bean := range beansToCheck {
sliceType := reflect.SliceOf(reflect.TypeOf(bean))
sliceValue := reflect.MakeSlice(sliceType, 0, 10)
@@ -33,7 +34,7 @@ func CheckConsistencyFor(t require.TestingT, beansToCheck ...any) {
ptrToSliceValue := reflect.New(sliceType)
ptrToSliceValue.Elem().Set(sliceValue)
assert.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface()))
assert.NoError(t, db.GetEngine(context.TODO()).Table(bean).Find(ptrToSliceValue.Interface()))
sliceValue = ptrToSliceValue.Elem()
for i := 0; i < sliceValue.Len(); i++ {
@@ -43,7 +44,7 @@ func CheckConsistencyFor(t require.TestingT, beansToCheck ...any) {
}
}
func checkForConsistency(t require.TestingT, bean any) {
func checkForConsistency(t TestingT, bean any) {
tb, err := db.TableInfo(bean)
assert.NoError(t, err)
f := consistencyCheckMap[tb.Name]
@@ -61,7 +62,7 @@ func init() {
return i
}
checkForUserConsistency := func(t assert.TestingT, bean any) {
checkForUserConsistency := func(t TestingT, bean any) {
user := reflectionWrap(bean)
AssertCountByCond(t, "repository", builder.Eq{"owner_id": user.int("ID")}, user.int("NumRepos"))
AssertCountByCond(t, "star", builder.Eq{"uid": user.int("ID")}, user.int("NumStars"))
@@ -75,7 +76,7 @@ func init() {
}
}
checkForRepoConsistency := func(t assert.TestingT, bean any) {
checkForRepoConsistency := func(t TestingT, bean any) {
repo := reflectionWrap(bean)
assert.Equal(t, repo.str("LowerName"), strings.ToLower(repo.str("Name")), "repo: %+v", repo)
AssertCountByCond(t, "star", builder.Eq{"repo_id": repo.int("ID")}, repo.int("NumStars"))
@@ -111,7 +112,7 @@ func init() {
"Unexpected number of closed milestones for repo id: %d", repo.int("ID"))
}
checkForIssueConsistency := func(t assert.TestingT, bean any) {
checkForIssueConsistency := func(t TestingT, bean any) {
issue := reflectionWrap(bean)
typeComment := modelsCommentTypeComment
actual := GetCountByCond(t, "comment", builder.Eq{"`type`": typeComment, "issue_id": issue.int("ID")})
@@ -122,14 +123,14 @@ func init() {
}
}
checkForPullRequestConsistency := func(t assert.TestingT, bean any) {
checkForPullRequestConsistency := func(t TestingT, bean any) {
pr := reflectionWrap(bean)
issueRow := AssertExistsAndLoadMap(t, "issue", builder.Eq{"id": pr.int("IssueID")})
assert.True(t, parseBool(issueRow["is_pull"]))
assert.Equal(t, parseInt(issueRow["index"]), pr.int("Index"), "Unexpected index for pull request id: %d", pr.int("ID"))
}
checkForMilestoneConsistency := func(t assert.TestingT, bean any) {
checkForMilestoneConsistency := func(t TestingT, bean any) {
milestone := reflectionWrap(bean)
AssertCountByCond(t, "issue", builder.Eq{"milestone_id": milestone.int("ID")}, milestone.int("NumIssues"))
@@ -143,9 +144,9 @@ func init() {
assert.Equal(t, completeness, milestone.int("Completeness"))
}
checkForLabelConsistency := func(t assert.TestingT, bean any) {
checkForLabelConsistency := func(t TestingT, bean any) {
label := reflectionWrap(bean)
issueLabels, err := db.GetEngine(db.DefaultContext).Table("issue_label").
issueLabels, err := db.GetEngine(context.TODO()).Table("issue_label").
Where(builder.Eq{"label_id": label.int("ID")}).
Query()
assert.NoError(t, err)
@@ -164,13 +165,13 @@ func init() {
assert.EqualValues(t, expected, label.int("NumClosedIssues"), "Unexpected number of closed issues for label id: %d", label.int("ID"))
}
checkForTeamConsistency := func(t assert.TestingT, bean any) {
checkForTeamConsistency := func(t TestingT, bean any) {
team := reflectionWrap(bean)
AssertCountByCond(t, "team_user", builder.Eq{"team_id": team.int("ID")}, team.int("NumMembers"))
AssertCountByCond(t, "team_repo", builder.Eq{"team_id": team.int("ID")}, team.int("NumRepos"))
}
checkForActionConsistency := func(t assert.TestingT, bean any) {
checkForActionConsistency := func(t TestingT, bean any) {
action := reflectionWrap(bean)
if action.int("RepoID") != 1700 { // dangling intentional
repoRow := AssertExistsAndLoadMap(t, "repository", builder.Eq{"id": action.int("RepoID")})

View File

@@ -23,7 +23,7 @@ var fixturesLoader FixturesLoader
// GetXORMEngine gets the XORM engine
func GetXORMEngine() (x *xorm.Engine) {
return db.GetEngine(db.DefaultContext).(*xorm.Engine)
return db.GetXORMEngineForTesting()
}
func loadFixtureResetSeqPgsql(e *xorm.Engine) error {

View File

@@ -4,6 +4,7 @@
package unittest
import (
"context"
"fmt"
"math"
"os"
@@ -14,7 +15,6 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/builder"
"xorm.io/xorm"
)
// Code in this file is mainly used by unittest.CheckConsistencyFor, which is not in the unit test for various reasons.
@@ -23,6 +23,12 @@ import (
// NonexistentID an ID that will never exist
const NonexistentID = int64(math.MaxInt64)
type TestingT interface {
require.TestingT
assert.TestingT
Context() context.Context
}
type testCond struct {
query any
args []any
@@ -55,13 +61,13 @@ func whereOrderConditions(e db.Engine, conditions []any) db.Engine {
return e.OrderBy(orderBy)
}
func getBeanIfExists(bean any, conditions ...any) (bool, error) {
e := db.GetEngine(db.DefaultContext)
func getBeanIfExists(t TestingT, bean any, conditions ...any) (bool, error) {
e := db.GetEngine(t.Context())
return whereOrderConditions(e, conditions).Get(bean)
}
func GetBean[T any](t require.TestingT, bean T, conditions ...any) (ret T) {
exists, err := getBeanIfExists(bean, conditions...)
func GetBean[T any](t TestingT, bean T, conditions ...any) (ret T) {
exists, err := getBeanIfExists(t, bean, conditions...)
require.NoError(t, err)
if exists {
return bean
@@ -70,8 +76,8 @@ func GetBean[T any](t require.TestingT, bean T, conditions ...any) (ret T) {
}
// AssertExistsAndLoadBean assert that a bean exists and load it from the test database
func AssertExistsAndLoadBean[T any](t require.TestingT, bean T, conditions ...any) T {
exists, err := getBeanIfExists(bean, conditions...)
func AssertExistsAndLoadBean[T any](t TestingT, bean T, conditions ...any) T {
exists, err := getBeanIfExists(t, bean, conditions...)
require.NoError(t, err)
require.True(t, exists,
"Expected to find %+v (of type %T, with conditions %+v), but did not",
@@ -80,8 +86,8 @@ func AssertExistsAndLoadBean[T any](t require.TestingT, bean T, conditions ...an
}
// AssertExistsAndLoadMap assert that a row exists and load it from the test database
func AssertExistsAndLoadMap(t assert.TestingT, table string, conditions ...any) map[string]string {
e := db.GetEngine(db.DefaultContext).Table(table)
func AssertExistsAndLoadMap(t TestingT, table string, conditions ...any) map[string]string {
e := db.GetEngine(t.Context()).Table(table)
res, err := whereOrderConditions(e, conditions).Query()
assert.NoError(t, err)
assert.Len(t, res, 1,
@@ -100,8 +106,8 @@ func AssertExistsAndLoadMap(t assert.TestingT, table string, conditions ...any)
}
// GetCount get the count of a bean
func GetCount(t assert.TestingT, bean any, conditions ...any) int {
e := db.GetEngine(db.DefaultContext)
func GetCount(t TestingT, bean any, conditions ...any) int {
e := db.GetEngine(t.Context())
for _, condition := range conditions {
switch cond := condition.(type) {
case *testCond:
@@ -116,14 +122,14 @@ func GetCount(t assert.TestingT, bean any, conditions ...any) int {
}
// AssertNotExistsBean assert that a bean does not exist in the test database
func AssertNotExistsBean(t assert.TestingT, bean any, conditions ...any) {
exists, err := getBeanIfExists(bean, conditions...)
func AssertNotExistsBean(t TestingT, bean any, conditions ...any) {
exists, err := getBeanIfExists(t, bean, conditions...)
assert.NoError(t, err)
assert.False(t, exists)
}
// AssertCount assert the count of a bean
func AssertCount(t assert.TestingT, bean, expected any) bool {
func AssertCount(t TestingT, bean, expected any) bool {
return assert.EqualValues(t, expected, GetCount(t, bean))
}
@@ -134,22 +140,22 @@ func AssertInt64InRange(t assert.TestingT, low, high, value int64) {
}
// GetCountByCond get the count of database entries matching bean
func GetCountByCond(t assert.TestingT, tableName string, cond builder.Cond) int64 {
e := db.GetEngine(db.DefaultContext)
func GetCountByCond(t TestingT, tableName string, cond builder.Cond) int64 {
e := db.GetEngine(t.Context())
count, err := e.Table(tableName).Where(cond).Count()
assert.NoError(t, err)
return count
}
// AssertCountByCond test the count of database entries matching bean
func AssertCountByCond(t assert.TestingT, tableName string, cond builder.Cond, expected int) bool {
func AssertCountByCond(t TestingT, tableName string, cond builder.Cond, expected int) bool {
return assert.EqualValues(t, expected, GetCountByCond(t, tableName, cond),
"Failed consistency test, the counted bean (of table %s) was %+v", tableName, cond)
}
// DumpQueryResult dumps the result of a query for debugging purpose
func DumpQueryResult(t require.TestingT, sqlOrBean any, sqlArgs ...any) {
x := db.GetEngine(db.DefaultContext).(*xorm.Engine)
x := GetXORMEngine()
goDB := x.DB().DB
sql, ok := sqlOrBean.(string)
if !ok {

View File

@@ -8,7 +8,6 @@ import (
"strings"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/storage"
@@ -23,12 +22,12 @@ func TestUserAvatarLink(t *testing.T) {
defer test.MockVariableValue(&setting.AppSubURL, "")()
u := &User{ID: 1, Avatar: "avatar.png"}
link := u.AvatarLink(db.DefaultContext)
link := u.AvatarLink(t.Context())
assert.Equal(t, "https://localhost/avatars/avatar.png", link)
setting.AppURL = "https://localhost/sub-path/"
setting.AppSubURL = "/sub-path"
link = u.AvatarLink(db.DefaultContext)
link = u.AvatarLink(t.Context())
assert.Equal(t, "https://localhost/sub-path/avatars/avatar.png", link)
}
@@ -43,7 +42,7 @@ func TestUserAvatarGenerate(t *testing.T) {
// there was no avatar, generate a new one
assert.Empty(t, u.Avatar)
err = GenerateRandomAvatar(db.DefaultContext, u)
err = GenerateRandomAvatar(t.Context(), u)
require.NoError(t, err)
assert.NotEmpty(t, u.Avatar)
@@ -56,7 +55,7 @@ func TestUserAvatarGenerate(t *testing.T) {
require.NoError(t, err)
// try to generate again
err = GenerateRandomAvatar(db.DefaultContext, u)
err = GenerateRandomAvatar(t.Context(), u)
require.NoError(t, err)
assert.Equal(t, oldAvatarPath, u.CustomAvatarRelativePath())
f, err := storage.Avatars.Open(u.CustomAvatarRelativePath())

View File

@@ -18,14 +18,14 @@ import (
func TestGetEmailAddresses(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
emails, _ := user_model.GetEmailAddresses(db.DefaultContext, int64(1))
emails, _ := user_model.GetEmailAddresses(t.Context(), int64(1))
if assert.Len(t, emails, 3) {
assert.True(t, emails[0].IsPrimary)
assert.True(t, emails[2].IsActivated)
assert.False(t, emails[2].IsPrimary)
}
emails, _ = user_model.GetEmailAddresses(db.DefaultContext, int64(2))
emails, _ = user_model.GetEmailAddresses(t.Context(), int64(2))
if assert.Len(t, emails, 2) {
assert.True(t, emails[0].IsPrimary)
assert.True(t, emails[0].IsActivated)
@@ -35,36 +35,36 @@ func TestGetEmailAddresses(t *testing.T) {
func TestIsEmailUsed(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
isExist, _ := user_model.IsEmailUsed(db.DefaultContext, "")
isExist, _ := user_model.IsEmailUsed(t.Context(), "")
assert.True(t, isExist)
isExist, _ = user_model.IsEmailUsed(db.DefaultContext, "user11@example.com")
isExist, _ = user_model.IsEmailUsed(t.Context(), "user11@example.com")
assert.True(t, isExist)
isExist, _ = user_model.IsEmailUsed(db.DefaultContext, "user1234567890@example.com")
isExist, _ = user_model.IsEmailUsed(t.Context(), "user1234567890@example.com")
assert.False(t, isExist)
}
func TestMakeEmailPrimary(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
err := user_model.MakeActiveEmailPrimary(db.DefaultContext, 9999999)
err := user_model.MakeActiveEmailPrimary(t.Context(), 9999999)
assert.Error(t, err)
assert.ErrorIs(t, err, user_model.ErrEmailAddressNotExist{})
email := unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "user11@example.com"})
err = user_model.MakeActiveEmailPrimary(db.DefaultContext, email.ID)
err = user_model.MakeActiveEmailPrimary(t.Context(), email.ID)
assert.Error(t, err)
assert.ErrorIs(t, err, user_model.ErrEmailAddressNotExist{}) // inactive email is considered as not exist for "MakeActiveEmailPrimary"
email = unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "user9999999@example.com"})
err = user_model.MakeActiveEmailPrimary(db.DefaultContext, email.ID)
err = user_model.MakeActiveEmailPrimary(t.Context(), email.ID)
assert.Error(t, err)
assert.True(t, user_model.IsErrUserNotExist(err))
email = unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "user101@example.com"})
err = user_model.MakeActiveEmailPrimary(db.DefaultContext, email.ID)
err = user_model.MakeActiveEmailPrimary(t.Context(), email.ID)
assert.NoError(t, err)
user, _ := user_model.GetUserByID(db.DefaultContext, int64(10))
user, _ := user_model.GetUserByID(t.Context(), int64(10))
assert.Equal(t, "user101@example.com", user.Email)
}
@@ -76,9 +76,9 @@ func TestActivate(t *testing.T) {
UID: int64(1),
Email: "user11@example.com",
}
assert.NoError(t, user_model.ActivateEmail(db.DefaultContext, email))
assert.NoError(t, user_model.ActivateEmail(t.Context(), email))
emails, _ := user_model.GetEmailAddresses(db.DefaultContext, int64(1))
emails, _ := user_model.GetEmailAddresses(t.Context(), int64(1))
assert.Len(t, emails, 3)
assert.True(t, emails[0].IsActivated)
assert.True(t, emails[0].IsPrimary)
@@ -96,7 +96,7 @@ func TestListEmails(t *testing.T) {
PageSize: 10000,
},
}
emails, count, err := user_model.SearchEmails(db.DefaultContext, opts)
emails, count, err := user_model.SearchEmails(t.Context(), opts)
assert.NoError(t, err)
assert.Greater(t, count, int64(5))
@@ -110,13 +110,13 @@ func TestListEmails(t *testing.T) {
// Must find no records
opts = &user_model.SearchEmailOptions{Keyword: "NOTFOUND"}
emails, count, err = user_model.SearchEmails(db.DefaultContext, opts)
emails, count, err = user_model.SearchEmails(t.Context(), opts)
assert.NoError(t, err)
assert.Equal(t, int64(0), count)
// Must find users 'user2', 'user28', etc.
opts = &user_model.SearchEmailOptions{Keyword: "user2"}
emails, count, err = user_model.SearchEmails(db.DefaultContext, opts)
emails, count, err = user_model.SearchEmails(t.Context(), opts)
assert.NoError(t, err)
assert.NotEqual(t, int64(0), count)
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 2 }))
@@ -124,14 +124,14 @@ func TestListEmails(t *testing.T) {
// Must find only primary addresses (i.e. from the `user` table)
opts = &user_model.SearchEmailOptions{IsPrimary: optional.Some(true)}
emails, _, err = user_model.SearchEmails(db.DefaultContext, opts)
emails, _, err = user_model.SearchEmails(t.Context(), opts)
assert.NoError(t, err)
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.IsPrimary }))
assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return !s.IsPrimary }))
// Must find only inactive addresses (i.e. not validated)
opts = &user_model.SearchEmailOptions{IsActivated: optional.Some(false)}
emails, _, err = user_model.SearchEmails(db.DefaultContext, opts)
emails, _, err = user_model.SearchEmails(t.Context(), opts)
assert.NoError(t, err)
assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return !s.IsActivated }))
assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return s.IsActivated }))
@@ -143,7 +143,7 @@ func TestListEmails(t *testing.T) {
Page: 1,
},
}
emails, count, err = user_model.SearchEmails(db.DefaultContext, opts)
emails, count, err = user_model.SearchEmails(t.Context(), opts)
assert.NoError(t, err)
assert.Len(t, emails, 5)
assert.Greater(t, count, int64(len(emails)))

View File

@@ -6,7 +6,6 @@ package user_test
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -15,9 +14,9 @@ import (
func TestIsFollowing(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
assert.True(t, user_model.IsFollowing(db.DefaultContext, 4, 2))
assert.False(t, user_model.IsFollowing(db.DefaultContext, 2, 4))
assert.False(t, user_model.IsFollowing(db.DefaultContext, 5, unittest.NonexistentID))
assert.False(t, user_model.IsFollowing(db.DefaultContext, unittest.NonexistentID, 5))
assert.False(t, user_model.IsFollowing(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID))
assert.True(t, user_model.IsFollowing(t.Context(), 4, 2))
assert.False(t, user_model.IsFollowing(t.Context(), 2, 4))
assert.False(t, user_model.IsFollowing(t.Context(), 5, unittest.NonexistentID))
assert.False(t, user_model.IsFollowing(t.Context(), unittest.NonexistentID, 5))
assert.False(t, user_model.IsFollowing(t.Context(), unittest.NonexistentID, unittest.NonexistentID))
}

View File

@@ -6,7 +6,6 @@ package user_test
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -17,7 +16,7 @@ import (
func TestGetUserOpenIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(1))
oids, err := user_model.GetUserOpenIDs(t.Context(), int64(1))
if assert.NoError(t, err) && assert.Len(t, oids, 2) {
assert.Equal(t, "https://user1.domain1.tld/", oids[0].URI)
assert.False(t, oids[0].Show)
@@ -25,7 +24,7 @@ func TestGetUserOpenIDs(t *testing.T) {
assert.True(t, oids[1].Show)
}
oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2))
oids, err = user_model.GetUserOpenIDs(t.Context(), int64(2))
if assert.NoError(t, err) && assert.Len(t, oids, 1) {
assert.Equal(t, "https://domain1.tld/user2/", oids[0].URI)
assert.True(t, oids[0].Show)
@@ -34,23 +33,23 @@ func TestGetUserOpenIDs(t *testing.T) {
func TestToggleUserOpenIDVisibility(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(2))
oids, err := user_model.GetUserOpenIDs(t.Context(), int64(2))
require.NoError(t, err)
require.Len(t, oids, 1)
assert.True(t, oids[0].Show)
err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID)
err = user_model.ToggleUserOpenIDVisibility(t.Context(), oids[0].ID)
require.NoError(t, err)
oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2))
oids, err = user_model.GetUserOpenIDs(t.Context(), int64(2))
require.NoError(t, err)
require.Len(t, oids, 1)
assert.False(t, oids[0].Show)
err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID)
err = user_model.ToggleUserOpenIDVisibility(t.Context(), oids[0].ID)
require.NoError(t, err)
oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2))
oids, err = user_model.GetUserOpenIDs(t.Context(), int64(2))
require.NoError(t, err)
if assert.Len(t, oids, 1) {
assert.True(t, oids[0].Show)

View File

@@ -6,7 +6,6 @@ package user_test
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -16,10 +15,10 @@ import (
func TestLookupUserRedirect(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
userID, err := user_model.LookupUserRedirect(db.DefaultContext, "olduser1")
userID, err := user_model.LookupUserRedirect(t.Context(), "olduser1")
assert.NoError(t, err)
assert.EqualValues(t, 1, userID)
_, err = user_model.LookupUserRedirect(db.DefaultContext, "doesnotexist")
_, err = user_model.LookupUserRedirect(t.Context(), "doesnotexist")
assert.True(t, user_model.IsErrUserRedirectNotExist(err))
}

View File

@@ -6,7 +6,6 @@ package user_test
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -20,41 +19,41 @@ func TestSettings(t *testing.T) {
newSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Gitea User Setting Test"}
// create setting
err := user_model.SetUserSetting(db.DefaultContext, newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue)
err := user_model.SetUserSetting(t.Context(), newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue)
assert.NoError(t, err)
// test about saving unchanged values
err = user_model.SetUserSetting(db.DefaultContext, newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue)
err = user_model.SetUserSetting(t.Context(), newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue)
assert.NoError(t, err)
// get specific setting
settings, err := user_model.GetSettings(db.DefaultContext, 99, []string{keyName})
settings, err := user_model.GetSettings(t.Context(), 99, []string{keyName})
assert.NoError(t, err)
assert.Len(t, settings, 1)
assert.Equal(t, newSetting.SettingValue, settings[keyName].SettingValue)
settingValue, err := user_model.GetUserSetting(db.DefaultContext, 99, keyName)
settingValue, err := user_model.GetUserSetting(t.Context(), 99, keyName)
assert.NoError(t, err)
assert.Equal(t, newSetting.SettingValue, settingValue)
settingValue, err = user_model.GetUserSetting(db.DefaultContext, 99, "no_such")
settingValue, err = user_model.GetUserSetting(t.Context(), 99, "no_such")
assert.NoError(t, err)
assert.Empty(t, settingValue)
// updated setting
updatedSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Updated"}
err = user_model.SetUserSetting(db.DefaultContext, updatedSetting.UserID, updatedSetting.SettingKey, updatedSetting.SettingValue)
err = user_model.SetUserSetting(t.Context(), updatedSetting.UserID, updatedSetting.SettingKey, updatedSetting.SettingValue)
assert.NoError(t, err)
// get all settings
settings, err = user_model.GetUserAllSettings(db.DefaultContext, 99)
settings, err = user_model.GetUserAllSettings(t.Context(), 99)
assert.NoError(t, err)
assert.Len(t, settings, 1)
assert.Equal(t, updatedSetting.SettingValue, settings[updatedSetting.SettingKey].SettingValue)
// delete setting
err = user_model.DeleteUserSetting(db.DefaultContext, 99, keyName)
err = user_model.DeleteUserSetting(t.Context(), 99, keyName)
assert.NoError(t, err)
settings, err = user_model.GetUserAllSettings(db.DefaultContext, 99)
settings, err = user_model.GetUserAllSettings(t.Context(), 99)
assert.NoError(t, err)
assert.Empty(t, settings)
}

View File

@@ -6,27 +6,25 @@ package user
import (
"testing"
"code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSystemUser(t *testing.T) {
u, err := GetPossibleUserByID(db.DefaultContext, -1)
u, err := GetPossibleUserByID(t.Context(), -1)
require.NoError(t, err)
assert.Equal(t, "Ghost", u.Name)
assert.Equal(t, "ghost", u.LowerName)
assert.True(t, u.IsGhost())
assert.True(t, IsGhostUserName("gHost"))
u, err = GetPossibleUserByID(db.DefaultContext, -2)
u, err = GetPossibleUserByID(t.Context(), -2)
require.NoError(t, err)
assert.Equal(t, "gitea-actions", u.Name)
assert.Equal(t, "gitea-actions", u.LowerName)
assert.True(t, u.IsGiteaActions())
assert.True(t, IsGiteaActionsUserName("Gitea-actionS"))
_, err = GetPossibleUserByID(db.DefaultContext, -3)
_, err = GetPossibleUserByID(t.Context(), -3)
require.Error(t, err)
}

View File

@@ -44,7 +44,7 @@ func TestIsUsableUsername(t *testing.T) {
func TestOAuth2Application_LoadUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
app := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ID: 1})
user, err := user_model.GetUserByID(db.DefaultContext, app.UID)
user, err := user_model.GetUserByID(t.Context(), app.UID)
assert.NoError(t, err)
assert.NotNil(t, user)
}
@@ -53,14 +53,14 @@ func TestUserEmails(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
t.Run("GetUserEmailsByNames", func(t *testing.T) {
// ignore none active user email
assert.ElementsMatch(t, []string{"user8@example.com"}, user_model.GetUserEmailsByNames(db.DefaultContext, []string{"user8", "user9"}))
assert.ElementsMatch(t, []string{"user8@example.com", "user5@example.com"}, user_model.GetUserEmailsByNames(db.DefaultContext, []string{"user8", "user5"}))
assert.ElementsMatch(t, []string{"user8@example.com"}, user_model.GetUserEmailsByNames(db.DefaultContext, []string{"user8", "org7"}))
assert.ElementsMatch(t, []string{"user8@example.com"}, user_model.GetUserEmailsByNames(t.Context(), []string{"user8", "user9"}))
assert.ElementsMatch(t, []string{"user8@example.com", "user5@example.com"}, user_model.GetUserEmailsByNames(t.Context(), []string{"user8", "user5"}))
assert.ElementsMatch(t, []string{"user8@example.com"}, user_model.GetUserEmailsByNames(t.Context(), []string{"user8", "org7"}))
})
t.Run("GetUsersByEmails", func(t *testing.T) {
defer test.MockVariableValue(&setting.Service.NoReplyAddress, "NoReply.gitea.internal")()
testGetUserByEmail := func(t *testing.T, email string, uid int64) {
m, err := user_model.GetUsersByEmails(db.DefaultContext, []string{email})
m, err := user_model.GetUsersByEmails(t.Context(), []string{email})
require.NoError(t, err)
user := m.GetByEmail(email)
if uid == 0 {
@@ -114,7 +114,7 @@ func TestCanCreateOrganization(t *testing.T) {
func TestSearchUsers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(opts user_model.SearchUserOptions, expectedUserOrOrgIDs []int64) {
users, _, err := user_model.SearchUsers(db.DefaultContext, opts)
users, _, err := user_model.SearchUsers(t.Context(), opts)
assert.NoError(t, err)
cassText := fmt.Sprintf("ids: %v, opts: %v", expectedUserOrOrgIDs, opts)
if assert.Len(t, users, len(expectedUserOrOrgIDs), "case: %s", cassText) {
@@ -243,7 +243,7 @@ func BenchmarkHashPassword(b *testing.B) {
func TestNewGitSig(t *testing.T) {
users := make([]*user_model.User, 0, 20)
err := db.GetEngine(db.DefaultContext).Find(&users)
err := db.GetEngine(t.Context()).Find(&users)
assert.NoError(t, err)
for _, user := range users {
@@ -257,7 +257,7 @@ func TestNewGitSig(t *testing.T) {
func TestDisplayName(t *testing.T) {
users := make([]*user_model.User, 0, 20)
err := db.GetEngine(db.DefaultContext).Find(&users)
err := db.GetEngine(t.Context()).Find(&users)
assert.NoError(t, err)
for _, user := range users {
@@ -280,7 +280,7 @@ func TestCreateUserInvalidEmail(t *testing.T) {
MustChangePassword: false,
}
err := user_model.CreateUser(db.DefaultContext, user, &user_model.Meta{})
err := user_model.CreateUser(t.Context(), user, &user_model.Meta{})
assert.Error(t, err)
assert.True(t, user_model.IsErrEmailCharIsNotSupported(err))
}
@@ -294,7 +294,7 @@ func TestCreateUserEmailAlreadyUsed(t *testing.T) {
user.Name = "testuser"
user.LowerName = strings.ToLower(user.Name)
user.ID = 0
err := user_model.CreateUser(db.DefaultContext, user, &user_model.Meta{})
err := user_model.CreateUser(t.Context(), user, &user_model.Meta{})
assert.Error(t, err)
assert.True(t, user_model.IsErrEmailAlreadyUsed(err))
}
@@ -311,7 +311,7 @@ func TestCreateUserCustomTimestamps(t *testing.T) {
user.ID = 0
user.Email = "unique@example.com"
user.CreatedUnix = creationTimestamp
err := user_model.CreateUser(db.DefaultContext, user, &user_model.Meta{})
err := user_model.CreateUser(t.Context(), user, &user_model.Meta{})
assert.NoError(t, err)
fetched, err := user_model.GetUserByID(t.Context(), user.ID)
@@ -336,7 +336,7 @@ func TestCreateUserWithoutCustomTimestamps(t *testing.T) {
user.Email = "unique@example.com"
user.CreatedUnix = 0
user.UpdatedUnix = 0
err := user_model.CreateUser(db.DefaultContext, user, &user_model.Meta{})
err := user_model.CreateUser(t.Context(), user, &user_model.Meta{})
assert.NoError(t, err)
timestampEnd := time.Now().Unix()
@@ -355,12 +355,12 @@ func TestGetUserIDsByNames(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
// ignore non existing
IDs, err := user_model.GetUserIDsByNames(db.DefaultContext, []string{"user1", "user2", "none_existing_user"}, true)
IDs, err := user_model.GetUserIDsByNames(t.Context(), []string{"user1", "user2", "none_existing_user"}, true)
assert.NoError(t, err)
assert.Equal(t, []int64{1, 2}, IDs)
// ignore non existing
IDs, err = user_model.GetUserIDsByNames(db.DefaultContext, []string{"user1", "do_not_exist"}, false)
IDs, err = user_model.GetUserIDsByNames(t.Context(), []string{"user1", "do_not_exist"}, false)
assert.Error(t, err)
assert.Equal(t, []int64(nil), IDs)
}
@@ -368,14 +368,14 @@ func TestGetUserIDsByNames(t *testing.T) {
func TestGetMaileableUsersByIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
results, err := user_model.GetMailableUsersByIDs(db.DefaultContext, []int64{1, 4}, false)
results, err := user_model.GetMailableUsersByIDs(t.Context(), []int64{1, 4}, false)
assert.NoError(t, err)
assert.Len(t, results, 1)
if len(results) > 1 {
assert.Equal(t, 1, results[0].ID)
}
results, err = user_model.GetMailableUsersByIDs(db.DefaultContext, []int64{1, 4}, true)
results, err = user_model.GetMailableUsersByIDs(t.Context(), []int64{1, 4}, true)
assert.NoError(t, err)
assert.Len(t, results, 2)
if len(results) > 2 {
@@ -389,7 +389,7 @@ func TestNewUserRedirect(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "newusername"))
assert.NoError(t, user_model.NewUserRedirect(t.Context(), user.ID, user.Name, "newusername"))
unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{
LowerName: user.LowerName,
@@ -406,7 +406,7 @@ func TestNewUserRedirect2(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "olduser1"))
assert.NoError(t, user_model.NewUserRedirect(t.Context(), user.ID, user.Name, "olduser1"))
unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{
LowerName: user.LowerName,
@@ -423,7 +423,7 @@ func TestNewUserRedirect3(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "newusername"))
assert.NoError(t, user_model.NewUserRedirect(t.Context(), user.ID, user.Name, "newusername"))
unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{
LowerName: user.LowerName,
@@ -434,17 +434,17 @@ func TestNewUserRedirect3(t *testing.T) {
func TestGetUserByOpenID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
_, err := user_model.GetUserByOpenID(db.DefaultContext, "https://unknown")
_, err := user_model.GetUserByOpenID(t.Context(), "https://unknown")
if assert.Error(t, err) {
assert.True(t, user_model.IsErrUserNotExist(err))
}
user, err := user_model.GetUserByOpenID(db.DefaultContext, "https://user1.domain1.tld")
user, err := user_model.GetUserByOpenID(t.Context(), "https://user1.domain1.tld")
if assert.NoError(t, err) {
assert.Equal(t, int64(1), user.ID)
}
user, err = user_model.GetUserByOpenID(db.DefaultContext, "https://domain1.tld/user2/")
user, err = user_model.GetUserByOpenID(t.Context(), "https://domain1.tld/user2/")
if assert.NoError(t, err) {
assert.Equal(t, int64(2), user.ID)
}
@@ -454,7 +454,7 @@ func TestFollowUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(follower, followed *user_model.User) {
assert.NoError(t, user_model.FollowUser(db.DefaultContext, follower, followed))
assert.NoError(t, user_model.FollowUser(t.Context(), follower, followed))
unittest.AssertExistsAndLoadBean(t, &user_model.Follow{UserID: follower.ID, FollowID: followed.ID})
}
@@ -465,7 +465,7 @@ func TestFollowUser(t *testing.T) {
testSuccess(user4, user2)
testSuccess(user5, user2)
assert.NoError(t, user_model.FollowUser(db.DefaultContext, user2, user2))
assert.NoError(t, user_model.FollowUser(t.Context(), user2, user2))
unittest.CheckConsistencyFor(t, &user_model.User{})
}
@@ -474,7 +474,7 @@ func TestUnfollowUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(followerID, followedID int64) {
assert.NoError(t, user_model.UnfollowUser(db.DefaultContext, followerID, followedID))
assert.NoError(t, user_model.UnfollowUser(t.Context(), followerID, followedID))
unittest.AssertNotExistsBean(t, &user_model.Follow{UserID: followerID, FollowID: followedID})
}
testSuccess(4, 2)
@@ -501,7 +501,7 @@ func TestIsUserVisibleToViewer(t *testing.T) {
}
return u.Name
}
assert.Equal(t, expected, user_model.IsUserVisibleToViewer(db.DefaultContext, u, viewer), "user %v should be visible to viewer %v: %v", name(u), name(viewer), expected)
assert.Equal(t, expected, user_model.IsUserVisibleToViewer(t.Context(), u, viewer), "user %v should be visible to viewer %v: %v", name(u), name(viewer), expected)
}
// admin viewer
@@ -636,11 +636,11 @@ func TestGetInactiveUsers(t *testing.T) {
// all inactive users
// user1's createdunix is 1730468968
users, err := user_model.GetInactiveUsers(db.DefaultContext, 0)
users, err := user_model.GetInactiveUsers(t.Context(), 0)
assert.NoError(t, err)
assert.Len(t, users, 1)
interval := time.Now().Unix() - 1730468968 + 3600*24
users, err = user_model.GetInactiveUsers(db.DefaultContext, time.Duration(interval*int64(time.Second)))
users, err = user_model.GetInactiveUsers(t.Context(), time.Duration(interval*int64(time.Second)))
assert.NoError(t, err)
assert.Empty(t, users)
}

View File

@@ -6,7 +6,6 @@ package webhook
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/optional"
@@ -16,20 +15,20 @@ import (
func TestGetSystemOrDefaultWebhooks(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hooks, err := GetSystemOrDefaultWebhooks(db.DefaultContext, optional.None[bool]())
hooks, err := GetSystemOrDefaultWebhooks(t.Context(), optional.None[bool]())
assert.NoError(t, err)
if assert.Len(t, hooks, 2) {
assert.Equal(t, int64(5), hooks[0].ID)
assert.Equal(t, int64(6), hooks[1].ID)
}
hooks, err = GetSystemOrDefaultWebhooks(db.DefaultContext, optional.Some(true))
hooks, err = GetSystemOrDefaultWebhooks(t.Context(), optional.Some(true))
assert.NoError(t, err)
if assert.Len(t, hooks, 1) {
assert.Equal(t, int64(5), hooks[0].ID)
}
hooks, err = GetSystemOrDefaultWebhooks(db.DefaultContext, optional.Some(false))
hooks, err = GetSystemOrDefaultWebhooks(t.Context(), optional.Some(false))
assert.NoError(t, err)
if assert.Len(t, hooks, 1) {
assert.Equal(t, int64(6), hooks[0].ID)

View File

@@ -31,7 +31,7 @@ func TestIsValidHookContentType(t *testing.T) {
func TestWebhook_History(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
webhook := unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 1})
tasks, err := webhook.History(db.DefaultContext, 0)
tasks, err := webhook.History(t.Context(), 0)
assert.NoError(t, err)
if assert.Len(t, tasks, 3) {
assert.Equal(t, int64(3), tasks[0].ID)
@@ -40,7 +40,7 @@ func TestWebhook_History(t *testing.T) {
}
webhook = unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 2})
tasks, err = webhook.History(db.DefaultContext, 0)
tasks, err = webhook.History(t.Context(), 0)
assert.NoError(t, err)
assert.Empty(t, tasks)
}
@@ -95,35 +95,35 @@ func TestCreateWebhook(t *testing.T) {
Events: `{"push_only":false,"send_everything":false,"choose_events":false,"events":{"create":false,"push":true,"pull_request":true}}`,
}
unittest.AssertNotExistsBean(t, hook)
assert.NoError(t, CreateWebhook(db.DefaultContext, hook))
assert.NoError(t, CreateWebhook(t.Context(), hook))
unittest.AssertExistsAndLoadBean(t, hook)
}
func TestGetWebhookByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hook, err := GetWebhookByRepoID(db.DefaultContext, 1, 1)
hook, err := GetWebhookByRepoID(t.Context(), 1, 1)
assert.NoError(t, err)
assert.Equal(t, int64(1), hook.ID)
_, err = GetWebhookByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)
_, err = GetWebhookByRepoID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
assert.Error(t, err)
assert.True(t, IsErrWebhookNotExist(err))
}
func TestGetWebhookByOwnerID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hook, err := GetWebhookByOwnerID(db.DefaultContext, 3, 3)
hook, err := GetWebhookByOwnerID(t.Context(), 3, 3)
assert.NoError(t, err)
assert.Equal(t, int64(3), hook.ID)
_, err = GetWebhookByOwnerID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)
_, err = GetWebhookByOwnerID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
assert.Error(t, err)
assert.True(t, IsErrWebhookNotExist(err))
}
func TestGetActiveWebhooksByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hooks, err := db.Find[Webhook](db.DefaultContext, ListWebhookOptions{RepoID: 1, IsActive: optional.Some(true)})
hooks, err := db.Find[Webhook](t.Context(), ListWebhookOptions{RepoID: 1, IsActive: optional.Some(true)})
assert.NoError(t, err)
if assert.Len(t, hooks, 1) {
assert.Equal(t, int64(1), hooks[0].ID)
@@ -133,7 +133,7 @@ func TestGetActiveWebhooksByRepoID(t *testing.T) {
func TestGetWebhooksByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hooks, err := db.Find[Webhook](db.DefaultContext, ListWebhookOptions{RepoID: 1})
hooks, err := db.Find[Webhook](t.Context(), ListWebhookOptions{RepoID: 1})
assert.NoError(t, err)
if assert.Len(t, hooks, 2) {
assert.Equal(t, int64(1), hooks[0].ID)
@@ -143,7 +143,7 @@ func TestGetWebhooksByRepoID(t *testing.T) {
func TestGetActiveWebhooksByOwnerID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hooks, err := db.Find[Webhook](db.DefaultContext, ListWebhookOptions{OwnerID: 3, IsActive: optional.Some(true)})
hooks, err := db.Find[Webhook](t.Context(), ListWebhookOptions{OwnerID: 3, IsActive: optional.Some(true)})
assert.NoError(t, err)
if assert.Len(t, hooks, 1) {
assert.Equal(t, int64(3), hooks[0].ID)
@@ -153,7 +153,7 @@ func TestGetActiveWebhooksByOwnerID(t *testing.T) {
func TestGetWebhooksByOwnerID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hooks, err := db.Find[Webhook](db.DefaultContext, ListWebhookOptions{OwnerID: 3})
hooks, err := db.Find[Webhook](t.Context(), ListWebhookOptions{OwnerID: 3})
assert.NoError(t, err)
if assert.Len(t, hooks, 1) {
assert.Equal(t, int64(3), hooks[0].ID)
@@ -167,17 +167,17 @@ func TestUpdateWebhook(t *testing.T) {
hook.IsActive = true
hook.ContentType = ContentTypeForm
unittest.AssertNotExistsBean(t, hook)
assert.NoError(t, UpdateWebhook(db.DefaultContext, hook))
assert.NoError(t, UpdateWebhook(t.Context(), hook))
unittest.AssertExistsAndLoadBean(t, hook)
}
func TestDeleteWebhookByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 2, RepoID: 1})
assert.NoError(t, DeleteWebhookByRepoID(db.DefaultContext, 1, 2))
assert.NoError(t, DeleteWebhookByRepoID(t.Context(), 1, 2))
unittest.AssertNotExistsBean(t, &Webhook{ID: 2, RepoID: 1})
err := DeleteWebhookByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)
err := DeleteWebhookByRepoID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
assert.Error(t, err)
assert.True(t, IsErrWebhookNotExist(err))
}
@@ -185,17 +185,17 @@ func TestDeleteWebhookByRepoID(t *testing.T) {
func TestDeleteWebhookByOwnerID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 3, OwnerID: 3})
assert.NoError(t, DeleteWebhookByOwnerID(db.DefaultContext, 3, 3))
assert.NoError(t, DeleteWebhookByOwnerID(t.Context(), 3, 3))
unittest.AssertNotExistsBean(t, &Webhook{ID: 3, OwnerID: 3})
err := DeleteWebhookByOwnerID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)
err := DeleteWebhookByOwnerID(t.Context(), unittest.NonexistentID, unittest.NonexistentID)
assert.Error(t, err)
assert.True(t, IsErrWebhookNotExist(err))
}
func TestHookTasks(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
hookTasks, err := HookTasks(db.DefaultContext, 1, 1)
hookTasks, err := HookTasks(t.Context(), 1, 1)
assert.NoError(t, err)
if assert.Len(t, hookTasks, 3) {
assert.Equal(t, int64(3), hookTasks[0].ID)
@@ -203,7 +203,7 @@ func TestHookTasks(t *testing.T) {
assert.Equal(t, int64(1), hookTasks[2].ID)
}
hookTasks, err = HookTasks(db.DefaultContext, unittest.NonexistentID, 1)
hookTasks, err = HookTasks(t.Context(), unittest.NonexistentID, 1)
assert.NoError(t, err)
assert.Empty(t, hookTasks)
}
@@ -215,7 +215,7 @@ func TestCreateHookTask(t *testing.T) {
PayloadVersion: 2,
}
unittest.AssertNotExistsBean(t, hookTask)
_, err := CreateHookTask(db.DefaultContext, hookTask)
_, err := CreateHookTask(t.Context(), hookTask)
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, hookTask)
}
@@ -227,7 +227,7 @@ func TestUpdateHookTask(t *testing.T) {
hook.PayloadContent = "new payload content"
hook.IsDelivered = true
unittest.AssertNotExistsBean(t, hook)
assert.NoError(t, UpdateHookTask(db.DefaultContext, hook))
assert.NoError(t, UpdateHookTask(t.Context(), hook))
unittest.AssertExistsAndLoadBean(t, hook)
}
@@ -240,7 +240,7 @@ func TestCleanupHookTaskTable_PerWebhook_DeletesDelivered(t *testing.T) {
PayloadVersion: 2,
}
unittest.AssertNotExistsBean(t, hookTask)
_, err := CreateHookTask(db.DefaultContext, hookTask)
_, err := CreateHookTask(t.Context(), hookTask)
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, hookTask)
@@ -256,7 +256,7 @@ func TestCleanupHookTaskTable_PerWebhook_LeavesUndelivered(t *testing.T) {
PayloadVersion: 2,
}
unittest.AssertNotExistsBean(t, hookTask)
_, err := CreateHookTask(db.DefaultContext, hookTask)
_, err := CreateHookTask(t.Context(), hookTask)
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, hookTask)
@@ -273,7 +273,7 @@ func TestCleanupHookTaskTable_PerWebhook_LeavesMostRecentTask(t *testing.T) {
PayloadVersion: 2,
}
unittest.AssertNotExistsBean(t, hookTask)
_, err := CreateHookTask(db.DefaultContext, hookTask)
_, err := CreateHookTask(t.Context(), hookTask)
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, hookTask)
@@ -290,7 +290,7 @@ func TestCleanupHookTaskTable_OlderThan_DeletesDelivered(t *testing.T) {
PayloadVersion: 2,
}
unittest.AssertNotExistsBean(t, hookTask)
_, err := CreateHookTask(db.DefaultContext, hookTask)
_, err := CreateHookTask(t.Context(), hookTask)
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, hookTask)
@@ -306,7 +306,7 @@ func TestCleanupHookTaskTable_OlderThan_LeavesUndelivered(t *testing.T) {
PayloadVersion: 2,
}
unittest.AssertNotExistsBean(t, hookTask)
_, err := CreateHookTask(db.DefaultContext, hookTask)
_, err := CreateHookTask(t.Context(), hookTask)
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, hookTask)
@@ -323,7 +323,7 @@ func TestCleanupHookTaskTable_OlderThan_LeavesTaskEarlierThanAgeToDelete(t *test
PayloadVersion: 2,
}
unittest.AssertNotExistsBean(t, hookTask)
_, err := CreateHookTask(db.DefaultContext, hookTask)
_, err := CreateHookTask(t.Context(), hookTask)
assert.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, hookTask)

View File

@@ -10,7 +10,6 @@ import (
"net/http/httptest"
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
@@ -22,7 +21,7 @@ func TestActivityPubSignedPost(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
pubID := "https://example.com/pubID"
c, err := NewClient(db.DefaultContext, user, pubID)
c, err := NewClient(t.Context(), user, pubID)
assert.NoError(t, err)
expected := "BODY"

View File

@@ -6,7 +6,6 @@ package activitypub
import (
"testing"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
@@ -18,12 +17,12 @@ import (
func TestUserSettings(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
pub, priv, err := GetKeyPair(db.DefaultContext, user1)
pub, priv, err := GetKeyPair(t.Context(), user1)
assert.NoError(t, err)
pub1, err := GetPublicKey(db.DefaultContext, user1)
pub1, err := GetPublicKey(t.Context(), user1)
assert.NoError(t, err)
assert.Equal(t, pub, pub1)
priv1, err := GetPrivateKey(db.DefaultContext, user1)
priv1, err := GetPrivateKey(t.Context(), user1)
assert.NoError(t, err)
assert.Equal(t, priv, priv1)
}

View File

@@ -30,7 +30,7 @@ func Init() error {
return err
}
go populateRepoIndexer(db.DefaultContext)
go populateRepoIndexer(graceful.GetManager().ShutdownContext())
return nil
}

View File

@@ -7,7 +7,6 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/queue"
@@ -33,7 +32,7 @@ func TestRepoStatsIndex(t *testing.T) {
err := Init()
assert.NoError(t, err)
repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 1)
repo, err := repo_model.GetRepositoryByID(t.Context(), 1)
assert.NoError(t, err)
err = UpdateRepoIndexer(repo)
@@ -41,10 +40,10 @@ func TestRepoStatsIndex(t *testing.T) {
assert.NoError(t, queue.GetManager().FlushAll(t.Context(), 5*time.Second))
status, err := repo_model.GetIndexerStatus(db.DefaultContext, repo, repo_model.RepoIndexerTypeStats)
status, err := repo_model.GetIndexerStatus(t.Context(), repo, repo_model.RepoIndexerTypeStats)
assert.NoError(t, err)
assert.Equal(t, "65f1bf27bc3bf70f64657658635e66094edbcb4d", status.CommitSha)
langs, err := repo_model.GetTopLanguageStats(db.DefaultContext, repo, 5)
langs, err := repo_model.GetTopLanguageStats(t.Context(), repo, 5)
assert.NoError(t, err)
assert.Empty(t, langs)
}

View File

@@ -7,7 +7,7 @@ import (
"runtime"
activities_model "code.gitea.io/gitea/models/activities"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/setting"
"github.com/prometheus/client_golang/prometheus"
@@ -233,7 +233,7 @@ func (c Collector) Describe(ch chan<- *prometheus.Desc) {
// Collect returns the metrics with values
func (c Collector) Collect(ch chan<- prometheus.Metric) {
stats := activities_model.GetStatistic(db.DefaultContext)
stats := activities_model.GetStatistic(graceful.GetManager().ShutdownContext())
ch <- prometheus.MustNewConstMetric(
c.Accesses,

View File

@@ -16,16 +16,16 @@ import (
func TestSyncRepoBranches(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
_, err := db.GetEngine(db.DefaultContext).ID(1).Update(&repo_model.Repository{ObjectFormatName: "bad-fmt"})
assert.NoError(t, db.TruncateBeans(db.DefaultContext, &git_model.Branch{}))
_, err := db.GetEngine(t.Context()).ID(1).Update(&repo_model.Repository{ObjectFormatName: "bad-fmt"})
assert.NoError(t, db.TruncateBeans(t.Context(), &git_model.Branch{}))
assert.NoError(t, err)
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
assert.Equal(t, "bad-fmt", repo.ObjectFormatName)
_, err = SyncRepoBranches(db.DefaultContext, 1, 0)
_, err = SyncRepoBranches(t.Context(), 1, 0)
assert.NoError(t, err)
repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
assert.Equal(t, "sha1", repo.ObjectFormatName)
branch, err := git_model.GetBranch(db.DefaultContext, 1, "master")
branch, err := git_model.GetBranch(t.Context(), 1, "master")
assert.NoError(t, err)
assert.Equal(t, "master", branch.Name)
}

View File

@@ -8,7 +8,6 @@ import (
"testing"
"time"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/git"
@@ -125,11 +124,11 @@ func TestPushCommits_AvatarLink(t *testing.T) {
assert.Equal(t,
"/avatars/ab53a2911ddf9b4817ac01ddcd3d975f?size="+strconv.Itoa(28*setting.Avatar.RenderedSizeFactor),
pushCommits.AvatarLink(db.DefaultContext, "user2@example.com"))
pushCommits.AvatarLink(t.Context(), "user2@example.com"))
assert.Equal(t,
"/assets/img/avatar_default.png",
pushCommits.AvatarLink(db.DefaultContext, "nonexistent@example.com"))
pushCommits.AvatarLink(t.Context(), "nonexistent@example.com"))
}
func TestCommitToPushCommit(t *testing.T) {

View File

@@ -6,7 +6,6 @@ package repository
import (
"testing"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest"
@@ -15,7 +14,7 @@ import (
func TestGetDirectorySize(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 1)
repo, err := repo_model.GetRepositoryByID(t.Context(), 1)
assert.NoError(t, err)
size, err := getDirectorySize(repo.RepoPath())
assert.NoError(t, err)

View File

@@ -4,11 +4,11 @@
package session
import (
"context"
"log"
"sync"
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/modules/timeutil"
"gitea.com/go-chi/session"
@@ -21,6 +21,10 @@ type DBStore struct {
data map[any]any
}
func dbContext() context.Context {
return context.Background()
}
// NewDBStore creates and returns a DB session store.
func NewDBStore(sid string, kv map[any]any) *DBStore {
return &DBStore{
@@ -72,7 +76,7 @@ func (s *DBStore) Release() error {
return err
}
return auth.UpdateSession(db.DefaultContext, s.sid, data)
return auth.UpdateSession(dbContext(), s.sid, data)
}
// Flush deletes all session data.
@@ -98,7 +102,7 @@ func (p *DBProvider) Init(maxLifetime int64, connStr string) error {
// Read returns raw session store by session ID.
func (p *DBProvider) Read(sid string) (session.RawStore, error) {
s, err := auth.ReadSession(db.DefaultContext, sid)
s, err := auth.ReadSession(dbContext(), sid)
if err != nil {
return nil, err
}
@@ -118,7 +122,7 @@ func (p *DBProvider) Read(sid string) (session.RawStore, error) {
// Exist returns true if session with given ID exists.
func (p *DBProvider) Exist(sid string) bool {
has, err := auth.ExistSession(db.DefaultContext, sid)
has, err := auth.ExistSession(dbContext(), sid)
if err != nil {
panic("session/DB: error checking existence: " + err.Error())
}
@@ -127,12 +131,12 @@ func (p *DBProvider) Exist(sid string) bool {
// Destroy deletes a session by session ID.
func (p *DBProvider) Destroy(sid string) error {
return auth.DestroySession(db.DefaultContext, sid)
return auth.DestroySession(dbContext(), sid)
}
// Regenerate regenerates a session store from old session ID to new one.
func (p *DBProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err error) {
s, err := auth.RegenerateSession(db.DefaultContext, oldsid, sid)
s, err := auth.RegenerateSession(dbContext(), oldsid, sid)
if err != nil {
return nil, err
}
@@ -152,7 +156,7 @@ func (p *DBProvider) Regenerate(oldsid, sid string) (_ session.RawStore, err err
// Count counts and returns number of sessions.
func (p *DBProvider) Count() int {
total, err := auth.CountSessions(db.DefaultContext)
total, err := auth.CountSessions(dbContext())
if err != nil {
panic("session/DB: error counting records: " + err.Error())
}
@@ -161,7 +165,7 @@ func (p *DBProvider) Count() int {
// GC calls GC to clean expired sessions.
func (p *DBProvider) GC() {
if err := auth.CleanupSessions(db.DefaultContext, p.maxLifetime); err != nil {
if err := auth.CleanupSessions(dbContext(), p.maxLifetime); err != nil {
log.Printf("session/DB: error garbage collecting: %v", err)
}
}

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