From 0cbaa0b66201cd9c657188b3985dc38261c3a807 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Thu, 28 Aug 2025 11:52:43 +0800 Subject: [PATCH] Remove incorrect "db.DefaultContext" usages (#35366) --- cmd/admin_user_change_password_test.go | 4 +- cmd/admin_user_create_test.go | 6 +- cmd/admin_user_delete_test.go | 12 +-- cmd/admin_user_must_change_password_test.go | 2 +- cmd/migrate_storage_test.go | 3 +- models/actions/runner_token_test.go | 11 +- models/activities/action_test.go | 32 +++--- models/activities/notification_test.go | 24 ++--- models/activities/user_heatmap_test.go | 5 +- models/asymkey/gpg_key_test.go | 8 +- models/asymkey/ssh_key_test.go | 3 +- models/auth/access_token_test.go | 34 +++--- models/auth/oauth2_test.go | 39 ++++--- models/auth/source_test.go | 5 +- models/auth/webauthn_test.go | 13 ++- models/avatars/avatar_test.go | 11 +- models/db/context.go | 33 +++--- models/db/context_committer_test.go | 2 +- models/db/context_test.go | 26 ++--- models/db/engine.go | 6 ++ models/db/engine_init.go | 12 +-- models/db/engine_test.go | 12 +-- models/db/index_test.go | 32 +++--- models/db/install/db.go | 21 ++-- models/db/iterate_test.go | 6 +- models/db/list_test.go | 8 +- models/dbfs/dbfs_test.go | 24 ++--- models/git/branch_test.go | 28 ++--- models/git/commit_status_test.go | 30 +++--- models/git/protected_branch_test.go | 12 +-- models/git/protected_tag_test.go | 19 ++-- models/issues/assignees_test.go | 35 +++--- models/issues/comment_test.go | 16 +-- models/issues/content_history_test.go | 16 +-- models/issues/dependency_test.go | 27 +++-- models/issues/issue_label_test.go | 3 +- models/issues/issue_list_test.go | 5 +- models/issues/issue_test.go | 46 ++++---- models/issues/issue_user_test.go | 12 +-- models/issues/issue_watch_test.go | 18 ++-- models/issues/issue_xref_test.go | 12 +-- models/issues/label_test.go | 100 ++++++++--------- models/issues/milestone_test.go | 50 ++++----- models/issues/pull_list_test.go | 9 +- models/issues/pull_test.go | 102 +++++++++--------- models/issues/review_test.go | 75 +++++++------ models/issues/stopwatch_test.go | 23 ++-- models/issues/tracked_time_test.go | 37 ++++--- models/migrations/v1_22/v293_test.go | 5 +- models/organization/org_list_test.go | 16 +-- models/organization/org_test.go | 100 ++++++++--------- models/organization/org_user_test.go | 21 ++-- models/organization/org_worktime.go | 13 +-- models/organization/team_invite_test.go | 11 +- models/organization/team_list_test.go | 3 +- models/organization/team_repo_test.go | 3 +- models/organization/team_test.go | 38 +++---- models/packages/package_test.go | 13 ++- models/perm/access/access_test.go | 38 +++---- models/project/column_test.go | 35 +++--- models/project/project_test.go | 18 ++-- models/repo/attachment_test.go | 27 +++-- models/repo/avatar_test.go | 5 +- models/repo/collaboration_test.go | 32 +++--- models/repo/fork_test.go | 9 +- models/repo/pushmirror_test.go | 8 +- models/repo/redirect_test.go | 11 +- models/repo/release_test.go | 5 +- models/repo/repo_list_test.go | 20 ++-- models/repo/repo_test.go | 25 +++-- models/repo/star_test.go | 22 ++-- models/repo/topic_test.go | 20 ++-- models/repo/user_repo_test.go | 13 ++- models/repo/watch_test.go | 50 ++++----- models/repo_test.go | 7 +- models/system/notice.go | 10 +- models/system/notice_test.go | 14 +-- models/system/setting_test.go | 16 +-- models/unittest/consistency.go | 27 ++--- models/unittest/fixtures.go | 2 +- models/unittest/unit_tests.go | 42 ++++---- models/user/avatar_test.go | 9 +- models/user/email_address_test.go | 36 +++---- models/user/follow_test.go | 11 +- models/user/openid_test.go | 15 ++- models/user/redirect_test.go | 5 +- models/user/setting_test.go | 19 ++-- models/user/user_system_test.go | 8 +- models/user/user_test.go | 56 +++++----- models/webhook/webhook_system_test.go | 7 +- models/webhook/webhook_test.go | 52 ++++----- modules/activitypub/client_test.go | 3 +- modules/activitypub/user_settings_test.go | 7 +- modules/indexer/stats/indexer.go | 2 +- modules/indexer/stats/indexer_test.go | 7 +- modules/metrics/collector.go | 4 +- modules/repository/branch_test.go | 8 +- modules/repository/commits_test.go | 5 +- modules/repository/create_test.go | 3 +- modules/session/db.go | 20 ++-- modules/system/appstate_test.go | 11 +- routers/api/v1/api.go | 4 +- routers/install/install.go | 6 +- routers/private/hook_post_receive_test.go | 9 +- routers/web/auth/auth_test.go | 3 +- routers/web/auth/oauth_test.go | 9 +- routers/web/org/worktime.go | 6 +- routers/web/repo/actions/actions_test.go | 4 +- routers/web/repo/pull_review_test.go | 12 +-- routers/web/repo/setting/settings_test.go | 9 +- routers/web/repo/wiki_test.go | 11 +- routers/web/user/home_test.go | 3 +- routers/web/web.go | 4 +- services/actions/init_test.go | 14 +-- services/asymkey/ssh_key_test.go | 6 +- services/attachment/attachment_test.go | 5 +- services/auth/auth_token_test.go | 31 +++--- services/convert/pull_review_test.go | 9 +- services/convert/pull_test.go | 11 +- services/convert/release_test.go | 5 +- services/convert/user_test.go | 9 +- services/doctor/dbconsistency_test.go | 14 +-- services/feed/feed_test.go | 28 ++--- services/feed/notifier_test.go | 3 +- services/gitdiff/csv_test.go | 3 +- services/gitdiff/git_diff_tree_test.go | 5 +- services/gitdiff/gitdiff_test.go | 29 +++-- services/gitdiff/submodule_test.go | 3 +- services/issue/assignee_test.go | 13 ++- services/issue/commit_test.go | 17 ++- services/issue/issue_test.go | 29 +++-- services/issue/label_test.go | 5 +- services/issue/milestone_test.go | 7 +- services/issue/reaction_test.go | 17 ++- services/issue/suggestion_test.go | 3 +- services/mailer/mail_test.go | 7 +- services/markup/renderhelper_mention_test.go | 3 +- services/migrations/gitea_uploader_test.go | 22 ++-- services/org/org_test.go | 7 +- services/org/team.go | 4 +- services/org/team_test.go | 49 +++++---- services/org/user_test.go | 9 +- services/packages/arch/vercmp.go | 5 +- services/packages/container/common.go | 2 +- services/projects/issue_test.go | 44 ++++---- services/pull/check_test.go | 2 +- services/pull/lfs.go | 3 +- services/pull/pull_test.go | 13 ++- services/pull/review_test.go | 19 ++-- services/pull/reviewer_test.go | 7 +- services/release/release_test.go | 51 +++++---- services/repository/adopt.go | 3 +- services/repository/adopt_test.go | 14 +-- services/repository/archiver/archiver_test.go | 13 ++- services/repository/avatar_test.go | 11 +- services/repository/collaboration_test.go | 11 +- .../repository/contributors_graph_test.go | 3 +- services/repository/create.go | 3 +- services/repository/create_test.go | 5 +- services/repository/delete.go | 4 +- services/repository/delete_test.go | 7 +- services/repository/fork_test.go | 5 +- services/repository/lfs_test.go | 7 +- services/repository/repo_team_test.go | 5 +- services/repository/repository_test.go | 10 +- services/repository/transfer_test.go | 45 ++++---- services/task/task.go | 3 +- services/uinotification/notify.go | 2 +- services/user/block_test.go | 35 +++--- services/user/email_test.go | 47 ++++---- services/user/update_test.go | 15 ++- services/user/user_test.go | 50 ++++----- services/webhook/deliver_test.go | 15 ++- services/webhook/webhook_test.go | 11 +- tests/integration/actions_trigger_test.go | 88 +++++++-------- .../api_activitypub_person_test.go | 3 +- tests/integration/api_branch_test.go | 8 +- .../api_comment_attachment_test.go | 5 +- tests/integration/api_comment_test.go | 11 +- tests/integration/api_fork_test.go | 11 +- tests/integration/api_issue_reaction_test.go | 13 ++- tests/integration/api_issue_stopwatch_test.go | 7 +- .../api_issue_subscription_test.go | 3 +- tests/integration/api_issue_test.go | 5 +- .../api_issue_tracked_time_test.go | 15 ++- tests/integration/api_notification_test.go | 7 +- tests/integration/api_org_test.go | 3 +- tests/integration/api_packages_alpine_test.go | 9 +- tests/integration/api_packages_arch_test.go | 9 +- tests/integration/api_packages_cargo_test.go | 23 ++-- tests/integration/api_packages_chef_test.go | 13 ++- .../integration/api_packages_composer_test.go | 19 ++-- tests/integration/api_packages_conan_test.go | 25 +++-- tests/integration/api_packages_conda_test.go | 17 ++- .../api_packages_container_test.go | 27 +++-- tests/integration/api_packages_cran_test.go | 11 +- tests/integration/api_packages_debian_test.go | 13 ++- .../integration/api_packages_generic_test.go | 19 ++-- .../integration/api_packages_goproxy_test.go | 9 +- tests/integration/api_packages_helm_test.go | 11 +- tests/integration/api_packages_maven_test.go | 31 +++--- tests/integration/api_packages_npm_test.go | 19 ++-- tests/integration/api_packages_nuget_test.go | 39 ++++--- tests/integration/api_packages_pub_test.go | 9 +- tests/integration/api_packages_pypi_test.go | 29 +++-- tests/integration/api_packages_rpm_test.go | 11 +- .../integration/api_packages_rubygems_test.go | 15 ++- tests/integration/api_packages_swift_test.go | 21 ++-- tests/integration/api_packages_test.go | 32 +++--- .../integration/api_packages_vagrant_test.go | 9 +- tests/integration/api_pull_commits_test.go | 3 +- tests/integration/api_pull_review_test.go | 22 ++-- tests/integration/api_pull_test.go | 9 +- tests/integration/api_repo_edit_test.go | 23 ++-- tests/integration/api_repo_lfs_test.go | 19 ++-- tests/integration/api_repo_test.go | 11 +- tests/integration/api_team_test.go | 11 +- tests/integration/api_team_user_test.go | 3 +- tests/integration/api_twofa_test.go | 3 +- tests/integration/api_user_block_test.go | 10 +- tests/integration/api_user_orgs_test.go | 13 ++- tests/integration/auth_ldap_test.go | 38 +++---- tests/integration/compare_test.go | 3 +- tests/integration/db_collation_test.go | 4 +- tests/integration/empty_repo_test.go | 2 +- tests/integration/eventsource_test.go | 3 +- tests/integration/git_general_test.go | 9 +- tests/integration/git_misc_test.go | 19 ++-- tests/integration/git_push_test.go | 6 +- tests/integration/incoming_email_test.go | 33 +++--- tests/integration/issue_test.go | 5 +- tests/integration/lfs_getobject_test.go | 11 +- tests/integration/lfs_view_test.go | 2 +- tests/integration/linguist_test.go | 5 +- tests/integration/migrate_test.go | 3 +- tests/integration/mirror_pull_test.go | 8 +- tests/integration/mirror_push_test.go | 10 +- tests/integration/oauth_test.go | 10 +- tests/integration/org_count_test.go | 2 +- tests/integration/org_team_invite_test.go | 31 +++--- tests/integration/org_worktime_test.go | 13 ++- tests/integration/project_test.go | 13 ++- tests/integration/pull_compare_test.go | 3 +- tests/integration/pull_merge_test.go | 47 ++++---- tests/integration/pull_review_test.go | 30 +++--- tests/integration/pull_update_test.go | 13 ++- tests/integration/repo_fork_test.go | 11 +- tests/integration/repo_merge_upstream_test.go | 2 +- tests/integration/repo_search_test.go | 5 +- tests/integration/repo_tag_test.go | 8 +- tests/integration/repo_test.go | 5 +- tests/integration/session_test.go | 7 +- tests/integration/signin_test.go | 2 +- tests/integration/signup_test.go | 2 +- tests/integration/user_avatar_test.go | 3 +- tests/test_utils.go | 2 +- 256 files changed, 1951 insertions(+), 2098 deletions(-) diff --git a/cmd/admin_user_change_password_test.go b/cmd/admin_user_change_password_test.go index 17d0382af7..902632f3e4 100644 --- a/cmd/admin_user_change_password_test.go +++ b/cmd/admin_user_change_password_test.go @@ -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"}) diff --git a/cmd/admin_user_create_test.go b/cmd/admin_user_create_test.go index 437e07d9a2..dbe949ff8d 100644 --- a/cmd/admin_user_create_test.go +++ b/cmd/admin_user_create_test.go @@ -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) { diff --git a/cmd/admin_user_delete_test.go b/cmd/admin_user_delete_test.go index d0330582d7..b68b358152 100644 --- a/cmd/admin_user_delete_test.go +++ b/cmd/admin_user_delete_test.go @@ -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{})) } } diff --git a/cmd/admin_user_must_change_password_test.go b/cmd/admin_user_must_change_password_test.go index a6611fdc04..efdbe3a9ee 100644 --- a/cmd/admin_user_must_change_password_test.go +++ b/cmd/admin_user_must_change_password_test.go @@ -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) diff --git a/cmd/migrate_storage_test.go b/cmd/migrate_storage_test.go index 6817867e28..3ea193eb1e 100644 --- a/cmd/migrate_storage_test.go +++ b/cmd/migrate_storage_test.go @@ -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, diff --git a/models/actions/runner_token_test.go b/models/actions/runner_token_test.go index 21614b7086..243d6716a0 100644 --- a/models/actions/runner_token_test.go +++ b/models/actions/runner_token_test.go @@ -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) } diff --git a/models/activities/action_test.go b/models/activities/action_test.go index ff311ac891..9447f39d62 100644 --- a/models/activities/action_test.go +++ b/models/activities/action_test.go @@ -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) } diff --git a/models/activities/notification_test.go b/models/activities/notification_test.go index 5d2a29bc36..6f2253c815 100644 --- a/models/activities/notification_test.go +++ b/models/activities/notification_test.go @@ -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) } diff --git a/models/activities/user_heatmap_test.go b/models/activities/user_heatmap_test.go index 380045d3c5..66087325b1 100644 --- a/models/activities/user_heatmap_test.go +++ b/models/activities/user_heatmap_test.go @@ -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) diff --git a/models/asymkey/gpg_key_test.go b/models/asymkey/gpg_key_test.go index 408cf15763..4621337f11 100644 --- a/models/asymkey/gpg_key_test.go +++ b/models/asymkey/gpg_key_test.go @@ -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 diff --git a/models/asymkey/ssh_key_test.go b/models/asymkey/ssh_key_test.go index 21e4ddf62e..d7f48ada03 100644 --- a/models/asymkey/ssh_key_test.go +++ b/models/asymkey/ssh_key_test.go @@ -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]) diff --git a/models/auth/access_token_test.go b/models/auth/access_token_test.go index 4360f1a214..9ae072cc5f 100644 --- a/models/auth/access_token_test.go +++ b/models/auth/access_token_test.go @@ -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)) } diff --git a/models/auth/oauth2_test.go b/models/auth/oauth2_test.go index c6626b283e..97f750755a 100644 --- a/models/auth/oauth2_test.go +++ b/models/auth/oauth2_test.go @@ -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"}) } diff --git a/models/auth/source_test.go b/models/auth/source_test.go index 64c7460b64..285f55a24b 100644 --- a/models/auth/source_test.go +++ b/models/auth/source_test.go @@ -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"`) } diff --git a/models/auth/webauthn_test.go b/models/auth/webauthn_test.go index 654427e974..41c5f6de94 100644 --- a/models/auth/webauthn_test.go +++ b/models/auth/webauthn_test.go @@ -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) diff --git a/models/avatars/avatar_test.go b/models/avatars/avatar_test.go index c8f7a6574b..43a062cc2a 100644 --- a/models/avatars/avatar_test.go +++ b/models/avatars/avatar_test.go @@ -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), ) } diff --git a/models/db/context.go b/models/db/context.go index ad99ada8c8..cac9721747 100644 --- a/models/db/context.go +++ b/models/db/context.go @@ -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, diff --git a/models/db/context_committer_test.go b/models/db/context_committer_test.go index 849c5dea41..90f6aaefa1 100644 --- a/models/db/context_committer_test.go +++ b/models/db/context_committer_test.go @@ -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 } diff --git a/models/db/context_test.go b/models/db/context_test.go index a6bd11d2ae..1bc84ffbf9 100644 --- a/models/db/context_test.go +++ b/models/db/context_test.go @@ -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 }) }) diff --git a/models/db/engine.go b/models/db/engine.go index ba287d58f0..4b12925b1c 100755 --- a/models/db/engine.go +++ b/models/db/engine.go @@ -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) diff --git a/models/db/engine_init.go b/models/db/engine_init.go index bb02aff274..373a99e7b5 100644 --- a/models/db/engine_init.go +++ b/models/db/engine_init.go @@ -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 diff --git a/models/db/engine_test.go b/models/db/engine_test.go index a236f83735..167525a5a8 100644 --- a/models/db/engine_test.go +++ b/models/db/engine_test.go @@ -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) } diff --git a/models/db/index_test.go b/models/db/index_test.go index 5fce0a6012..e2af7f35bb 100644 --- a/models/db/index_test.go +++ b/models/db/index_test.go @@ -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 } diff --git a/models/db/install/db.go b/models/db/install/db.go index 1b3b2ec3e9..a84e5e54fe 100644 --- a/models/db/install/db.go +++ b/models/db/install/db.go @@ -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 diff --git a/models/db/iterate_test.go b/models/db/iterate_test.go index e9f2790671..21bb0c0b4b 100644 --- a/models/db/iterate_test.go +++ b/models/db/iterate_test.go @@ -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 diff --git a/models/db/list_test.go b/models/db/list_test.go index 170473a968..ddcfff1f88 100644 --- a/models/db/list_test.go +++ b/models/db/list_test.go @@ -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) diff --git a/models/dbfs/dbfs_test.go b/models/dbfs/dbfs_test.go index 0257d2bd15..e1ecd871e4 100644 --- a/models/dbfs/dbfs_test.go +++ b/models/dbfs/dbfs_test.go @@ -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() diff --git a/models/git/branch_test.go b/models/git/branch_test.go index 252dcc5690..5be435172b 100644 --- a/models/git/branch_test.go +++ b/models/git/branch_test.go @@ -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) diff --git a/models/git/commit_status_test.go b/models/git/commit_status_test.go index eea7807237..d1b9dfc3bf 100644 --- a/models/git/commit_status_test.go +++ b/models/git/commit_status_test.go @@ -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) } diff --git a/models/git/protected_branch_test.go b/models/git/protected_branch_test.go index 367992081d..3aa1d7daa8 100644 --- a/models/git/protected_branch_test.go +++ b/models/git/protected_branch_test.go @@ -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) } diff --git a/models/git/protected_tag_test.go b/models/git/protected_tag_test.go index 164c33e28f..252eaf1bba 100644 --- a/models/git/protected_tag_test.go +++ b/models/git/protected_tag_test.go @@ -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) } diff --git a/models/issues/assignees_test.go b/models/issues/assignees_test.go index 2c33efd99e..13922899dc 100644 --- a/models/issues/assignees_test.go +++ b/models/issues/assignees_test.go @@ -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) } diff --git a/models/issues/comment_test.go b/models/issues/comment_test.go index c08e3b970d..3660f9c939 100644 --- a/models/issues/comment_test.go +++ b/models/issues/comment_test.go @@ -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) } diff --git a/models/issues/content_history_test.go b/models/issues/content_history_test.go index 1caa73a948..d2fcc82b1d 100644 --- a/models/issues/content_history_test.go +++ b/models/issues/content_history_test.go @@ -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) } diff --git a/models/issues/dependency_test.go b/models/issues/dependency_test.go index 67418039de..0e6a870ff9 100644 --- a/models/issues/dependency_test.go +++ b/models/issues/dependency_test.go @@ -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) } diff --git a/models/issues/issue_label_test.go b/models/issues/issue_label_test.go index 0470b99e24..6ccf6debae 100644 --- a/models/issues/issue_label_test.go +++ b/models/issues/issue_label_test.go @@ -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) diff --git a/models/issues/issue_list_test.go b/models/issues/issue_list_test.go index 5b4d2ca5ab..e9dc412331 100644 --- a/models/issues/issue_list_test.go +++ b/models/issues/issue_list_test.go @@ -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 { diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go index 1c5db55bbc..09fd492667 100644 --- a/models/issues/issue_test.go +++ b/models/issues/issue_test.go @@ -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}) diff --git a/models/issues/issue_user_test.go b/models/issues/issue_user_test.go index 7c21aa15ee..ec6d85c2bb 100644 --- a/models/issues/issue_user_test.go +++ b/models/issues/issue_user_test.go @@ -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") } diff --git a/models/issues/issue_watch_test.go b/models/issues/issue_watch_test.go index fad94e243e..c860e8b8ca 100644 --- a/models/issues/issue_watch_test.go +++ b/models/issues/issue_watch_test.go @@ -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) diff --git a/models/issues/issue_xref_test.go b/models/issues/issue_xref_test.go index 7f257330b7..b25a704bec 100644 --- a/models/issues/issue_xref_test.go +++ b/models/issues/issue_xref_test.go @@ -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) diff --git a/models/issues/label_test.go b/models/issues/label_test.go index 226036d543..50393855d9 100644 --- a/models/issues/label_test.go +++ b/models/issues/label_test.go @@ -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)) diff --git a/models/issues/milestone_test.go b/models/issues/milestone_test.go index f73355c27d..107ad305d4 100644 --- a/models/issues/milestone_test.go +++ b/models/issues/milestone_test.go @@ -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}) diff --git a/models/issues/pull_list_test.go b/models/issues/pull_list_test.go index eb2de006d6..437830701c 100644 --- a/models/issues/pull_list_test.go +++ b/models/issues/pull_list_test.go @@ -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) diff --git a/models/issues/pull_test.go b/models/issues/pull_test.go index 39efaa5792..7089af253b 100644 --- a/models/issues/pull_test.go +++ b/models/issues/pull_test.go @@ -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 \nReviewed-by: Org Six \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}) diff --git a/models/issues/review_test.go b/models/issues/review_test.go index 2588b8ba41..7b8537cc7d 100644 --- a/models/issues/review_test.go +++ b/models/issues/review_test.go @@ -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)) } diff --git a/models/issues/stopwatch_test.go b/models/issues/stopwatch_test.go index 6333c10234..684ec6cd31 100644 --- a/models/issues/stopwatch_test.go +++ b/models/issues/stopwatch_test.go @@ -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) } diff --git a/models/issues/tracked_time_test.go b/models/issues/tracked_time_test.go index 44054a1b83..ef7c72958f 100644 --- a/models/issues/tracked_time_test.go +++ b/models/issues/tracked_time_test.go @@ -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) } diff --git a/models/migrations/v1_22/v293_test.go b/models/migrations/v1_22/v293_test.go index 2c8f7683a8..c7b643c7e0 100644 --- a/models/migrations/v1_22/v293_test.go +++ b/models/migrations/v1_22/v293_test.go @@ -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) diff --git a/models/organization/org_list_test.go b/models/organization/org_list_test.go index a2a25c6f91..b2a1044422 100644 --- a/models/organization/org_list_test.go +++ b/models/organization/org_list_test.go @@ -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) diff --git a/models/organization/org_test.go b/models/organization/org_test.go index 234325a8cd..e7c4d2f9f7 100644 --- a/models/organization/org_test.go +++ b/models/organization/org_test.go @@ -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{}) diff --git a/models/organization/org_user_test.go b/models/organization/org_user_test.go index 689544430d..d21df4b474 100644 --- a/models/organization/org_user_test.go +++ b/models/organization/org_user_test.go @@ -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) diff --git a/models/organization/org_worktime.go b/models/organization/org_worktime.go index 7b57182a8a..3ef3e512ad 100644 --- a/models/organization/org_worktime.go +++ b/models/organization/org_worktime.go @@ -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"). diff --git a/models/organization/team_invite_test.go b/models/organization/team_invite_test.go index 45db8494e8..e9fabed1db 100644 --- a/models/organization/team_invite_test.go +++ b/models/organization/team_invite_test.go @@ -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) }) } diff --git a/models/organization/team_list_test.go b/models/organization/team_list_test.go index 5526446e22..df73f95898 100644 --- a/models/organization/team_list_test.go +++ b/models/organization/team_list_test.go @@ -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) diff --git a/models/organization/team_repo_test.go b/models/organization/team_repo_test.go index 73a06a93c2..af959f4658 100644 --- a/models/organization/team_repo_test.go +++ b/models/organization/team_repo_test.go @@ -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) diff --git a/models/organization/team_test.go b/models/organization/team_test.go index b0bf842584..fea5e8990a 100644 --- a/models/organization/team_test.go +++ b/models/organization/team_test.go @@ -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) } diff --git a/models/packages/package_test.go b/models/packages/package_test.go index 7f03151e77..9c71f2980d 100644 --- a/models/packages/package_test.go +++ b/models/packages/package_test.go @@ -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) } diff --git a/models/perm/access/access_test.go b/models/perm/access/access_test.go index 51d625707c..f01993ab4e 100644 --- a/models/perm/access/access_test.go +++ b/models/perm/access/access_test.go @@ -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) } diff --git a/models/project/column_test.go b/models/project/column_test.go index 6a615090a5..948e012c62 100644 --- a/models/project/column_test.go +++ b/models/project/column_test.go @@ -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, }) diff --git a/models/project/project_test.go b/models/project/project_test.go index c2e924e8ae..4b24615979 100644 --- a/models/project/project_test.go +++ b/models/project/project_test.go @@ -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) diff --git a/models/repo/attachment_test.go b/models/repo/attachment_test.go index c059ffd39a..d41008344d 100644 --- a/models/repo/attachment_test.go +++ b/models/repo/attachment_test.go @@ -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) diff --git a/models/repo/avatar_test.go b/models/repo/avatar_test.go index fc1f8baeca..f683a13e84 100644 --- a/models/repo/avatar_test.go +++ b/models/repo/avatar_test.go @@ -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) } diff --git a/models/repo/collaboration_test.go b/models/repo/collaboration_test.go index 1e0c84092b..7e06bffb72 100644 --- a/models/repo/collaboration_test.go +++ b/models/repo/collaboration_test.go @@ -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) } diff --git a/models/repo/fork_test.go b/models/repo/fork_test.go index e8dca204cc..e33b6f2f0a 100644 --- a/models/repo/fork_test.go +++ b/models/repo/fork_test.go @@ -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) } diff --git a/models/repo/pushmirror_test.go b/models/repo/pushmirror_test.go index 9fb7471147..777cc5982f 100644 --- a/models/repo/pushmirror_test.go +++ b/models/repo/pushmirror_test.go @@ -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) diff --git a/models/repo/redirect_test.go b/models/repo/redirect_test.go index 24cf7e89fb..aa5e5b7c6b 100644 --- a/models/repo/redirect_test.go +++ b/models/repo/redirect_test.go @@ -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, diff --git a/models/repo/release_test.go b/models/repo/release_test.go index 41ea083229..01f0fb3cff 100644 --- a/models/repo/release_test.go +++ b/models/repo/release_test.go @@ -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"] diff --git a/models/repo/repo_list_test.go b/models/repo/repo_list_test.go index 7eb76416c2..6cc0d3155c 100644 --- a/models/repo/repo_list_test.go +++ b/models/repo/repo_list_test.go @@ -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) }) diff --git a/models/repo/repo_test.go b/models/repo/repo_test.go index 66abe864fc..ce17789a3b 100644 --- a/models/repo/repo_test.go +++ b/models/repo/repo_test.go @@ -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) diff --git a/models/repo/star_test.go b/models/repo/star_test.go index b540f54310..4fd256cd08 100644 --- a/models/repo/star_test.go +++ b/models/repo/star_test.go @@ -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) } diff --git a/models/repo/topic_test.go b/models/repo/topic_test.go index b6a7aed7b1..903b9ad3fa 100644 --- a/models/repo/topic_test.go +++ b/models/repo/topic_test.go @@ -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) diff --git a/models/repo/user_repo_test.go b/models/repo/user_repo_test.go index 50c970344c..a53cf39dc4 100644 --- a/models/repo/user_repo_test.go +++ b/models/repo/user_repo_test.go @@ -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) diff --git a/models/repo/watch_test.go b/models/repo/watch_test.go index 7ed72386c9..19e363f6b0 100644 --- a/models/repo/watch_test.go +++ b/models/repo/watch_test.go @@ -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) } diff --git a/models/repo_test.go b/models/repo_test.go index b6c53fd197..5273b9d838 100644 --- a/models/repo_test.go +++ b/models/repo_test.go @@ -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) diff --git a/models/system/notice.go b/models/system/notice.go index 91bf4be0f6..f39188f8fb 100644 --- a/models/system/notice.go +++ b/models/system/notice.go @@ -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) } } diff --git a/models/system/notice_test.go b/models/system/notice_test.go index 9fc9e6cce1..802bcf41b1 100644 --- a/models/system/notice_test.go +++ b/models/system/notice_test.go @@ -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}) diff --git a/models/system/setting_test.go b/models/system/setting_test.go index 7e7e0c8fca..780a323fe1 100644 --- a/models/system/setting_test.go +++ b/models/system/setting_test.go @@ -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) diff --git a/models/unittest/consistency.go b/models/unittest/consistency.go index 364afb5c52..b51cadce0a 100644 --- a/models/unittest/consistency.go +++ b/models/unittest/consistency.go @@ -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")}) diff --git a/models/unittest/fixtures.go b/models/unittest/fixtures.go index fb2d2d0085..a9a01a3227 100644 --- a/models/unittest/fixtures.go +++ b/models/unittest/fixtures.go @@ -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 { diff --git a/models/unittest/unit_tests.go b/models/unittest/unit_tests.go index 4a4cec40ae..49d42d7fe6 100644 --- a/models/unittest/unit_tests.go +++ b/models/unittest/unit_tests.go @@ -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 { diff --git a/models/user/avatar_test.go b/models/user/avatar_test.go index 941068957c..9ebf00de49 100644 --- a/models/user/avatar_test.go +++ b/models/user/avatar_test.go @@ -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()) diff --git a/models/user/email_address_test.go b/models/user/email_address_test.go index c0666246b0..6ef18fb0f6 100644 --- a/models/user/email_address_test.go +++ b/models/user/email_address_test.go @@ -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))) diff --git a/models/user/follow_test.go b/models/user/follow_test.go index c327d935ae..1d5f144164 100644 --- a/models/user/follow_test.go +++ b/models/user/follow_test.go @@ -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)) } diff --git a/models/user/openid_test.go b/models/user/openid_test.go index 708af9e653..fa260e7a9e 100644 --- a/models/user/openid_test.go +++ b/models/user/openid_test.go @@ -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) diff --git a/models/user/redirect_test.go b/models/user/redirect_test.go index 484c5a663f..015eac0668 100644 --- a/models/user/redirect_test.go +++ b/models/user/redirect_test.go @@ -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)) } diff --git a/models/user/setting_test.go b/models/user/setting_test.go index 3c199013f3..7332e442b4 100644 --- a/models/user/setting_test.go +++ b/models/user/setting_test.go @@ -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) } diff --git a/models/user/user_system_test.go b/models/user/user_system_test.go index 97768b509b..5aa3fa463c 100644 --- a/models/user/user_system_test.go +++ b/models/user/user_system_test.go @@ -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) } diff --git a/models/user/user_test.go b/models/user/user_test.go index 7944fc4b73..4201ec4816 100644 --- a/models/user/user_test.go +++ b/models/user/user_test.go @@ -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) } diff --git a/models/webhook/webhook_system_test.go b/models/webhook/webhook_system_test.go index 96157ed9c9..8aac693995 100644 --- a/models/webhook/webhook_system_test.go +++ b/models/webhook/webhook_system_test.go @@ -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) diff --git a/models/webhook/webhook_test.go b/models/webhook/webhook_test.go index edad8fc996..71f50017c5 100644 --- a/models/webhook/webhook_test.go +++ b/models/webhook/webhook_test.go @@ -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) diff --git a/modules/activitypub/client_test.go b/modules/activitypub/client_test.go index d0c4845445..361270a800 100644 --- a/modules/activitypub/client_test.go +++ b/modules/activitypub/client_test.go @@ -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" diff --git a/modules/activitypub/user_settings_test.go b/modules/activitypub/user_settings_test.go index 55862357f1..105d4aedea 100644 --- a/modules/activitypub/user_settings_test.go +++ b/modules/activitypub/user_settings_test.go @@ -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) } diff --git a/modules/indexer/stats/indexer.go b/modules/indexer/stats/indexer.go index 7ec89e2afb..aaf120c6d0 100644 --- a/modules/indexer/stats/indexer.go +++ b/modules/indexer/stats/indexer.go @@ -30,7 +30,7 @@ func Init() error { return err } - go populateRepoIndexer(db.DefaultContext) + go populateRepoIndexer(graceful.GetManager().ShutdownContext()) return nil } diff --git a/modules/indexer/stats/indexer_test.go b/modules/indexer/stats/indexer_test.go index d32a8bf151..088f63234a 100644 --- a/modules/indexer/stats/indexer_test.go +++ b/modules/indexer/stats/indexer_test.go @@ -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) } diff --git a/modules/metrics/collector.go b/modules/metrics/collector.go index 4d2ec287a9..d02e5c1128 100755 --- a/modules/metrics/collector.go +++ b/modules/metrics/collector.go @@ -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, diff --git a/modules/repository/branch_test.go b/modules/repository/branch_test.go index ead28aa141..262a35fbf7 100644 --- a/modules/repository/branch_test.go +++ b/modules/repository/branch_test.go @@ -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) } diff --git a/modules/repository/commits_test.go b/modules/repository/commits_test.go index 5aad5fd710..04c0711828 100644 --- a/modules/repository/commits_test.go +++ b/modules/repository/commits_test.go @@ -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) { diff --git a/modules/repository/create_test.go b/modules/repository/create_test.go index b85a10adad..68b0f4dea1 100644 --- a/modules/repository/create_test.go +++ b/modules/repository/create_test.go @@ -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) diff --git a/modules/session/db.go b/modules/session/db.go index 9909f2dc1e..7b5be1bc70 100644 --- a/modules/session/db.go +++ b/modules/session/db.go @@ -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) } } diff --git a/modules/system/appstate_test.go b/modules/system/appstate_test.go index b5c057cf88..509210127d 100644 --- a/modules/system/appstate_test.go +++ b/modules/system/appstate_test.go @@ -6,7 +6,6 @@ package system import ( "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" @@ -37,25 +36,25 @@ func TestAppStateDB(t *testing.T) { as := &DBStore{} item1 := new(testItem1) - assert.NoError(t, as.Get(db.DefaultContext, item1)) + assert.NoError(t, as.Get(t.Context(), item1)) assert.Empty(t, item1.Val1) assert.Equal(t, 0, item1.Val2) item1 = new(testItem1) item1.Val1 = "a" item1.Val2 = 2 - assert.NoError(t, as.Set(db.DefaultContext, item1)) + assert.NoError(t, as.Set(t.Context(), item1)) item2 := new(testItem2) item2.K = "V" - assert.NoError(t, as.Set(db.DefaultContext, item2)) + assert.NoError(t, as.Set(t.Context(), item2)) item1 = new(testItem1) - assert.NoError(t, as.Get(db.DefaultContext, item1)) + assert.NoError(t, as.Get(t.Context(), item1)) assert.Equal(t, "a", item1.Val1) assert.Equal(t, 2, item1.Val2) item2 = new(testItem2) - assert.NoError(t, as.Get(db.DefaultContext, item2)) + assert.NoError(t, as.Get(t.Context(), item2)) assert.Equal(t, "V", item2.K) } diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index f412e8a06c..e185a2147c 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -72,13 +72,13 @@ import ( actions_model "code.gitea.io/gitea/models/actions" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/perm" access_model "code.gitea.io/gitea/models/perm/access" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" @@ -780,7 +780,7 @@ func buildAuthGroup() *auth.Group { group.Add(&auth.ReverseProxy{}) } - if setting.IsWindows && auth_model.IsSSPIEnabled(db.DefaultContext) { + if setting.IsWindows && auth_model.IsSSPIEnabled(graceful.GetManager().ShutdownContext()) { group.Add(&auth.SSPI{}) // it MUST be the last, see the comment of SSPI } diff --git a/routers/install/install.go b/routers/install/install.go index dc8f209f3b..4a9dabac6f 100644 --- a/routers/install/install.go +++ b/routers/install/install.go @@ -180,20 +180,20 @@ func checkDatabase(ctx *context.Context, form *forms.InstallForm) bool { return false } - err = db_install.CheckDatabaseConnection() + err = db_install.CheckDatabaseConnection(ctx) if err != nil { ctx.Data["Err_DbSetting"] = true ctx.RenderWithErr(ctx.Tr("install.invalid_db_setting", err), tplInstall, form) return false } - hasPostInstallationUser, err := db_install.HasPostInstallationUsers() + hasPostInstallationUser, err := db_install.HasPostInstallationUsers(ctx) if err != nil { ctx.Data["Err_DbSetting"] = true ctx.RenderWithErr(ctx.Tr("install.invalid_db_table", "user", err), tplInstall, form) return false } - dbMigrationVersion, err := db_install.GetMigrationVersion() + dbMigrationVersion, err := db_install.GetMigrationVersion(ctx) if err != nil { ctx.Data["Err_DbSetting"] = true ctx.RenderWithErr(ctx.Tr("install.invalid_db_table", "version", err), tplInstall, form) diff --git a/routers/private/hook_post_receive_test.go b/routers/private/hook_post_receive_test.go index ca721b16d1..23b8085e94 100644 --- a/routers/private/hook_post_receive_test.go +++ b/routers/private/hook_post_receive_test.go @@ -6,7 +6,6 @@ package private import ( "testing" - "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" pull_model "code.gitea.io/gitea/models/pull" repo_model "code.gitea.io/gitea/models/repo" @@ -21,13 +20,13 @@ import ( func TestHandlePullRequestMerging(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.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) + assert.NoError(t, pr.LoadBaseRepo(t.Context())) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - err = pull_model.ScheduleAutoMerge(db.DefaultContext, user1, pr.ID, repo_model.MergeStyleSquash, "squash merge a pr", false) + err = pull_model.ScheduleAutoMerge(t.Context(), user1, pr.ID, repo_model.MergeStyleSquash, "squash merge a pr", false) assert.NoError(t, err) autoMerge := unittest.AssertExistsAndLoadBean(t, &pull_model.AutoMerge{PullID: pr.ID}) @@ -40,7 +39,7 @@ func TestHandlePullRequestMerging(t *testing.T) { {NewCommitID: "01234567"}, }) assert.Empty(t, resp.Body.String()) - pr, err = issues_model.GetPullRequestByID(db.DefaultContext, pr.ID) + pr, err = issues_model.GetPullRequestByID(t.Context(), pr.ID) assert.NoError(t, err) assert.True(t, pr.HasMerged) assert.Equal(t, "01234567", pr.MergedCommitID) diff --git a/routers/web/auth/auth_test.go b/routers/web/auth/auth_test.go index a0fd5c0e50..5ccffe0d50 100644 --- a/routers/web/auth/auth_test.go +++ b/routers/web/auth/auth_test.go @@ -9,7 +9,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/session" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/test" @@ -24,7 +23,7 @@ import ( func addOAuth2Source(t *testing.T, authName string, cfg oauth2.Source) { cfg.Provider = util.IfZero(cfg.Provider, "gitea") - err := auth_model.CreateSource(db.DefaultContext, &auth_model.Source{ + err := auth_model.CreateSource(t.Context(), &auth_model.Source{ Type: auth_model.OAuth2, Name: authName, IsActive: true, diff --git a/routers/web/auth/oauth_test.go b/routers/web/auth/oauth_test.go index 4571a70b72..36b0cf6eac 100644 --- a/routers/web/auth/oauth_test.go +++ b/routers/web/auth/oauth_test.go @@ -7,7 +7,6 @@ import ( "testing" "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/services/oauth2_provider" @@ -21,7 +20,7 @@ func createAndParseToken(t *testing.T, grant *auth.OAuth2Grant) *oauth2_provider assert.NoError(t, err) assert.NotNil(t, signingKey) - response, terr := oauth2_provider.NewAccessTokenResponse(db.DefaultContext, grant, signingKey, signingKey) + response, terr := oauth2_provider.NewAccessTokenResponse(t.Context(), grant, signingKey, signingKey) assert.Nil(t, terr) assert.NotNil(t, response) @@ -43,7 +42,7 @@ func createAndParseToken(t *testing.T, grant *auth.OAuth2Grant) *oauth2_provider func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - grants, err := auth.GetOAuth2GrantsByUserID(db.DefaultContext, 3) + grants, err := auth.GetOAuth2GrantsByUserID(t.Context(), 3) assert.NoError(t, err) assert.Len(t, grants, 1) @@ -59,7 +58,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { assert.False(t, oidcToken.EmailVerified) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) - grants, err = auth.GetOAuth2GrantsByUserID(db.DefaultContext, user.ID) + grants, err = auth.GetOAuth2GrantsByUserID(t.Context(), user.ID) assert.NoError(t, err) assert.Len(t, grants, 1) @@ -68,7 +67,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { assert.Equal(t, user.DisplayName(), oidcToken.Name) assert.Equal(t, user.Name, oidcToken.PreferredUsername) assert.Equal(t, user.HTMLURL(t.Context()), oidcToken.Profile) - assert.Equal(t, user.AvatarLink(db.DefaultContext), oidcToken.Picture) + assert.Equal(t, user.AvatarLink(t.Context()), oidcToken.Picture) assert.Equal(t, user.Website, oidcToken.Website) assert.Equal(t, user.UpdatedUnix, oidcToken.UpdatedAt) assert.Equal(t, user.Email, oidcToken.Email) diff --git a/routers/web/org/worktime.go b/routers/web/org/worktime.go index c7b44baf7b..bf8db1a9a1 100644 --- a/routers/web/org/worktime.go +++ b/routers/web/org/worktime.go @@ -58,13 +58,13 @@ func Worktime(ctx *context.Context) { var err error switch worktimeBy { case "milestones": - worktimeSumResult, err = organization.GetWorktimeByMilestones(ctx.Org.Organization, unixFrom, unixTo) + worktimeSumResult, err = organization.GetWorktimeByMilestones(ctx, ctx.Org.Organization, unixFrom, unixTo) ctx.Data["WorktimeByMilestones"] = true case "members": - worktimeSumResult, err = organization.GetWorktimeByMembers(ctx.Org.Organization, unixFrom, unixTo) + worktimeSumResult, err = organization.GetWorktimeByMembers(ctx, ctx.Org.Organization, unixFrom, unixTo) ctx.Data["WorktimeByMembers"] = true default: /* by repos */ - worktimeSumResult, err = organization.GetWorktimeByRepos(ctx.Org.Organization, unixFrom, unixTo) + worktimeSumResult, err = organization.GetWorktimeByRepos(ctx, ctx.Org.Organization, unixFrom, unixTo) ctx.Data["WorktimeByRepos"] = true } if err != nil { diff --git a/routers/web/repo/actions/actions_test.go b/routers/web/repo/actions/actions_test.go index 6a976ed65c..9e83ff0fbb 100644 --- a/routers/web/repo/actions/actions_test.go +++ b/routers/web/repo/actions/actions_test.go @@ -162,7 +162,7 @@ func TestReadWorkflow_WorkflowDispatchConfig(t *testing.T) { func Test_loadIsRefDeleted(t *testing.T) { unittest.PrepareTestEnv(t) - runs, total, err := db.FindAndCount[actions_model.ActionRun](db.DefaultContext, + runs, total, err := db.FindAndCount[actions_model.ActionRun](t.Context(), actions_model.FindRunOptions{RepoID: 4, Ref: "refs/heads/test"}) assert.NoError(t, err) assert.Len(t, runs, 1) @@ -171,7 +171,7 @@ func Test_loadIsRefDeleted(t *testing.T) { assert.False(t, run.IsRefDeleted) } - assert.NoError(t, loadIsRefDeleted(db.DefaultContext, 4, runs)) + assert.NoError(t, loadIsRefDeleted(t.Context(), 4, runs)) for _, run := range runs { assert.True(t, run.IsRefDeleted) } diff --git a/routers/web/repo/pull_review_test.go b/routers/web/repo/pull_review_test.go index 3d0997ab4d..42223c1d9c 100644 --- a/routers/web/repo/pull_review_test.go +++ b/routers/web/repo/pull_review_test.go @@ -23,10 +23,10 @@ import ( func TestRenderConversation(t *testing.T) { unittest.PrepareTestEnv(t) - pr, _ := issues_model.GetPullRequestByID(db.DefaultContext, 2) - _ = pr.LoadIssue(db.DefaultContext) - _ = pr.Issue.LoadPoster(db.DefaultContext) - _ = pr.Issue.LoadRepo(db.DefaultContext) + pr, _ := issues_model.GetPullRequestByID(t.Context(), 2) + _ = pr.LoadIssue(t.Context()) + _ = pr.Issue.LoadPoster(t.Context()) + _ = pr.Issue.LoadRepo(t.Context()) run := func(name string, cb func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder)) { t.Run(name, func(t *testing.T) { @@ -73,7 +73,7 @@ func TestRenderConversation(t *testing.T) { assert.Contains(t, resp.Body.String(), `
", msgID) } diff --git a/services/markup/renderhelper_mention_test.go b/services/markup/renderhelper_mention_test.go index d54ab13a48..11aa7b2132 100644 --- a/services/markup/renderhelper_mention_test.go +++ b/services/markup/renderhelper_mention_test.go @@ -8,7 +8,6 @@ import ( "net/http/httptest" "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/user" gitea_context "code.gitea.io/gitea/services/context" @@ -45,7 +44,7 @@ func TestRenderHelperMention(t *testing.T) { assert.True(t, FormalRenderHelperFuncs().IsUsernameMentionable(giteaCtx, userPublic)) assert.False(t, FormalRenderHelperFuncs().IsUsernameMentionable(giteaCtx, userPrivate)) - giteaCtx.Doer, err = user.GetUserByName(db.DefaultContext, userPrivate) + giteaCtx.Doer, err = user.GetUserByName(t.Context(), userPrivate) assert.NoError(t, err) assert.True(t, FormalRenderHelperFuncs().IsUsernameMentionable(giteaCtx, userPublic)) assert.True(t, FormalRenderHelperFuncs().IsUsernameMentionable(giteaCtx, userPrivate)) diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 05fbe2d461..5e6fe6cc05 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -45,7 +45,7 @@ func TestGiteaUploadRepo(t *testing.T) { uploader = NewGiteaLocalUploader(graceful.GetManager().HammerContext(), user, user.Name, repoName) ) - err := migrateRepository(db.DefaultContext, user, downloader, uploader, base.MigrateOptions{ + err := migrateRepository(t.Context(), user, downloader, uploader, base.MigrateOptions{ CloneAddr: "https://github.com/go-xorm/builder", RepoName: repoName, AuthUsername: "", @@ -66,14 +66,14 @@ func TestGiteaUploadRepo(t *testing.T) { assert.True(t, repo.HasWiki()) assert.Equal(t, repo_model.RepositoryReady, repo.Status) - 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: optional.Some(false), }) assert.NoError(t, err) assert.Len(t, milestones, 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{ RepoID: repo.ID, IsClosed: optional.Some(true), }) @@ -84,7 +84,7 @@ func TestGiteaUploadRepo(t *testing.T) { assert.NoError(t, err) assert.Len(t, labels, 12) - releases, err := db.Find[repo_model.Release](db.DefaultContext, repo_model.FindReleasesOptions{ + releases, err := db.Find[repo_model.Release](t.Context(), repo_model.FindReleasesOptions{ ListOptions: db.ListOptions{ PageSize: 10, Page: 0, @@ -95,7 +95,7 @@ func TestGiteaUploadRepo(t *testing.T) { assert.NoError(t, err) assert.Len(t, releases, 8) - releases, err = db.Find[repo_model.Release](db.DefaultContext, repo_model.FindReleasesOptions{ + releases, err = db.Find[repo_model.Release](t.Context(), repo_model.FindReleasesOptions{ ListOptions: db.ListOptions{ PageSize: 10, Page: 0, @@ -106,23 +106,23 @@ func TestGiteaUploadRepo(t *testing.T) { assert.NoError(t, err) assert.Len(t, releases, 1) - issues, err := issues_model.Issues(db.DefaultContext, &issues_model.IssuesOptions{ + issues, err := issues_model.Issues(t.Context(), &issues_model.IssuesOptions{ RepoIDs: []int64{repo.ID}, IsPull: optional.Some(false), SortType: "oldest", }) assert.NoError(t, err) assert.Len(t, issues, 15) - assert.NoError(t, issues[0].LoadDiscussComments(db.DefaultContext)) + assert.NoError(t, issues[0].LoadDiscussComments(t.Context())) assert.Empty(t, issues[0].Comments) - pulls, _, err := issues_model.PullRequests(db.DefaultContext, repo.ID, &issues_model.PullRequestsOptions{ + pulls, _, err := issues_model.PullRequests(t.Context(), repo.ID, &issues_model.PullRequestsOptions{ SortType: "oldest", }) assert.NoError(t, err) assert.Len(t, pulls, 30) - assert.NoError(t, pulls[0].LoadIssue(db.DefaultContext)) - assert.NoError(t, pulls[0].Issue.LoadDiscussComments(db.DefaultContext)) + assert.NoError(t, pulls[0].LoadIssue(t.Context())) + assert.NoError(t, pulls[0].Issue.LoadDiscussComments(t.Context())) assert.Len(t, pulls[0].Issue.Comments, 2) } @@ -214,7 +214,7 @@ func TestGiteaUploadRemapExternalUser(t *testing.T) { LoginSourceID: 0, Provider: structs.GiteaService.Name(), } - err = user_model.LinkExternalToUser(db.DefaultContext, linkedUser, externalLoginUser) + err = user_model.LinkExternalToUser(t.Context(), linkedUser, externalLoginUser) assert.NoError(t, err) // diff --git a/services/org/org_test.go b/services/org/org_test.go index 791404c5c8..5fdc1a6fd5 100644 --- a/services/org/org_test.go +++ b/services/org/org_test.go @@ -6,7 +6,6 @@ package org import ( "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -22,17 +21,17 @@ func TestMain(m *testing.M) { func TestDeleteOrganization(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 6}) - assert.NoError(t, DeleteOrganization(db.DefaultContext, org, false)) + assert.NoError(t, DeleteOrganization(t.Context(), org, false)) unittest.AssertNotExistsBean(t, &organization.Organization{ID: 6}) unittest.AssertNotExistsBean(t, &organization.OrgUser{OrgID: 6}) unittest.AssertNotExistsBean(t, &organization.Team{OrgID: 6}) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) - err := DeleteOrganization(db.DefaultContext, org, false) + err := DeleteOrganization(t.Context(), org, false) assert.Error(t, err) assert.True(t, repo_model.IsErrUserOwnRepos(err)) user := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 5}) - assert.Error(t, DeleteOrganization(db.DefaultContext, user, false)) + assert.Error(t, DeleteOrganization(t.Context(), user, false)) unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{}) } diff --git a/services/org/team.go b/services/org/team.go index 773bd11f49..633056cf95 100644 --- a/services/org/team.go +++ b/services/org/team.go @@ -15,6 +15,7 @@ import ( access_model "code.gitea.io/gitea/models/perm/access" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" + "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" @@ -259,10 +260,9 @@ func AddTeamMember(ctx context.Context, team *organization.Team, user *user_mode log.Error("GetTeamRepositories failed: %v", err) } - // FIXME: in the goroutine, it can't access the "ctx", it could only use db.DefaultContext at the moment go func(repos []*repo_model.Repository) { for _, repo := range repos { - if err = repo_model.WatchRepo(db.DefaultContext, user, repo, true); err != nil { + if err = repo_model.WatchRepo(graceful.GetManager().ShutdownContext(), user, repo, true); err != nil { log.Error("watch repo failed: %v", err) } } diff --git a/services/org/team_test.go b/services/org/team_test.go index c1a69d8ee7..a5e01e7a54 100644 --- a/services/org/team_test.go +++ b/services/org/team_test.go @@ -8,7 +8,6 @@ import ( "strings" "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/perm" access_model "code.gitea.io/gitea/models/perm/access" @@ -25,7 +24,7 @@ func TestTeam_AddMember(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) test := func(team *organization.Team, user *user_model.User) { - assert.NoError(t, AddTeamMember(db.DefaultContext, team, user)) + assert.NoError(t, AddTeamMember(t.Context(), team, user)) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: user.ID, TeamID: team.ID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: team.ID}, &user_model.User{ID: team.OrgID}) } @@ -44,7 +43,7 @@ func TestTeam_RemoveMember(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(team *organization.Team, user *user_model.User) { - assert.NoError(t, RemoveTeamMember(db.DefaultContext, team, user)) + assert.NoError(t, RemoveTeamMember(t.Context(), team, user)) unittest.AssertNotExistsBean(t, &organization.TeamUser{UID: user.ID, TeamID: team.ID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: team.ID}) } @@ -59,7 +58,7 @@ func TestTeam_RemoveMember(t *testing.T) { testSuccess(team2, user2) testSuccess(team3, user2) - err := RemoveTeamMember(db.DefaultContext, team1, user2) + err := RemoveTeamMember(t.Context(), team1, user2) assert.True(t, organization.IsErrLastOrgOwner(err)) } @@ -68,7 +67,7 @@ func TestNewTeam(t *testing.T) { const teamName = "newTeamName" team := &organization.Team{Name: teamName, OrgID: 3} - assert.NoError(t, NewTeam(db.DefaultContext, team)) + assert.NoError(t, NewTeam(t.Context(), team)) unittest.AssertExistsAndLoadBean(t, &organization.Team{Name: teamName}) unittest.CheckConsistencyFor(t, &organization.Team{}, &user_model.User{ID: team.OrgID}) } @@ -82,7 +81,7 @@ func TestUpdateTeam(t *testing.T) { team.Name = "newName" team.Description = strings.Repeat("A long description!", 100) team.AccessMode = perm.AccessModeAdmin - assert.NoError(t, UpdateTeam(db.DefaultContext, team, true, false)) + assert.NoError(t, UpdateTeam(t.Context(), team, true, false)) team = unittest.AssertExistsAndLoadBean(t, &organization.Team{Name: "newName"}) assert.True(t, strings.HasPrefix(team.Description, "A long description!")) @@ -101,7 +100,7 @@ func TestUpdateTeam2(t *testing.T) { team.LowerName = "owners" team.Name = "Owners" team.Description = strings.Repeat("A long description!", 100) - err := UpdateTeam(db.DefaultContext, team, true, false) + err := UpdateTeam(t.Context(), team, true, false) assert.True(t, organization.IsErrTeamAlreadyExist(err)) unittest.CheckConsistencyFor(t, &organization.Team{ID: team.ID}) @@ -111,7 +110,7 @@ func TestDeleteTeam(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) - assert.NoError(t, DeleteTeam(db.DefaultContext, team)) + assert.NoError(t, DeleteTeam(t.Context(), team)) unittest.AssertNotExistsBean(t, &organization.Team{ID: team.ID}) unittest.AssertNotExistsBean(t, &organization.TeamRepo{TeamID: team.ID}) unittest.AssertNotExistsBean(t, &organization.TeamUser{TeamID: team.ID}) @@ -119,7 +118,7 @@ func TestDeleteTeam(t *testing.T) { // check that team members don't have "leftover" access to repos user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) - accessMode, err := access_model.AccessLevel(db.DefaultContext, user, repo) + accessMode, err := access_model.AccessLevel(t.Context(), user, repo) assert.NoError(t, err) assert.Less(t, accessMode, perm.AccessModeWrite) } @@ -128,7 +127,7 @@ func TestAddTeamMember(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) test := func(team *organization.Team, user *user_model.User) { - assert.NoError(t, AddTeamMember(db.DefaultContext, team, user)) + assert.NoError(t, AddTeamMember(t.Context(), team, user)) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: user.ID, TeamID: team.ID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: team.ID}, &user_model.User{ID: team.OrgID}) } @@ -147,7 +146,7 @@ func TestRemoveTeamMember(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(team *organization.Team, user *user_model.User) { - assert.NoError(t, RemoveTeamMember(db.DefaultContext, team, user)) + assert.NoError(t, RemoveTeamMember(t.Context(), team, user)) unittest.AssertNotExistsBean(t, &organization.TeamUser{UID: user.ID, TeamID: team.ID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: team.ID}) } @@ -162,7 +161,7 @@ func TestRemoveTeamMember(t *testing.T) { testSuccess(team2, user2) testSuccess(team3, user2) - err := RemoveTeamMember(db.DefaultContext, team1, user2) + err := RemoveTeamMember(t.Context(), team1, user2) assert.True(t, organization.IsErrLastOrgOwner(err)) } @@ -171,7 +170,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { testTeamRepositories := func(teamID int64, repoIDs []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, "%s: GetTeamRepositories", team.Name) @@ -179,13 +178,13 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { assert.Len(t, repos, len(repoIDs), "%s: repo count", team.Name) for i, rid := range repoIDs { if rid > 0 { - assert.True(t, repo_service.HasRepository(db.DefaultContext, team, rid), "%s: HasRepository(%d) %d", rid, i) + assert.True(t, repo_service.HasRepository(t.Context(), team, rid), "%s: HasRepository(%d) %d", rid, i) } } } // Get an admin user. - user, err := user_model.GetUserByID(db.DefaultContext, 1) + user, err := user_model.GetUserByID(t.Context(), 1) assert.NoError(t, err, "GetUserByID") // Create org. @@ -195,17 +194,17 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { Type: user_model.UserTypeOrganization, Visibility: structs.VisibleTypePublic, } - assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, user), "CreateOrganization") + assert.NoError(t, organization.CreateOrganization(t.Context(), org, user), "CreateOrganization") // Check Owner team. - ownerTeam, err := org.GetOwnerTeam(db.DefaultContext) + ownerTeam, err := org.GetOwnerTeam(t.Context()) assert.NoError(t, err, "GetOwnerTeam") assert.True(t, ownerTeam.IncludesAllRepositories, "Owner team includes all repositories") // Create repos. repoIDs := make([]int64, 0) for i := range 3 { - r, err := repo_service.CreateRepositoryDirectly(db.DefaultContext, user, org.AsUser(), + r, err := repo_service.CreateRepositoryDirectly(t.Context(), user, org.AsUser(), repo_service.CreateRepoOptions{Name: fmt.Sprintf("repo-%d", i)}, true) assert.NoError(t, err, "CreateRepository %d", i) if r != nil { @@ -213,7 +212,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { } } // Get fresh copy of Owner team after creating repos. - ownerTeam, err = org.GetOwnerTeam(db.DefaultContext) + ownerTeam, err = org.GetOwnerTeam(t.Context()) assert.NoError(t, err, "GetOwnerTeam") // Create teams and check repositories. @@ -253,7 +252,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { } for i, team := range teams { if i > 0 { // first team is Owner. - assert.NoError(t, NewTeam(db.DefaultContext, team), "%s: NewTeam", team.Name) + assert.NoError(t, NewTeam(t.Context(), team), "%s: NewTeam", team.Name) } testTeamRepositories(team.ID, teamRepos[i]) } @@ -263,12 +262,12 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { teams[4].IncludesAllRepositories = true teamRepos[4] = repoIDs for i, team := range teams { - assert.NoError(t, UpdateTeam(db.DefaultContext, team, false, true), "%s: UpdateTeam", team.Name) + assert.NoError(t, UpdateTeam(t.Context(), team, false, true), "%s: UpdateTeam", team.Name) testTeamRepositories(team.ID, teamRepos[i]) } // Create repo and check teams repositories. - r, err := repo_service.CreateRepositoryDirectly(db.DefaultContext, user, org.AsUser(), repo_service.CreateRepoOptions{Name: "repo-last"}, true) + r, err := repo_service.CreateRepositoryDirectly(t.Context(), user, org.AsUser(), repo_service.CreateRepoOptions{Name: "repo-last"}, true) assert.NoError(t, err, "CreateRepository last") if r != nil { repoIDs = append(repoIDs, r.ID) @@ -281,7 +280,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { } // Remove repo and check teams repositories. - assert.NoError(t, repo_service.DeleteRepositoryDirectly(db.DefaultContext, repoIDs[0]), "DeleteRepository") + assert.NoError(t, repo_service.DeleteRepositoryDirectly(t.Context(), repoIDs[0]), "DeleteRepository") teamRepos[0] = repoIDs[1:] teamRepos[1] = repoIDs[1:] teamRepos[3] = repoIDs[1:3] @@ -293,8 +292,8 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { // Wipe created items. for i, rid := range repoIDs { if i > 0 { // first repo already deleted. - assert.NoError(t, repo_service.DeleteRepositoryDirectly(db.DefaultContext, rid), "DeleteRepository %d", i) + assert.NoError(t, repo_service.DeleteRepositoryDirectly(t.Context(), rid), "DeleteRepository %d", i) } } - assert.NoError(t, DeleteOrganization(db.DefaultContext, org, false), "DeleteOrganization") + assert.NoError(t, DeleteOrganization(t.Context(), org, false), "DeleteOrganization") } diff --git a/services/org/user_test.go b/services/org/user_test.go index c61d600d90..3df9d53356 100644 --- a/services/org/user_test.go +++ b/services/org/user_test.go @@ -6,7 +6,6 @@ package org 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" @@ -24,7 +23,7 @@ func TestUser_RemoveMember(t *testing.T) { // remove a user that is a member unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{UID: user4.ID, OrgID: org.ID}) prevNumMembers := org.NumMembers - assert.NoError(t, RemoveOrgUser(db.DefaultContext, org, user4)) + assert.NoError(t, RemoveOrgUser(t.Context(), org, user4)) unittest.AssertNotExistsBean(t, &organization.OrgUser{UID: user4.ID, OrgID: org.ID}) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: org.ID}) @@ -33,7 +32,7 @@ func TestUser_RemoveMember(t *testing.T) { // remove a user that is not a member unittest.AssertNotExistsBean(t, &organization.OrgUser{UID: user5.ID, OrgID: org.ID}) prevNumMembers = org.NumMembers - assert.NoError(t, RemoveOrgUser(db.DefaultContext, org, user5)) + assert.NoError(t, RemoveOrgUser(t.Context(), org, user5)) unittest.AssertNotExistsBean(t, &organization.OrgUser{UID: user5.ID, OrgID: org.ID}) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: org.ID}) @@ -50,7 +49,7 @@ func TestRemoveOrgUser(t *testing.T) { if unittest.GetBean(t, &organization.OrgUser{OrgID: org.ID, UID: user.ID}) != nil { expectedNumMembers-- } - assert.NoError(t, RemoveOrgUser(db.DefaultContext, org, user)) + assert.NoError(t, RemoveOrgUser(t.Context(), org, user)) unittest.AssertNotExistsBean(t, &organization.OrgUser{OrgID: org.ID, UID: user.ID}) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: org.ID}) assert.Equal(t, expectedNumMembers, org.NumMembers) @@ -66,7 +65,7 @@ func TestRemoveOrgUser(t *testing.T) { org3 = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) testSuccess(org3, user4) - err := RemoveOrgUser(db.DefaultContext, org7, user5) + err := RemoveOrgUser(t.Context(), org7, user5) assert.Error(t, err) assert.True(t, organization.IsErrLastOrgOwner(err)) unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{OrgID: org7.ID, UID: user5.ID}) diff --git a/services/packages/arch/vercmp.go b/services/packages/arch/vercmp.go index d44aa530f0..f4a83d5eb1 100644 --- a/services/packages/arch/vercmp.go +++ b/services/packages/arch/vercmp.go @@ -4,16 +4,13 @@ package arch import ( + "strconv" "strings" "unicode" ) // https://gitlab.archlinux.org/pacman/pacman/-/blob/d55b47e5512808b67bc944feb20c2bcc6c1a4c45/lib/libalpm/version.c -import ( - "strconv" -) - func parseEVR(evr string) (epoch, version, release string) { if before, after, f := strings.Cut(evr, ":"); f { epoch = before diff --git a/services/packages/container/common.go b/services/packages/container/common.go index 02cbff2286..d3e2996a52 100644 --- a/services/packages/container/common.go +++ b/services/packages/container/common.go @@ -15,7 +15,7 @@ import ( "code.gitea.io/gitea/modules/packages" container_module "code.gitea.io/gitea/modules/packages/container" - "github.com/opencontainers/image-spec/specs-go/v1" + v1 "github.com/opencontainers/image-spec/specs-go/v1" ) // UpdateRepositoryNames updates the repository name property for all packages of the specific owner diff --git a/services/projects/issue_test.go b/services/projects/issue_test.go index e76d31e757..7255cdfe52 100644 --- a/services/projects/issue_test.go +++ b/services/projects/issue_test.go @@ -31,10 +31,10 @@ func Test_Projects(t *testing.T) { IssueID: 1, ProjectColumnID: 4, } - err := db.Insert(db.DefaultContext, &pi1) + err := db.Insert(t.Context(), &pi1) assert.NoError(t, err) defer func() { - _, err = db.DeleteByID[project_model.ProjectIssue](db.DefaultContext, pi1.ID) + _, err = db.DeleteByID[project_model.ProjectIssue](t.Context(), pi1.ID) assert.NoError(t, err) }() @@ -43,14 +43,14 @@ func Test_Projects(t *testing.T) { IssueID: 4, ProjectColumnID: 4, } - err = db.Insert(db.DefaultContext, &pi2) + err = db.Insert(t.Context(), &pi2) assert.NoError(t, err) defer func() { - _, err = db.DeleteByID[project_model.ProjectIssue](db.DefaultContext, pi2.ID) + _, err = db.DeleteByID[project_model.ProjectIssue](t.Context(), pi2.ID) assert.NoError(t, err) }() - projects, err := db.Find[project_model.Project](db.DefaultContext, project_model.SearchOptions{ + projects, err := db.Find[project_model.Project](t.Context(), project_model.SearchOptions{ OwnerID: user2.ID, }) assert.NoError(t, err) @@ -58,7 +58,7 @@ func Test_Projects(t *testing.T) { assert.EqualValues(t, 4, projects[0].ID) t.Run("Authenticated user", func(t *testing.T) { - columnIssues, err := LoadIssuesFromProject(db.DefaultContext, projects[0], &issues_model.IssuesOptions{ + columnIssues, err := LoadIssuesFromProject(t.Context(), projects[0], &issues_model.IssuesOptions{ Owner: user2, Doer: user2, }) @@ -68,7 +68,7 @@ func Test_Projects(t *testing.T) { }) t.Run("Anonymous user", func(t *testing.T) { - columnIssues, err := LoadIssuesFromProject(db.DefaultContext, projects[0], &issues_model.IssuesOptions{ + columnIssues, err := LoadIssuesFromProject(t.Context(), projects[0], &issues_model.IssuesOptions{ AllPublic: true, }) assert.NoError(t, err) @@ -77,7 +77,7 @@ func Test_Projects(t *testing.T) { }) t.Run("Authenticated user with no permission to the private repo", func(t *testing.T) { - columnIssues, err := LoadIssuesFromProject(db.DefaultContext, projects[0], &issues_model.IssuesOptions{ + columnIssues, err := LoadIssuesFromProject(t.Context(), projects[0], &issues_model.IssuesOptions{ Owner: user2, Doer: user4, }) @@ -94,10 +94,10 @@ func Test_Projects(t *testing.T) { Type: project_model.TypeOrganization, TemplateType: project_model.TemplateTypeBasicKanban, } - err := project_model.NewProject(db.DefaultContext, &project1) + err := project_model.NewProject(t.Context(), &project1) assert.NoError(t, err) defer func() { - err := project_model.DeleteProjectByID(db.DefaultContext, project1.ID) + err := project_model.DeleteProjectByID(t.Context(), project1.ID) assert.NoError(t, err) }() @@ -105,27 +105,27 @@ func Test_Projects(t *testing.T) { Title: "column 1", ProjectID: project1.ID, } - err = project_model.NewColumn(db.DefaultContext, &column1) + err = project_model.NewColumn(t.Context(), &column1) assert.NoError(t, err) column2 := project_model.Column{ Title: "column 2", ProjectID: project1.ID, } - err = project_model.NewColumn(db.DefaultContext, &column2) + err = project_model.NewColumn(t.Context(), &column2) assert.NoError(t, err) // issue 6 belongs to private repo 3 under org 3 issue6 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 6}) - err = issues_model.IssueAssignOrRemoveProject(db.DefaultContext, issue6, user2, project1.ID, column1.ID) + err = issues_model.IssueAssignOrRemoveProject(t.Context(), issue6, user2, project1.ID, column1.ID) assert.NoError(t, err) // issue 16 belongs to public repo 16 under org 3 issue16 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 16}) - err = issues_model.IssueAssignOrRemoveProject(db.DefaultContext, issue16, user2, project1.ID, column1.ID) + err = issues_model.IssueAssignOrRemoveProject(t.Context(), issue16, user2, project1.ID, column1.ID) assert.NoError(t, err) - projects, err := db.Find[project_model.Project](db.DefaultContext, project_model.SearchOptions{ + projects, err := db.Find[project_model.Project](t.Context(), project_model.SearchOptions{ OwnerID: org3.ID, }) assert.NoError(t, err) @@ -133,7 +133,7 @@ func Test_Projects(t *testing.T) { assert.Equal(t, project1.ID, projects[0].ID) t.Run("Authenticated user", func(t *testing.T) { - columnIssues, err := LoadIssuesFromProject(db.DefaultContext, projects[0], &issues_model.IssuesOptions{ + columnIssues, err := LoadIssuesFromProject(t.Context(), projects[0], &issues_model.IssuesOptions{ Owner: org3.AsUser(), Doer: userAdmin, }) @@ -143,7 +143,7 @@ func Test_Projects(t *testing.T) { }) t.Run("Anonymous user", func(t *testing.T) { - columnIssues, err := LoadIssuesFromProject(db.DefaultContext, projects[0], &issues_model.IssuesOptions{ + columnIssues, err := LoadIssuesFromProject(t.Context(), projects[0], &issues_model.IssuesOptions{ AllPublic: true, }) assert.NoError(t, err) @@ -152,7 +152,7 @@ func Test_Projects(t *testing.T) { }) t.Run("Authenticated user with no permission to the private repo", func(t *testing.T) { - columnIssues, err := LoadIssuesFromProject(db.DefaultContext, projects[0], &issues_model.IssuesOptions{ + columnIssues, err := LoadIssuesFromProject(t.Context(), projects[0], &issues_model.IssuesOptions{ Owner: org3.AsUser(), Doer: user2, }) @@ -165,7 +165,7 @@ func Test_Projects(t *testing.T) { t.Run("Repository projects", func(t *testing.T) { repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - projects, err := db.Find[project_model.Project](db.DefaultContext, project_model.SearchOptions{ + projects, err := db.Find[project_model.Project](t.Context(), project_model.SearchOptions{ RepoID: repo1.ID, }) assert.NoError(t, err) @@ -173,7 +173,7 @@ func Test_Projects(t *testing.T) { assert.EqualValues(t, 1, projects[0].ID) t.Run("Authenticated user", func(t *testing.T) { - columnIssues, err := LoadIssuesFromProject(db.DefaultContext, projects[0], &issues_model.IssuesOptions{ + columnIssues, err := LoadIssuesFromProject(t.Context(), projects[0], &issues_model.IssuesOptions{ RepoIDs: []int64{repo1.ID}, Doer: userAdmin, }) @@ -185,7 +185,7 @@ func Test_Projects(t *testing.T) { }) t.Run("Anonymous user", func(t *testing.T) { - columnIssues, err := LoadIssuesFromProject(db.DefaultContext, projects[0], &issues_model.IssuesOptions{ + columnIssues, err := LoadIssuesFromProject(t.Context(), projects[0], &issues_model.IssuesOptions{ AllPublic: true, }) assert.NoError(t, err) @@ -196,7 +196,7 @@ func Test_Projects(t *testing.T) { }) t.Run("Authenticated user with no permission to the private repo", func(t *testing.T) { - columnIssues, err := LoadIssuesFromProject(db.DefaultContext, projects[0], &issues_model.IssuesOptions{ + columnIssues, err := LoadIssuesFromProject(t.Context(), projects[0], &issues_model.IssuesOptions{ RepoIDs: []int64{repo1.ID}, Doer: user2, }) diff --git a/services/pull/check_test.go b/services/pull/check_test.go index eb66615dcf..0f39237932 100644 --- a/services/pull/check_test.go +++ b/services/pull/check_test.go @@ -42,7 +42,7 @@ func TestPullRequest_AddToTaskQueue(t *testing.T) { assert.NoError(t, err) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) - StartPullRequestCheckImmediately(db.DefaultContext, pr) + StartPullRequestCheckImmediately(t.Context(), pr) assert.Eventually(t, func() bool { pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) diff --git a/services/pull/lfs.go b/services/pull/lfs.go index ed03583d4f..eb2a08ed8d 100644 --- a/services/pull/lfs.go +++ b/services/pull/lfs.go @@ -11,7 +11,6 @@ import ( "strconv" "sync" - "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/modules/git/pipeline" @@ -40,7 +39,7 @@ func LFSPush(ctx context.Context, tmpBasePath, mergeHeadSHA, mergeBaseSHA string // 6. Take the output of cat-file --batch and check if each file in turn // to see if they're pointers to files in the LFS store associated with // the head repo and add them to the base repo if so - go createLFSMetaObjectsFromCatFileBatch(db.DefaultContext, catFileBatchReader, &wg, pr) + go createLFSMetaObjectsFromCatFileBatch(ctx, catFileBatchReader, &wg, pr) // 5. Take the shas of the blobs and batch read them go pipeline.CatFileBatch(ctx, shasToBatchReader, catFileBatchWriter, &wg, tmpBasePath) diff --git a/services/pull/pull_test.go b/services/pull/pull_test.go index c4376b9e3f..1c03ab45ae 100644 --- a/services/pull/pull_test.go +++ b/services/pull/pull_test.go @@ -7,7 +7,6 @@ package pull 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/unit" @@ -40,18 +39,18 @@ func TestPullRequest_GetDefaultMergeMessage_InternalTracker(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) + assert.NoError(t, pr.LoadBaseRepo(t.Context())) gitRepo, err := gitrepo.OpenRepository(t.Context(), pr.BaseRepo) assert.NoError(t, err) defer gitRepo.Close() - mergeMessage, _, err := GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") + mergeMessage, _, err := GetDefaultMergeMessage(t.Context(), gitRepo, pr, "") assert.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (#3) from branch2 into master", mergeMessage) pr.BaseRepoID = 1 pr.HeadRepoID = 2 - mergeMessage, _, err = GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") + mergeMessage, _, err = GetDefaultMergeMessage(t.Context(), gitRepo, pr, "") assert.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (#3) from user2/repo1:branch2 into master", mergeMessage) } @@ -70,12 +69,12 @@ func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) { pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2, BaseRepo: baseRepo}) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) + assert.NoError(t, pr.LoadBaseRepo(t.Context())) gitRepo, err := gitrepo.OpenRepository(t.Context(), pr.BaseRepo) assert.NoError(t, err) defer gitRepo.Close() - mergeMessage, _, err := GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") + mergeMessage, _, err := GetDefaultMergeMessage(t.Context(), gitRepo, pr, "") assert.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (!3) from branch2 into master", mergeMessage) @@ -84,7 +83,7 @@ func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) { pr.HeadRepoID = 2 pr.BaseRepo = nil pr.HeadRepo = nil - mergeMessage, _, err = GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") + mergeMessage, _, err = GetDefaultMergeMessage(t.Context(), gitRepo, pr, "") assert.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (#3) from user2/repo2:branch2 into master", mergeMessage) diff --git a/services/pull/review_test.go b/services/pull/review_test.go index 3bce1e523d..ddb2c04eaa 100644 --- a/services/pull/review_test.go +++ b/services/pull/review_test.go @@ -6,7 +6,6 @@ package pull_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" @@ -19,11 +18,11 @@ func TestDismissReview(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) pull := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{}) - 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}) - review, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{ + review, err := issues_model.CreateReview(t.Context(), issues_model.CreateReviewOptions{ Issue: issue, Reviewer: reviewer, Type: issues_model.ReviewTypeReject, @@ -32,17 +31,17 @@ func TestDismissReview(t *testing.T) { assert.NoError(t, err) issue.IsClosed = true pull.HasMerged = false - assert.NoError(t, issues_model.UpdateIssueCols(db.DefaultContext, issue, "is_closed")) - assert.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) - _, err = pull_service.DismissReview(db.DefaultContext, review.ID, issue.RepoID, "", &user_model.User{}, false, false) + assert.NoError(t, issues_model.UpdateIssueCols(t.Context(), issue, "is_closed")) + assert.NoError(t, pull.UpdateCols(t.Context(), "has_merged")) + _, err = pull_service.DismissReview(t.Context(), review.ID, issue.RepoID, "", &user_model.User{}, false, false) assert.Error(t, err) assert.True(t, pull_service.IsErrDismissRequestOnClosedPR(err)) pull.HasMerged = true pull.Issue.IsClosed = false - assert.NoError(t, issues_model.UpdateIssueCols(db.DefaultContext, issue, "is_closed")) - assert.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) - _, err = pull_service.DismissReview(db.DefaultContext, review.ID, issue.RepoID, "", &user_model.User{}, false, false) + assert.NoError(t, issues_model.UpdateIssueCols(t.Context(), issue, "is_closed")) + assert.NoError(t, pull.UpdateCols(t.Context(), "has_merged")) + _, err = pull_service.DismissReview(t.Context(), review.ID, issue.RepoID, "", &user_model.User{}, false, false) assert.Error(t, err) assert.True(t, pull_service.IsErrDismissRequestOnClosedPR(err)) } diff --git a/services/pull/reviewer_test.go b/services/pull/reviewer_test.go index b106e2e89f..9fab65ce72 100644 --- a/services/pull/reviewer_test.go +++ b/services/pull/reviewer_test.go @@ -6,7 +6,6 @@ package pull_test import ( "testing" - "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" pull_service "code.gitea.io/gitea/services/pull" @@ -20,7 +19,7 @@ func TestRepoGetReviewers(t *testing.T) { // test public repo repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - ctx := db.DefaultContext + ctx := t.Context() reviewers, err := pull_service.GetReviewers(ctx, repo1, 2, 0) assert.NoError(t, err) if assert.Len(t, reviewers, 1) { @@ -61,12 +60,12 @@ func TestRepoGetReviewerTeams(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - teams, err := pull_service.GetReviewerTeams(db.DefaultContext, repo2) + teams, err := pull_service.GetReviewerTeams(t.Context(), repo2) assert.NoError(t, err) assert.Empty(t, teams) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) - teams, err = pull_service.GetReviewerTeams(db.DefaultContext, repo3) + teams, err = pull_service.GetReviewerTeams(t.Context(), repo3) assert.NoError(t, err) assert.Len(t, teams, 2) } diff --git a/services/release/release_test.go b/services/release/release_test.go index 8595aae899..ef495632a7 100644 --- a/services/release/release_test.go +++ b/services/release/release_test.go @@ -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" user_model "code.gitea.io/gitea/models/user" @@ -106,7 +105,7 @@ func TestRelease_Create(t *testing.T) { testPlayload := "testtest" - attach, err := attachment.NewAttachment(db.DefaultContext, &repo_model.Attachment{ + attach, err := attachment.NewAttachment(t.Context(), &repo_model.Attachment{ RepoID: repo.ID, UploaderID: user.ID, Name: "test.txt", @@ -153,13 +152,13 @@ func TestRelease_Update(t *testing.T) { IsPrerelease: false, IsTag: false, }, nil, "")) - release, err := repo_model.GetRelease(db.DefaultContext, repo.ID, "v1.1.1") + release, err := repo_model.GetRelease(t.Context(), repo.ID, "v1.1.1") assert.NoError(t, err) releaseCreatedUnix := release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Note = "Changed note" - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, nil, nil, nil)) - release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) + assert.NoError(t, UpdateRelease(t.Context(), user, gitRepo, release, nil, nil, nil)) + release, err = repo_model.GetReleaseByID(t.Context(), release.ID) assert.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) @@ -177,13 +176,13 @@ func TestRelease_Update(t *testing.T) { IsPrerelease: false, IsTag: false, }, nil, "")) - release, err = repo_model.GetRelease(db.DefaultContext, repo.ID, "v1.2.1") + release, err = repo_model.GetRelease(t.Context(), repo.ID, "v1.2.1") assert.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, nil, nil, nil)) - release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) + assert.NoError(t, UpdateRelease(t.Context(), user, gitRepo, release, nil, nil, nil)) + release, err = repo_model.GetReleaseByID(t.Context(), release.ID) assert.NoError(t, err) assert.Less(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) @@ -201,14 +200,14 @@ func TestRelease_Update(t *testing.T) { IsPrerelease: true, IsTag: false, }, nil, "")) - release, err = repo_model.GetRelease(db.DefaultContext, repo.ID, "v1.3.1") + release, err = repo_model.GetRelease(t.Context(), repo.ID, "v1.3.1") assert.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" release.Note = "Changed note" - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, nil, nil, nil)) - release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) + assert.NoError(t, UpdateRelease(t.Context(), user, gitRepo, release, nil, nil, nil)) + release, err = repo_model.GetReleaseByID(t.Context(), release.ID) assert.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) @@ -232,42 +231,42 @@ func TestRelease_Update(t *testing.T) { release.IsDraft = false tagName := release.TagName - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, nil, nil, nil)) - release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) + assert.NoError(t, UpdateRelease(t.Context(), user, gitRepo, release, nil, nil, nil)) + release, err = repo_model.GetReleaseByID(t.Context(), release.ID) assert.NoError(t, err) assert.Equal(t, tagName, release.TagName) // Add new attachments samplePayload := "testtest" - attach, err := attachment.NewAttachment(db.DefaultContext, &repo_model.Attachment{ + attach, err := attachment.NewAttachment(t.Context(), &repo_model.Attachment{ RepoID: repo.ID, UploaderID: user.ID, Name: "test.txt", }, strings.NewReader(samplePayload), int64(len([]byte(samplePayload)))) assert.NoError(t, err) - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, []string{attach.UUID}, nil, nil)) - assert.NoError(t, repo_model.GetReleaseAttachments(db.DefaultContext, release)) + assert.NoError(t, UpdateRelease(t.Context(), user, gitRepo, release, []string{attach.UUID}, nil, nil)) + assert.NoError(t, repo_model.GetReleaseAttachments(t.Context(), release)) assert.Len(t, release.Attachments, 1) assert.Equal(t, attach.UUID, release.Attachments[0].UUID) assert.Equal(t, release.ID, release.Attachments[0].ReleaseID) assert.Equal(t, attach.Name, release.Attachments[0].Name) // update the attachment name - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, nil, nil, map[string]string{ + assert.NoError(t, UpdateRelease(t.Context(), user, gitRepo, release, nil, nil, map[string]string{ attach.UUID: "test2.txt", })) release.Attachments = nil - assert.NoError(t, repo_model.GetReleaseAttachments(db.DefaultContext, release)) + assert.NoError(t, repo_model.GetReleaseAttachments(t.Context(), release)) assert.Len(t, release.Attachments, 1) assert.Equal(t, attach.UUID, release.Attachments[0].UUID) assert.Equal(t, release.ID, release.Attachments[0].ReleaseID) assert.Equal(t, "test2.txt", release.Attachments[0].Name) // delete the attachment - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, nil, []string{attach.UUID}, nil)) + assert.NoError(t, UpdateRelease(t.Context(), user, gitRepo, release, nil, []string{attach.UUID}, nil)) release.Attachments = nil - assert.NoError(t, repo_model.GetReleaseAttachments(db.DefaultContext, release)) + assert.NoError(t, repo_model.GetReleaseAttachments(t.Context(), release)) assert.Empty(t, release.Attachments) } @@ -295,13 +294,13 @@ func TestRelease_createTag(t *testing.T) { IsPrerelease: false, IsTag: false, } - _, err = createTag(db.DefaultContext, gitRepo, release, "") + _, err = createTag(t.Context(), gitRepo, release, "") assert.NoError(t, err) assert.NotEmpty(t, release.CreatedUnix) releaseCreatedUnix := release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Note = "Changed note" - _, err = createTag(db.DefaultContext, gitRepo, release, "") + _, err = createTag(t.Context(), gitRepo, release, "") assert.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) @@ -319,12 +318,12 @@ func TestRelease_createTag(t *testing.T) { IsPrerelease: false, IsTag: false, } - _, err = createTag(db.DefaultContext, gitRepo, release, "") + _, err = createTag(t.Context(), gitRepo, release, "") assert.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" - _, err = createTag(db.DefaultContext, gitRepo, release, "") + _, err = createTag(t.Context(), gitRepo, release, "") assert.NoError(t, err) assert.Less(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) @@ -342,13 +341,13 @@ func TestRelease_createTag(t *testing.T) { IsPrerelease: true, IsTag: false, } - _, err = createTag(db.DefaultContext, gitRepo, release, "") + _, err = createTag(t.Context(), gitRepo, release, "") assert.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" release.Note = "Changed note" - _, err = createTag(db.DefaultContext, gitRepo, release, "") + _, err = createTag(t.Context(), gitRepo, release, "") assert.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) } diff --git a/services/repository/adopt.go b/services/repository/adopt.go index 2bd1c55de4..a17111dfaf 100644 --- a/services/repository/adopt.go +++ b/services/repository/adopt.go @@ -17,6 +17,7 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/container" "code.gitea.io/gitea/modules/gitrepo" + "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/optional" repo_module "code.gitea.io/gitea/modules/repository" @@ -28,7 +29,7 @@ import ( ) func deleteFailedAdoptRepository(repoID int64) error { - return db.WithTx(db.DefaultContext, func(ctx context.Context) error { + return db.WithTx(graceful.GetManager().ShutdownContext(), func(ctx context.Context) error { if err := deleteDBRepository(ctx, repoID); err != nil { return fmt.Errorf("deleteDBRepository: %w", err) } diff --git a/services/repository/adopt_test.go b/services/repository/adopt_test.go index 86f586c748..46f2f48417 100644 --- a/services/repository/adopt_test.go +++ b/services/repository/adopt_test.go @@ -43,7 +43,7 @@ func TestCheckUnadoptedRepositories(t *testing.T) { // Non existent user // unadopted := &unadoptedRepositories{start: 0, end: 100} - err := checkUnadoptedRepositories(db.DefaultContext, "notauser", []string{"repo"}, unadopted) + err := checkUnadoptedRepositories(t.Context(), "notauser", []string{"repo"}, unadopted) assert.NoError(t, err) assert.Empty(t, unadopted.repositories) // @@ -54,14 +54,14 @@ func TestCheckUnadoptedRepositories(t *testing.T) { repoName := "repo2" unadoptedRepoName := "unadopted" unadopted = &unadoptedRepositories{start: 0, end: 100} - err = checkUnadoptedRepositories(db.DefaultContext, userName, []string{repoName, unadoptedRepoName}, unadopted) + err = checkUnadoptedRepositories(t.Context(), userName, []string{repoName, unadoptedRepoName}, unadopted) assert.NoError(t, err) assert.Equal(t, []string{path.Join(userName, unadoptedRepoName)}, unadopted.repositories) // // Existing (adopted) repository is not returned // unadopted = &unadoptedRepositories{start: 0, end: 100} - err = checkUnadoptedRepositories(db.DefaultContext, userName, []string{repoName}, unadopted) + err = checkUnadoptedRepositories(t.Context(), userName, []string{repoName}, unadopted) assert.NoError(t, err) assert.Empty(t, unadopted.repositories) assert.Equal(t, 0, unadopted.index) @@ -76,13 +76,13 @@ func TestListUnadoptedRepositories_ListOptions(t *testing.T) { } opts := db.ListOptions{Page: 1, PageSize: 1} - repoNames, count, err := ListUnadoptedRepositories(db.DefaultContext, "", &opts) + repoNames, count, err := ListUnadoptedRepositories(t.Context(), "", &opts) assert.NoError(t, err) assert.Equal(t, 2, count) assert.Equal(t, unadoptedList[0], repoNames[0]) opts = db.ListOptions{Page: 2, PageSize: 1} - repoNames, count, err = ListUnadoptedRepositories(db.DefaultContext, "", &opts) + repoNames, count, err = ListUnadoptedRepositories(t.Context(), "", &opts) assert.NoError(t, err) assert.Equal(t, 2, count) assert.Equal(t, unadoptedList[1], repoNames[0]) @@ -97,7 +97,7 @@ func TestAdoptRepository(t *testing.T) { destDir := filepath.Join(setting.RepoRootPath, user2.Name, "test-adopt.git") assert.NoError(t, unittest.SyncDirs(filepath.Join(setting.RepoRootPath, user2.Name, "repo1.git"), destDir)) - adoptedRepo, err := AdoptRepository(db.DefaultContext, user2, user2, CreateRepoOptions{Name: "test-adopt"}) + adoptedRepo, err := AdoptRepository(t.Context(), user2, user2, CreateRepoOptions{Name: "test-adopt"}) assert.NoError(t, err) repoTestAdopt := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: "test-adopt"}) assert.Equal(t, "sha1", repoTestAdopt.ObjectFormatName) @@ -113,7 +113,7 @@ func TestAdoptRepository(t *testing.T) { _ = os.RemoveAll(filepath.Join(destDir, "hooks", "update.d")) assert.NoError(t, os.WriteFile(filepath.Join(destDir, "hooks", "update.d"), []byte("tests"), os.ModePerm)) - adoptedRepo, err = AdoptRepository(db.DefaultContext, user2, user2, CreateRepoOptions{Name: "test-adopt"}) + adoptedRepo, err = AdoptRepository(t.Context(), user2, user2, CreateRepoOptions{Name: "test-adopt"}) assert.Error(t, err) assert.Nil(t, adoptedRepo) diff --git a/services/repository/archiver/archiver_test.go b/services/repository/archiver/archiver_test.go index 87324ad38c..4ba193ccb6 100644 --- a/services/repository/archiver/archiver_test.go +++ b/services/repository/archiver/archiver_test.go @@ -7,7 +7,6 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/services/contexttest" @@ -79,13 +78,13 @@ func TestArchive_Basic(t *testing.T) { inFlight[1] = tgzReq inFlight[2] = secondReq - doArchive(db.DefaultContext, zipReq) - doArchive(db.DefaultContext, tgzReq) - doArchive(db.DefaultContext, secondReq) + doArchive(t.Context(), zipReq) + doArchive(t.Context(), tgzReq) + doArchive(t.Context(), secondReq) // Make sure sending an unprocessed request through doesn't affect the queue // count. - doArchive(db.DefaultContext, zipReq) + doArchive(t.Context(), zipReq) // Sleep two seconds to make sure the queue doesn't change. time.Sleep(2 * time.Second) @@ -100,7 +99,7 @@ func TestArchive_Basic(t *testing.T) { // We still have the other three stalled at completion, waiting to remove // from archiveInProgress. Try to submit this new one before its // predecessor has cleared out of the queue. - doArchive(db.DefaultContext, zipReq2) + doArchive(t.Context(), zipReq2) // Now we'll submit a request and TimedWaitForCompletion twice, before and // after we release it. We should trigger both the timeout and non-timeout @@ -108,7 +107,7 @@ func TestArchive_Basic(t *testing.T) { timedReq, err := NewRequest(ctx.Repo.Repository.ID, ctx.Repo.GitRepo, secondCommit+".tar.gz") assert.NoError(t, err) assert.NotNil(t, timedReq) - doArchive(db.DefaultContext, timedReq) + doArchive(t.Context(), timedReq) zipReq2, err = NewRequest(ctx.Repo.Repository.ID, ctx.Repo.GitRepo, firstCommit+".zip") assert.NoError(t, err) diff --git a/services/repository/avatar_test.go b/services/repository/avatar_test.go index 2dc5173eec..6c7b9e6d26 100644 --- a/services/repository/avatar_test.go +++ b/services/repository/avatar_test.go @@ -9,7 +9,6 @@ import ( "image/png" "testing" - "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/avatar" @@ -26,7 +25,7 @@ func TestUploadAvatar(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}) - err := UploadAvatar(db.DefaultContext, repo, buff.Bytes()) + err := UploadAvatar(t.Context(), repo, buff.Bytes()) assert.NoError(t, err) assert.Equal(t, avatar.HashAvatar(10, buff.Bytes()), repo.Avatar) } @@ -40,7 +39,7 @@ func TestUploadBigAvatar(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}) - err := UploadAvatar(db.DefaultContext, repo, buff.Bytes()) + err := UploadAvatar(t.Context(), repo, buff.Bytes()) assert.Error(t, err) } @@ -53,10 +52,10 @@ func TestDeleteAvatar(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}) - err := UploadAvatar(db.DefaultContext, repo, buff.Bytes()) + err := UploadAvatar(t.Context(), repo, buff.Bytes()) assert.NoError(t, err) - err = DeleteAvatar(db.DefaultContext, repo) + err = DeleteAvatar(t.Context(), repo) assert.NoError(t, err) assert.Empty(t, repo.Avatar) @@ -65,7 +64,7 @@ func TestDeleteAvatar(t *testing.T) { func TestGenerateAvatar(t *testing.T) { templateRepo := &repo_model.Repository{ID: 10, Avatar: "a"} generateRepo := &repo_model.Repository{ID: 11} - _ = generateAvatar(db.DefaultContext, templateRepo, generateRepo) + _ = generateAvatar(t.Context(), templateRepo, generateRepo) assert.NotEmpty(t, generateRepo.Avatar) assert.NotEqual(t, templateRepo.Avatar, generateRepo.Avatar) } diff --git a/services/repository/collaboration_test.go b/services/repository/collaboration_test.go index 2b9a5d0b8b..5e33c50366 100644 --- a/services/repository/collaboration_test.go +++ b/services/repository/collaboration_test.go @@ -6,7 +6,6 @@ package repository import ( "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -20,9 +19,9 @@ func TestRepository_AddCollaborator(t *testing.T) { testSuccess := func(repoID, userID int64) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) - assert.NoError(t, repo.LoadOwner(db.DefaultContext)) + assert.NoError(t, repo.LoadOwner(t.Context())) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID}) - assert.NoError(t, AddOrUpdateCollaborator(db.DefaultContext, repo, user, perm.AccessModeWrite)) + assert.NoError(t, AddOrUpdateCollaborator(t.Context(), repo, user, perm.AccessModeWrite)) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}, &user_model.User{ID: userID}) } testSuccess(1, 4) @@ -36,11 +35,11 @@ func TestRepository_DeleteCollaboration(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) - assert.NoError(t, repo.LoadOwner(db.DefaultContext)) - assert.NoError(t, DeleteCollaboration(db.DefaultContext, repo, user)) + assert.NoError(t, repo.LoadOwner(t.Context())) + assert.NoError(t, DeleteCollaboration(t.Context(), repo, user)) unittest.AssertNotExistsBean(t, &repo_model.Collaboration{RepoID: repo.ID, UserID: user.ID}) - assert.NoError(t, DeleteCollaboration(db.DefaultContext, repo, user)) + assert.NoError(t, DeleteCollaboration(t.Context(), repo, user)) unittest.AssertNotExistsBean(t, &repo_model.Collaboration{RepoID: repo.ID, UserID: user.ID}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID}) diff --git a/services/repository/contributors_graph_test.go b/services/repository/contributors_graph_test.go index 7d32b1c931..efdecf4b81 100644 --- a/services/repository/contributors_graph_test.go +++ b/services/repository/contributors_graph_test.go @@ -7,7 +7,6 @@ import ( "slices" "testing" - "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/cache" @@ -20,7 +19,7 @@ func TestRepository_ContributorsGraph(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - assert.NoError(t, repo.LoadOwner(db.DefaultContext)) + assert.NoError(t, repo.LoadOwner(t.Context())) mockCache, err := cache.NewStringCache(setting.Cache{}) assert.NoError(t, err) diff --git a/services/repository/create.go b/services/repository/create.go index c415a24353..da31ee4121 100644 --- a/services/repository/create.go +++ b/services/repository/create.go @@ -23,6 +23,7 @@ import ( "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/gitrepo" + "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/options" repo_module "code.gitea.io/gitea/modules/repository" @@ -459,7 +460,7 @@ func createRepositoryInDB(ctx context.Context, doer, u *user_model.User, repo *r } func cleanupRepository(repoID int64) { - if errDelete := DeleteRepositoryDirectly(db.DefaultContext, repoID); errDelete != nil { + if errDelete := DeleteRepositoryDirectly(graceful.GetManager().ShutdownContext(), repoID); errDelete != nil { log.Error("cleanupRepository failed: %v", errDelete) // add system notice if err := system_model.CreateRepositoryNotice("DeleteRepositoryDirectly failed when cleanup repository: %v", errDelete); err != nil { diff --git a/services/repository/create_test.go b/services/repository/create_test.go index e1642ffb30..b8c2ea59dd 100644 --- a/services/repository/create_test.go +++ b/services/repository/create_test.go @@ -7,7 +7,6 @@ import ( "os" "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" @@ -34,14 +33,14 @@ func TestCreateRepositoryDirectly(t *testing.T) { unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerName: user2.Name, Name: createdRepo.Name}) - err = DeleteRepositoryDirectly(db.DefaultContext, createdRepo.ID) + err = DeleteRepositoryDirectly(t.Context(), createdRepo.ID) assert.NoError(t, err) // a failed creating because some mock data // create the repository directory so that the creation will fail after database record created. assert.NoError(t, os.MkdirAll(repo_model.RepoPath(user2.Name, createdRepo.Name), os.ModePerm)) - createdRepo2, err := CreateRepositoryDirectly(db.DefaultContext, user2, user2, CreateRepoOptions{ + createdRepo2, err := CreateRepositoryDirectly(t.Context(), user2, user2, CreateRepoOptions{ Name: "created-repo", }, true) assert.Nil(t, createdRepo2) diff --git a/services/repository/delete.go b/services/repository/delete.go index c48d6e1d56..65dfc2a3b7 100644 --- a/services/repository/delete.go +++ b/services/repository/delete.go @@ -24,6 +24,7 @@ import ( "code.gitea.io/gitea/models/webhook" actions_module "code.gitea.io/gitea/modules/actions" "code.gitea.io/gitea/modules/gitrepo" + "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/lfs" "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/storage" @@ -309,8 +310,7 @@ func DeleteRepositoryDirectly(ctx context.Context, repoID int64, ignoreOrgTeams // Remove repository files. if err := gitrepo.DeleteRepository(ctx, repo); err != nil { desc := fmt.Sprintf("Delete repository files [%s]: %v", repo.FullName(), err) - // Note we use the db.DefaultContext here rather than passing in a context as the context may be cancelled - if err = system_model.CreateNotice(db.DefaultContext, system_model.NoticeRepository, desc); err != nil { + if err = system_model.CreateNotice(graceful.GetManager().ShutdownContext(), system_model.NoticeRepository, desc); err != nil { log.Error("CreateRepositoryNotice: %v", err) } } diff --git a/services/repository/delete_test.go b/services/repository/delete_test.go index 869b8af11d..f06373f24a 100644 --- a/services/repository/delete_test.go +++ b/services/repository/delete_test.go @@ -6,7 +6,6 @@ package repository_test import ( "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -21,7 +20,7 @@ func TestTeam_HasRepository(t *testing.T) { test := func(teamID, repoID int64, expected bool) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.Equal(t, expected, repo_service.HasRepository(db.DefaultContext, team, repoID)) + assert.Equal(t, expected, repo_service.HasRepository(t.Context(), team, repoID)) } test(1, 1, false) test(1, 3, true) @@ -37,7 +36,7 @@ func TestTeam_RemoveRepository(t *testing.T) { testSuccess := func(teamID, repoID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, repo_service.RemoveRepositoryFromTeam(db.DefaultContext, team, repoID)) + assert.NoError(t, repo_service.RemoveRepositoryFromTeam(t.Context(), team, repoID)) unittest.AssertNotExistsBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repoID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &repo_model.Repository{ID: repoID}) } @@ -51,5 +50,5 @@ func TestDeleteOwnerRepositoriesDirectly(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.NoError(t, repo_service.DeleteOwnerRepositoriesDirectly(db.DefaultContext, user)) + assert.NoError(t, repo_service.DeleteOwnerRepositoriesDirectly(t.Context(), user)) } diff --git a/services/repository/fork_test.go b/services/repository/fork_test.go index 7fe6a83c1a..680a7f3207 100644 --- a/services/repository/fork_test.go +++ b/services/repository/fork_test.go @@ -7,7 +7,6 @@ import ( "os" "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" @@ -68,14 +67,14 @@ func TestForkRepositoryCleanup(t *testing.T) { assert.NoError(t, err) assert.True(t, exist) - err = DeleteRepositoryDirectly(db.DefaultContext, fork.ID) + err = DeleteRepositoryDirectly(t.Context(), fork.ID) assert.NoError(t, err) // a failed creating because some mock data // create the repository directory so that the creation will fail after database record created. assert.NoError(t, os.MkdirAll(repo_model.RepoPath(user2.Name, "test"), os.ModePerm)) - fork2, err := ForkRepository(db.DefaultContext, user2, user2, ForkRepoOptions{ + fork2, err := ForkRepository(t.Context(), user2, user2, ForkRepoOptions{ BaseRepo: repo10, Name: "test", }) diff --git a/services/repository/lfs_test.go b/services/repository/lfs_test.go index 78ff8c853e..7fb202f42d 100644 --- a/services/repository/lfs_test.go +++ b/services/repository/lfs_test.go @@ -8,7 +8,6 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -27,7 +26,7 @@ func TestGarbageCollectLFSMetaObjects(t *testing.T) { err := storage.Init() assert.NoError(t, err) - repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") + repo, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), "user2", "repo1") assert.NoError(t, err) // add lfs object @@ -43,7 +42,7 @@ func TestGarbageCollectLFSMetaObjects(t *testing.T) { assert.NoError(t, err) // lfs meta has been deleted - _, err = git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, lfsOid) + _, err = git_model.GetLFSMetaObjectByOid(t.Context(), repo.ID, lfsOid) assert.ErrorIs(t, err, git_model.ErrLFSObjectNotExist) } @@ -51,7 +50,7 @@ func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string pointer, err := lfs.GeneratePointer(bytes.NewReader(*content)) assert.NoError(t, err) - _, err = git_model.NewLFSMetaObject(db.DefaultContext, repositoryID, pointer) + _, err = git_model.NewLFSMetaObject(t.Context(), repositoryID, pointer) assert.NoError(t, err) contentStore := lfs.NewContentStore() exist, err := contentStore.Exists(pointer) diff --git a/services/repository/repo_team_test.go b/services/repository/repo_team_test.go index 70b1b47d0a..1139d06cf8 100644 --- a/services/repository/repo_team_test.go +++ b/services/repository/repo_team_test.go @@ -6,7 +6,6 @@ package repository import ( "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -20,7 +19,7 @@ func TestTeam_AddRepository(t *testing.T) { testSuccess := func(teamID, repoID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) - assert.NoError(t, TeamAddRepository(db.DefaultContext, team, repo)) + assert.NoError(t, TeamAddRepository(t.Context(), team, repo)) unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repoID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &repo_model.Repository{ID: repoID}) } @@ -29,6 +28,6 @@ func TestTeam_AddRepository(t *testing.T) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - assert.Error(t, TeamAddRepository(db.DefaultContext, team, repo)) + assert.Error(t, TeamAddRepository(t.Context(), team, repo)) unittest.CheckConsistencyFor(t, &organization.Team{ID: 1}, &repo_model.Repository{ID: 1}) } diff --git a/services/repository/repository_test.go b/services/repository/repository_test.go index 8f9fdf8fa1..ba02e7601c 100644 --- a/services/repository/repository_test.go +++ b/services/repository/repository_test.go @@ -30,9 +30,9 @@ func TestLinkedRepository(t *testing.T) { } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - attach, err := repo_model.GetAttachmentByID(db.DefaultContext, tc.attachID) + attach, err := repo_model.GetAttachmentByID(t.Context(), tc.attachID) assert.NoError(t, err) - repo, unitType, err := LinkedRepository(db.DefaultContext, attach) + repo, unitType, err := LinkedRepository(t.Context(), attach) assert.NoError(t, err) if tc.expectedRepo != nil { assert.Equal(t, tc.expectedRepo.ID, repo.ID) @@ -46,17 +46,17 @@ func TestUpdateRepositoryVisibilityChanged(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) // Get sample repo and change visibility - repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 9) + repo, err := repo_model.GetRepositoryByID(t.Context(), 9) assert.NoError(t, err) repo.IsPrivate = true // Update it - err = updateRepository(db.DefaultContext, repo, true) + err = updateRepository(t.Context(), repo, true) assert.NoError(t, err) // Check visibility of action has become private act := activities_model.Action{} - _, err = db.GetEngine(db.DefaultContext).ID(3).Get(&act) + _, err = db.GetEngine(t.Context()).ID(3).Get(&act) assert.NoError(t, err) assert.True(t, act.IsPrivate) diff --git a/services/repository/transfer_test.go b/services/repository/transfer_test.go index 80a073e9f9..8d73fef7f4 100644 --- a/services/repository/transfer_test.go +++ b/services/repository/transfer_test.go @@ -8,7 +8,6 @@ import ( "testing" activities_model "code.gitea.io/gitea/models/activities" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" access_model "code.gitea.io/gitea/models/perm/access" repo_model "code.gitea.io/gitea/models/repo" @@ -39,10 +38,10 @@ func TestTransferOwnership(t *testing.T) { doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) - assert.NoError(t, repo.LoadOwner(db.DefaultContext)) + assert.NoError(t, repo.LoadOwner(t.Context())) repoTransfer := unittest.AssertExistsAndLoadBean(t, &repo_model.RepoTransfer{ID: 1}) - assert.NoError(t, repoTransfer.LoadAttributes(db.DefaultContext)) - assert.NoError(t, AcceptTransferOwnership(db.DefaultContext, repo, doer)) + assert.NoError(t, repoTransfer.LoadAttributes(t.Context())) + assert.NoError(t, AcceptTransferOwnership(t.Context(), repo, doer)) transferredRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) assert.EqualValues(t, 1, transferredRepo.OwnerID) // repo_transfer.yml id=1 @@ -70,15 +69,15 @@ func TestStartRepositoryTransferSetPermission(t *testing.T) { doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) recipient := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - assert.NoError(t, repo.LoadOwner(db.DefaultContext)) + assert.NoError(t, repo.LoadOwner(t.Context())) - hasAccess, err := access_model.HasAnyUnitAccess(db.DefaultContext, recipient.ID, repo) + hasAccess, err := access_model.HasAnyUnitAccess(t.Context(), recipient.ID, repo) assert.NoError(t, err) assert.False(t, hasAccess) - assert.NoError(t, StartRepositoryTransfer(db.DefaultContext, doer, recipient, repo, nil)) + assert.NoError(t, StartRepositoryTransfer(t.Context(), doer, recipient, repo, nil)) - hasAccess, err = access_model.HasAnyUnitAccess(db.DefaultContext, recipient.ID, repo) + hasAccess, err = access_model.HasAnyUnitAccess(t.Context(), recipient.ID, repo) assert.NoError(t, err) assert.True(t, hasAccess) @@ -91,41 +90,41 @@ func TestRepositoryTransfer(t *testing.T) { doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) - transfer, err := repo_model.GetPendingRepositoryTransfer(db.DefaultContext, repo) + transfer, err := repo_model.GetPendingRepositoryTransfer(t.Context(), repo) assert.NoError(t, err) assert.NotNil(t, transfer) // Cancel transfer - assert.NoError(t, CancelRepositoryTransfer(db.DefaultContext, transfer, doer)) + assert.NoError(t, CancelRepositoryTransfer(t.Context(), transfer, doer)) - transfer, err = repo_model.GetPendingRepositoryTransfer(db.DefaultContext, repo) + transfer, err = repo_model.GetPendingRepositoryTransfer(t.Context(), repo) assert.Error(t, err) assert.Nil(t, transfer) assert.True(t, repo_model.IsErrNoPendingTransfer(err)) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.NoError(t, repo_model.CreatePendingRepositoryTransfer(db.DefaultContext, doer, user2, repo.ID, nil)) + assert.NoError(t, repo_model.CreatePendingRepositoryTransfer(t.Context(), doer, user2, repo.ID, nil)) - transfer, err = repo_model.GetPendingRepositoryTransfer(db.DefaultContext, repo) + transfer, err = repo_model.GetPendingRepositoryTransfer(t.Context(), repo) assert.NoError(t, err) - assert.NoError(t, transfer.LoadAttributes(db.DefaultContext)) + assert.NoError(t, transfer.LoadAttributes(t.Context())) assert.Equal(t, "user2", transfer.Recipient.Name) org6 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Only transfer can be started at any given time - err = repo_model.CreatePendingRepositoryTransfer(db.DefaultContext, doer, org6, repo.ID, nil) + err = repo_model.CreatePendingRepositoryTransfer(t.Context(), doer, org6, repo.ID, nil) assert.Error(t, err) assert.True(t, repo_model.IsErrRepoTransferInProgress(err)) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) // Unknown user, transfer non-existent transfer repo id = 2 - err = repo_model.CreatePendingRepositoryTransfer(db.DefaultContext, doer, &user_model.User{ID: 1000, LowerName: "user1000"}, repo2.ID, nil) + err = repo_model.CreatePendingRepositoryTransfer(t.Context(), doer, &user_model.User{ID: 1000, LowerName: "user1000"}, repo2.ID, nil) assert.Error(t, err) // Reject transfer - err = RejectRepositoryTransfer(db.DefaultContext, repo2, doer) + err = RejectRepositoryTransfer(t.Context(), repo2, doer) assert.True(t, repo_model.IsErrNoPendingTransfer(err)) } @@ -139,29 +138,29 @@ func TestRepositoryTransferRejection(t *testing.T) { doerAdmin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 5}) - transfer, err := repo_model.GetPendingRepositoryTransfer(db.DefaultContext, repo) + transfer, err := repo_model.GetPendingRepositoryTransfer(t.Context(), repo) require.NoError(t, err) require.NotNil(t, transfer) - require.NoError(t, transfer.LoadRecipient(db.DefaultContext)) + require.NoError(t, transfer.LoadRecipient(t.Context())) require.True(t, doerAdmin.CanCreateRepoIn(transfer.Recipient)) // admin is not subject to limits // Administrator should not be affected by the limits so transfer should be successful - assert.NoError(t, AcceptTransferOwnership(db.DefaultContext, repo, doerAdmin)) + assert.NoError(t, AcceptTransferOwnership(t.Context(), repo, doerAdmin)) // Non admin user case doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 10}) repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 21}) - transfer, err = repo_model.GetPendingRepositoryTransfer(db.DefaultContext, repo) + transfer, err = repo_model.GetPendingRepositoryTransfer(t.Context(), repo) require.NoError(t, err) require.NotNil(t, transfer) - require.NoError(t, transfer.LoadRecipient(db.DefaultContext)) + require.NoError(t, transfer.LoadRecipient(t.Context())) require.False(t, doer.CanCreateRepoIn(transfer.Recipient)) // regular user is subject to limits // Cannot accept because of the limit - err = AcceptTransferOwnership(db.DefaultContext, repo, doer) + err = AcceptTransferOwnership(t.Context(), repo, doer) assert.Error(t, err) assert.True(t, IsRepositoryLimitReached(err)) } diff --git a/services/task/task.go b/services/task/task.go index ee5fa1f348..86cf6a041f 100644 --- a/services/task/task.go +++ b/services/task/task.go @@ -9,7 +9,6 @@ import ( "fmt" admin_model "code.gitea.io/gitea/models/admin" - "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/graceful" @@ -50,7 +49,7 @@ func Init() error { func handler(items ...*admin_model.Task) []*admin_model.Task { for _, task := range items { - if err := Run(db.DefaultContext, task); err != nil { + if err := Run(graceful.GetManager().ShutdownContext(), task); err != nil { log.Error("Run task failed: %v", err) } } diff --git a/services/uinotification/notify.go b/services/uinotification/notify.go index be5f7019a2..dd3f1557c6 100644 --- a/services/uinotification/notify.go +++ b/services/uinotification/notify.go @@ -52,7 +52,7 @@ func NewNotifier() notify_service.Notifier { func handler(items ...issueNotificationOpts) []issueNotificationOpts { for _, opts := range items { - if err := activities_model.CreateOrUpdateIssueNotifications(db.DefaultContext, opts.IssueID, opts.CommentID, opts.NotificationAuthorID, opts.ReceiverID); err != nil { + if err := activities_model.CreateOrUpdateIssueNotifications(graceful.GetManager().ShutdownContext(), opts.IssueID, opts.CommentID, opts.NotificationAuthorID, opts.ReceiverID); err != nil { log.Error("Was unable to create issue notification: %v", err) } } diff --git a/services/user/block_test.go b/services/user/block_test.go index aec3e03cf3..5dc6c1210d 100644 --- a/services/user/block_test.go +++ b/services/user/block_test.go @@ -6,7 +6,6 @@ package user import ( "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -23,23 +22,23 @@ func TestCanBlockUser(t *testing.T) { org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) // Doer can't self block - assert.False(t, CanBlockUser(db.DefaultContext, user1, user2, user1)) + assert.False(t, CanBlockUser(t.Context(), user1, user2, user1)) // Blocker can't be blockee - assert.False(t, CanBlockUser(db.DefaultContext, user1, user2, user2)) + assert.False(t, CanBlockUser(t.Context(), user1, user2, user2)) // Can't block already blocked user - assert.False(t, CanBlockUser(db.DefaultContext, user1, user2, user29)) + assert.False(t, CanBlockUser(t.Context(), user1, user2, user29)) // Blockee can't be an organization - assert.False(t, CanBlockUser(db.DefaultContext, user1, user2, org3)) + assert.False(t, CanBlockUser(t.Context(), user1, user2, org3)) // Doer must be blocker or admin - assert.False(t, CanBlockUser(db.DefaultContext, user2, user4, user29)) + assert.False(t, CanBlockUser(t.Context(), user2, user4, user29)) // Organization can't block a member - assert.False(t, CanBlockUser(db.DefaultContext, user1, org3, user4)) + assert.False(t, CanBlockUser(t.Context(), user1, org3, user4)) // Doer must be organization owner or admin if blocker is an organization - assert.False(t, CanBlockUser(db.DefaultContext, user4, org3, user2)) + assert.False(t, CanBlockUser(t.Context(), user4, org3, user2)) - assert.True(t, CanBlockUser(db.DefaultContext, user1, user2, user4)) - assert.True(t, CanBlockUser(db.DefaultContext, user2, user2, user4)) - assert.True(t, CanBlockUser(db.DefaultContext, user2, org3, user29)) + assert.True(t, CanBlockUser(t.Context(), user1, user2, user4)) + assert.True(t, CanBlockUser(t.Context(), user2, user2, user4)) + assert.True(t, CanBlockUser(t.Context(), user2, org3, user29)) } func TestCanUnblockUser(t *testing.T) { @@ -52,15 +51,15 @@ func TestCanUnblockUser(t *testing.T) { org17 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 17}) // Doer can't self unblock - assert.False(t, CanUnblockUser(db.DefaultContext, user1, user2, user1)) + assert.False(t, CanUnblockUser(t.Context(), user1, user2, user1)) // Can't unblock not blocked user - assert.False(t, CanUnblockUser(db.DefaultContext, user1, user2, user28)) + assert.False(t, CanUnblockUser(t.Context(), user1, user2, user28)) // Doer must be blocker or admin - assert.False(t, CanUnblockUser(db.DefaultContext, user28, user2, user29)) + assert.False(t, CanUnblockUser(t.Context(), user28, user2, user29)) // Doer must be organization owner or admin if blocker is an organization - assert.False(t, CanUnblockUser(db.DefaultContext, user2, org17, user28)) + assert.False(t, CanUnblockUser(t.Context(), user2, org17, user28)) - assert.True(t, CanUnblockUser(db.DefaultContext, user1, user2, user29)) - assert.True(t, CanUnblockUser(db.DefaultContext, user2, user2, user29)) - assert.True(t, CanUnblockUser(db.DefaultContext, user1, org17, user28)) + assert.True(t, CanUnblockUser(t.Context(), user1, user2, user29)) + assert.True(t, CanUnblockUser(t.Context(), user2, user2, user29)) + assert.True(t, CanUnblockUser(t.Context(), user1, org17, user28)) } diff --git a/services/user/email_test.go b/services/user/email_test.go index b40f86b6a6..78770633d2 100644 --- a/services/user/email_test.go +++ b/services/user/email_test.go @@ -6,7 +6,6 @@ package user import ( "testing" - "code.gitea.io/gitea/models/db" organization_model "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -21,23 +20,23 @@ func TestAdminAddOrSetPrimaryEmailAddress(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 27}) - emails, err := user_model.GetEmailAddresses(db.DefaultContext, user.ID) + emails, err := user_model.GetEmailAddresses(t.Context(), user.ID) assert.NoError(t, err) assert.Len(t, emails, 1) - primary, err := user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) + primary, err := user_model.GetPrimaryEmailAddressOfUser(t.Context(), user.ID) assert.NoError(t, err) assert.NotEqual(t, "new-primary@example.com", primary.Email) assert.Equal(t, user.Email, primary.Email) - assert.NoError(t, AdminAddOrSetPrimaryEmailAddress(db.DefaultContext, user, "new-primary@example.com")) + assert.NoError(t, AdminAddOrSetPrimaryEmailAddress(t.Context(), user, "new-primary@example.com")) - primary, err = user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) + primary, err = user_model.GetPrimaryEmailAddressOfUser(t.Context(), user.ID) assert.NoError(t, err) assert.Equal(t, "new-primary@example.com", primary.Email) assert.Equal(t, user.Email, primary.Email) - emails, err = user_model.GetEmailAddresses(db.DefaultContext, user.ID) + emails, err = user_model.GetEmailAddresses(t.Context(), user.ID) assert.NoError(t, err) assert.Len(t, emails, 2) @@ -46,21 +45,21 @@ func TestAdminAddOrSetPrimaryEmailAddress(t *testing.T) { setting.Service.EmailDomainAllowList = []glob.Glob{} }() - assert.NoError(t, AdminAddOrSetPrimaryEmailAddress(db.DefaultContext, user, "new-primary2@example2.com")) + assert.NoError(t, AdminAddOrSetPrimaryEmailAddress(t.Context(), user, "new-primary2@example2.com")) - primary, err = user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) + primary, err = user_model.GetPrimaryEmailAddressOfUser(t.Context(), user.ID) assert.NoError(t, err) assert.Equal(t, "new-primary2@example2.com", primary.Email) assert.Equal(t, user.Email, primary.Email) - assert.NoError(t, AdminAddOrSetPrimaryEmailAddress(db.DefaultContext, user, "user27@example.com")) + assert.NoError(t, AdminAddOrSetPrimaryEmailAddress(t.Context(), user, "user27@example.com")) - primary, err = user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) + primary, err = user_model.GetPrimaryEmailAddressOfUser(t.Context(), user.ID) assert.NoError(t, err) assert.Equal(t, "user27@example.com", primary.Email) assert.Equal(t, user.Email, primary.Email) - emails, err = user_model.GetEmailAddresses(db.DefaultContext, user.ID) + emails, err = user_model.GetEmailAddresses(t.Context(), user.ID) assert.NoError(t, err) assert.Len(t, emails, 3) } @@ -71,27 +70,27 @@ func TestReplacePrimaryEmailAddress(t *testing.T) { t.Run("User", func(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 13}) - emails, err := user_model.GetEmailAddresses(db.DefaultContext, user.ID) + emails, err := user_model.GetEmailAddresses(t.Context(), user.ID) assert.NoError(t, err) assert.Len(t, emails, 1) - primary, err := user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) + primary, err := user_model.GetPrimaryEmailAddressOfUser(t.Context(), user.ID) assert.NoError(t, err) assert.NotEqual(t, "primary-13@example.com", primary.Email) assert.Equal(t, user.Email, primary.Email) - assert.NoError(t, ReplacePrimaryEmailAddress(db.DefaultContext, user, "primary-13@example.com")) + assert.NoError(t, ReplacePrimaryEmailAddress(t.Context(), user, "primary-13@example.com")) - primary, err = user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) + primary, err = user_model.GetPrimaryEmailAddressOfUser(t.Context(), user.ID) assert.NoError(t, err) assert.Equal(t, "primary-13@example.com", primary.Email) assert.Equal(t, user.Email, primary.Email) - emails, err = user_model.GetEmailAddresses(db.DefaultContext, user.ID) + emails, err = user_model.GetEmailAddresses(t.Context(), user.ID) assert.NoError(t, err) assert.Len(t, emails, 1) - assert.NoError(t, ReplacePrimaryEmailAddress(db.DefaultContext, user, "primary-13@example.com")) + assert.NoError(t, ReplacePrimaryEmailAddress(t.Context(), user, "primary-13@example.com")) }) t.Run("Organization", func(t *testing.T) { @@ -99,7 +98,7 @@ func TestReplacePrimaryEmailAddress(t *testing.T) { assert.Equal(t, "org3@example.com", org.Email) - assert.NoError(t, ReplacePrimaryEmailAddress(db.DefaultContext, org.AsUser(), "primary-org@example.com")) + assert.NoError(t, ReplacePrimaryEmailAddress(t.Context(), org.AsUser(), "primary-org@example.com")) assert.Equal(t, "primary-org@example.com", org.Email) }) @@ -110,13 +109,13 @@ func TestAddEmailAddresses(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.Error(t, AddEmailAddresses(db.DefaultContext, user, []string{" invalid email "})) + assert.Error(t, AddEmailAddresses(t.Context(), user, []string{" invalid email "})) emails := []string{"user1234@example.com", "user5678@example.com"} - assert.NoError(t, AddEmailAddresses(db.DefaultContext, user, emails)) + assert.NoError(t, AddEmailAddresses(t.Context(), user, emails)) - err := AddEmailAddresses(db.DefaultContext, user, emails) + err := AddEmailAddresses(t.Context(), user, emails) assert.Error(t, err) assert.True(t, user_model.IsErrEmailAlreadyUsed(err)) } @@ -128,16 +127,16 @@ func TestDeleteEmailAddresses(t *testing.T) { emails := []string{"user2-2@example.com"} - err := DeleteEmailAddresses(db.DefaultContext, user, emails) + err := DeleteEmailAddresses(t.Context(), user, emails) assert.NoError(t, err) - err = DeleteEmailAddresses(db.DefaultContext, user, emails) + err = DeleteEmailAddresses(t.Context(), user, emails) assert.Error(t, err) assert.True(t, user_model.IsErrEmailAddressNotExist(err)) emails = []string{"user2@example.com"} - err = DeleteEmailAddresses(db.DefaultContext, user, emails) + err = DeleteEmailAddresses(t.Context(), user, emails) assert.Error(t, err) assert.True(t, user_model.IsErrPrimaryEmailCannotDelete(err)) } diff --git a/services/user/update_test.go b/services/user/update_test.go index 27513e8040..b81ac95783 100644 --- a/services/user/update_test.go +++ b/services/user/update_test.go @@ -6,7 +6,6 @@ package user import ( "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" password_module "code.gitea.io/gitea/modules/auth/password" @@ -21,11 +20,11 @@ func TestUpdateUser(t *testing.T) { admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - assert.Error(t, UpdateUser(db.DefaultContext, admin, &UpdateOptions{ + assert.Error(t, UpdateUser(t.Context(), admin, &UpdateOptions{ IsAdmin: UpdateOptionFieldFromValue(false), })) - assert.NoError(t, UpdateUser(db.DefaultContext, admin, &UpdateOptions{ + assert.NoError(t, UpdateUser(t.Context(), admin, &UpdateOptions{ IsAdmin: UpdateOptionFieldFromSync(false), })) @@ -52,7 +51,7 @@ func TestUpdateUser(t *testing.T) { EmailNotificationsPreference: optional.Some("disabled"), SetLastLogin: true, } - assert.NoError(t, UpdateUser(db.DefaultContext, user, opts)) + assert.NoError(t, UpdateUser(t.Context(), user, opts)) assert.Equal(t, opts.KeepEmailPrivate.Value(), user.KeepEmailPrivate) assert.Equal(t, opts.FullName.Value(), user.FullName) @@ -100,12 +99,12 @@ func TestUpdateAuth(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 28}) userCopy := *user - assert.NoError(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ + assert.NoError(t, UpdateAuth(t.Context(), user, &UpdateAuthOptions{ LoginName: optional.Some("new-login"), })) assert.Equal(t, "new-login", user.LoginName) - assert.NoError(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ + assert.NoError(t, UpdateAuth(t.Context(), user, &UpdateAuthOptions{ Password: optional.Some("%$DRZUVB576tfzgu"), MustChangePassword: optional.Some(true), })) @@ -113,12 +112,12 @@ func TestUpdateAuth(t *testing.T) { assert.NotEqual(t, userCopy.Passwd, user.Passwd) assert.NotEqual(t, userCopy.Salt, user.Salt) - assert.NoError(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ + assert.NoError(t, UpdateAuth(t.Context(), user, &UpdateAuthOptions{ ProhibitLogin: optional.Some(true), })) assert.True(t, user.ProhibitLogin) - assert.ErrorIs(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ + assert.ErrorIs(t, UpdateAuth(t.Context(), user, &UpdateAuthOptions{ Password: optional.Some("aaaa"), }), password_module.ErrMinLength) } diff --git a/services/user/user_test.go b/services/user/user_test.go index 28a0df8628..48852b4cb9 100644 --- a/services/user/user_test.go +++ b/services/user/user_test.go @@ -32,24 +32,24 @@ func TestDeleteUser(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID}) ownedRepos := make([]*repo_model.Repository, 0, 10) - assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&ownedRepos, &repo_model.Repository{OwnerID: userID})) + assert.NoError(t, db.GetEngine(t.Context()).Find(&ownedRepos, &repo_model.Repository{OwnerID: userID})) if len(ownedRepos) > 0 { - err := DeleteUser(db.DefaultContext, user, false) + err := DeleteUser(t.Context(), user, false) assert.Error(t, err) assert.True(t, repo_model.IsErrUserOwnRepos(err)) return } orgUsers := make([]*organization.OrgUser, 0, 10) - assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&orgUsers, &organization.OrgUser{UID: userID})) + assert.NoError(t, db.GetEngine(t.Context()).Find(&orgUsers, &organization.OrgUser{UID: userID})) for _, orgUser := range orgUsers { org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: orgUser.OrgID}) - if err := org_service.RemoveOrgUser(db.DefaultContext, org, user); err != nil { + if err := org_service.RemoveOrgUser(t.Context(), org, user); err != nil { assert.True(t, organization.IsErrLastOrgOwner(err)) return } } - assert.NoError(t, DeleteUser(db.DefaultContext, user, false)) + assert.NoError(t, DeleteUser(t.Context(), user, false)) unittest.AssertNotExistsBean(t, &user_model.User{ID: userID}) unittest.CheckConsistencyFor(t, &user_model.User{}, &repo_model.Repository{}) } @@ -59,7 +59,7 @@ func TestDeleteUser(t *testing.T) { test(11) org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) - assert.Error(t, DeleteUser(db.DefaultContext, org, false)) + assert.Error(t, DeleteUser(t.Context(), org, false)) } func TestPurgeUser(t *testing.T) { @@ -67,7 +67,7 @@ func TestPurgeUser(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID}) - err := DeleteUser(db.DefaultContext, user, true) + err := DeleteUser(t.Context(), user, true) assert.NoError(t, err) unittest.AssertNotExistsBean(t, &user_model.User{ID: userID}) @@ -79,7 +79,7 @@ func TestPurgeUser(t *testing.T) { test(11) org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) - assert.Error(t, DeleteUser(db.DefaultContext, org, false)) + assert.Error(t, DeleteUser(t.Context(), org, false)) } func TestCreateUser(t *testing.T) { @@ -92,9 +92,9 @@ func TestCreateUser(t *testing.T) { MustChangePassword: false, } - assert.NoError(t, user_model.CreateUser(db.DefaultContext, user, &user_model.Meta{})) + assert.NoError(t, user_model.CreateUser(t.Context(), user, &user_model.Meta{})) - assert.NoError(t, DeleteUser(db.DefaultContext, user, false)) + assert.NoError(t, DeleteUser(t.Context(), user, false)) } func TestRenameUser(t *testing.T) { @@ -106,18 +106,18 @@ func TestRenameUser(t *testing.T) { Type: user_model.UserTypeIndividual, LoginType: auth.OAuth2, } - assert.ErrorIs(t, RenameUser(db.DefaultContext, u, "user_rename"), user_model.ErrUserIsNotLocal{}) + assert.ErrorIs(t, RenameUser(t.Context(), u, "user_rename"), user_model.ErrUserIsNotLocal{}) }) t.Run("Same username", func(t *testing.T) { - assert.NoError(t, RenameUser(db.DefaultContext, user, user.Name)) + assert.NoError(t, RenameUser(t.Context(), user, user.Name)) }) t.Run("Non usable username", func(t *testing.T) { usernames := []string{"--diff", ".well-known", "gitea-actions", "aaa.atom", "aa.png"} for _, username := range usernames { assert.Error(t, user_model.IsUsableUsername(username), "non-usable username: %s", username) - assert.Error(t, RenameUser(db.DefaultContext, user, username), "non-usable username: %s", username) + assert.Error(t, RenameUser(t.Context(), user, username), "non-usable username: %s", username) } }) @@ -126,7 +126,7 @@ func TestRenameUser(t *testing.T) { unittest.AssertNotExistsBean(t, &user_model.User{ID: user.ID, Name: caps}) unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID, OwnerName: user.Name}) - assert.NoError(t, RenameUser(db.DefaultContext, user, caps)) + assert.NoError(t, RenameUser(t.Context(), user, caps)) unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: user.ID, Name: caps}) unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID, OwnerName: caps}) @@ -135,20 +135,20 @@ func TestRenameUser(t *testing.T) { t.Run("Already exists", func(t *testing.T) { existUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - assert.ErrorIs(t, RenameUser(db.DefaultContext, user, existUser.Name), user_model.ErrUserAlreadyExist{Name: existUser.Name}) - assert.ErrorIs(t, RenameUser(db.DefaultContext, user, existUser.LowerName), user_model.ErrUserAlreadyExist{Name: existUser.LowerName}) + assert.ErrorIs(t, RenameUser(t.Context(), user, existUser.Name), user_model.ErrUserAlreadyExist{Name: existUser.Name}) + assert.ErrorIs(t, RenameUser(t.Context(), user, existUser.LowerName), user_model.ErrUserAlreadyExist{Name: existUser.LowerName}) newUsername := fmt.Sprintf("uSEr%d", existUser.ID) - assert.ErrorIs(t, RenameUser(db.DefaultContext, user, newUsername), user_model.ErrUserAlreadyExist{Name: newUsername}) + assert.ErrorIs(t, RenameUser(t.Context(), user, newUsername), user_model.ErrUserAlreadyExist{Name: newUsername}) }) t.Run("Normal", func(t *testing.T) { oldUsername := user.Name newUsername := "User_Rename" - assert.NoError(t, RenameUser(db.DefaultContext, user, newUsername)) + assert.NoError(t, RenameUser(t.Context(), user, newUsername)) unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: user.ID, Name: newUsername, LowerName: strings.ToLower(newUsername)}) - redirectUID, err := user_model.LookupUserRedirect(db.DefaultContext, oldUsername) + redirectUID, err := user_model.LookupUserRedirect(t.Context(), oldUsername) assert.NoError(t, err) assert.Equal(t, user.ID, redirectUID) @@ -175,24 +175,24 @@ func TestCreateUser_Issue5882(t *testing.T) { for _, v := range tt { setting.Admin.DisableRegularOrgCreation = v.disableOrgCreation - assert.NoError(t, user_model.CreateUser(db.DefaultContext, v.user, &user_model.Meta{})) + assert.NoError(t, user_model.CreateUser(t.Context(), v.user, &user_model.Meta{})) - u, err := user_model.GetUserByEmail(db.DefaultContext, v.user.Email) + u, err := user_model.GetUserByEmail(t.Context(), v.user.Email) assert.NoError(t, err) assert.Equal(t, !u.AllowCreateOrganization, v.disableOrgCreation) - assert.NoError(t, DeleteUser(db.DefaultContext, v.user, false)) + assert.NoError(t, DeleteUser(t.Context(), v.user, false)) } } func TestDeleteInactiveUsers(t *testing.T) { addUser := func(name, email string, createdUnix timeutil.TimeStamp, active bool) { inactiveUser := &user_model.User{Name: name, LowerName: strings.ToLower(name), Email: email, CreatedUnix: createdUnix, IsActive: active} - _, err := db.GetEngine(db.DefaultContext).NoAutoTime().Insert(inactiveUser) + _, err := db.GetEngine(t.Context()).NoAutoTime().Insert(inactiveUser) assert.NoError(t, err) inactiveUserEmail := &user_model.EmailAddress{UID: inactiveUser.ID, IsPrimary: true, Email: email, LowerEmail: strings.ToLower(email), IsActivated: active} - err = db.Insert(db.DefaultContext, inactiveUserEmail) + err = db.Insert(t.Context(), inactiveUserEmail) assert.NoError(t, err) } addUser("user-inactive-10", "user-inactive-10@test.com", timeutil.TimeStampNow().Add(-600), false) @@ -201,7 +201,7 @@ func TestDeleteInactiveUsers(t *testing.T) { addUser("user-active-5", "user-active-5@test.com", timeutil.TimeStampNow().Add(-300), true) unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user-inactive-10"}) unittest.AssertExistsAndLoadBean(t, &user_model.EmailAddress{Email: "user-inactive-10@test.com"}) - assert.NoError(t, DeleteInactiveUsers(db.DefaultContext, 8*time.Minute)) + assert.NoError(t, DeleteInactiveUsers(t.Context(), 8*time.Minute)) unittest.AssertNotExistsBean(t, &user_model.User{Name: "user-inactive-10"}) unittest.AssertNotExistsBean(t, &user_model.EmailAddress{Email: "user-inactive-10@test.com"}) unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user-inactive-5"}) diff --git a/services/webhook/deliver_test.go b/services/webhook/deliver_test.go index 1d32d7b772..efbef1fc89 100644 --- a/services/webhook/deliver_test.go +++ b/services/webhook/deliver_test.go @@ -12,7 +12,6 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" webhook_model "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/hostmatcher" @@ -105,7 +104,7 @@ func TestWebhookDeliverAuthorizationHeader(t *testing.T) { } err := hook.SetHeaderAuthorization("Bearer s3cr3t-t0ken") assert.NoError(t, err) - assert.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) + assert.NoError(t, webhook_model.CreateWebhook(t.Context(), hook)) hookTask := &webhook_model.HookTask{ HookID: hook.ID, @@ -113,7 +112,7 @@ func TestWebhookDeliverAuthorizationHeader(t *testing.T) { PayloadVersion: 2, } - hookTask, err = webhook_model.CreateHookTask(db.DefaultContext, hookTask) + hookTask, err = webhook_model.CreateHookTask(t.Context(), hookTask) assert.NoError(t, err) assert.NotNil(t, hookTask) @@ -170,7 +169,7 @@ func TestWebhookDeliverHookTask(t *testing.T) { ContentType: webhook_model.ContentTypeJSON, Meta: `{"message_type":0}`, // text } - assert.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) + assert.NoError(t, webhook_model.CreateWebhook(t.Context(), hook)) t.Run("Version 1", func(t *testing.T) { hookTask := &webhook_model.HookTask{ @@ -180,7 +179,7 @@ func TestWebhookDeliverHookTask(t *testing.T) { PayloadVersion: 1, } - hookTask, err := webhook_model.CreateHookTask(db.DefaultContext, hookTask) + hookTask, err := webhook_model.CreateHookTask(t.Context(), hookTask) assert.NoError(t, err) assert.NotNil(t, hookTask) @@ -206,7 +205,7 @@ func TestWebhookDeliverHookTask(t *testing.T) { PayloadVersion: 2, } - hookTask, err = webhook_model.CreateHookTask(db.DefaultContext, hookTask) + hookTask, err = webhook_model.CreateHookTask(t.Context(), hookTask) assert.NoError(t, err) assert.NotNil(t, hookTask) @@ -266,7 +265,7 @@ func TestWebhookDeliverSpecificTypes(t *testing.T) { URL: s.URL + "/" + typ, Meta: "{}", } - assert.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) + assert.NoError(t, webhook_model.CreateWebhook(t.Context(), hook)) hookTask := &webhook_model.HookTask{ HookID: hook.ID, @@ -275,7 +274,7 @@ func TestWebhookDeliverSpecificTypes(t *testing.T) { PayloadVersion: 2, } - hookTask, err := webhook_model.CreateHookTask(db.DefaultContext, hookTask) + hookTask, err := webhook_model.CreateHookTask(t.Context(), hookTask) assert.NoError(t, err) assert.NotNil(t, hookTask) diff --git a/services/webhook/webhook_test.go b/services/webhook/webhook_test.go index 5a805347e3..34bcfd3df9 100644 --- a/services/webhook/webhook_test.go +++ b/services/webhook/webhook_test.go @@ -6,7 +6,6 @@ package webhook 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" @@ -43,7 +42,7 @@ func TestPrepareWebhooks(t *testing.T) { for _, hookTask := range hookTasks { unittest.AssertNotExistsBean(t, hookTask) } - assert.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Commits: []*api.PayloadCommit{{}}})) + assert.NoError(t, PrepareWebhooks(t.Context(), EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Commits: []*api.PayloadCommit{{}}})) for _, hookTask := range hookTasks { unittest.AssertExistsAndLoadBean(t, hookTask) } @@ -60,7 +59,7 @@ func TestPrepareWebhooksBranchFilterMatch(t *testing.T) { unittest.AssertNotExistsBean(t, hookTask) } // this test also ensures that * doesn't handle / in any special way (like shell would) - assert.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Ref: "refs/heads/feature/7791", Commits: []*api.PayloadCommit{{}}})) + assert.NoError(t, PrepareWebhooks(t.Context(), EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Ref: "refs/heads/feature/7791", Commits: []*api.PayloadCommit{{}}})) for _, hookTask := range hookTasks { unittest.AssertExistsAndLoadBean(t, hookTask) } @@ -76,7 +75,7 @@ func TestPrepareWebhooksBranchFilterNoMatch(t *testing.T) { for _, hookTask := range hookTasks { unittest.AssertNotExistsBean(t, hookTask) } - assert.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Ref: "refs/heads/fix_weird_bug"})) + assert.NoError(t, PrepareWebhooks(t.Context(), EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Ref: "refs/heads/fix_weird_bug"})) for _, hookTask := range hookTasks { unittest.AssertNotExistsBean(t, hookTask) @@ -88,6 +87,6 @@ func TestWebhookUserMail(t *testing.T) { defer test.MockVariableValue(&setting.Service.NoReplyAddress, "no-reply.com")() user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - assert.Equal(t, user.GetPlaceholderEmail(), convert.ToUser(db.DefaultContext, user, nil).Email) - assert.Equal(t, user.Email, convert.ToUser(db.DefaultContext, user, user).Email) + assert.Equal(t, user.GetPlaceholderEmail(), convert.ToUser(t.Context(), user, nil).Email) + assert.Equal(t, user.Email, convert.ToUser(t.Context(), user, user).Email) } diff --git a/tests/integration/actions_trigger_test.go b/tests/integration/actions_trigger_test.go index 1fb4b2b1aa..3edb6017b4 100644 --- a/tests/integration/actions_trigger_test.go +++ b/tests/integration/actions_trigger_test.go @@ -47,7 +47,7 @@ func TestPullRequestTargetEvent(t *testing.T) { user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // owner of the forked repo // create the base repo - baseRepo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + baseRepo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "repo-pull-request-target", Description: "test pull-request-target event", AutoInit: true, @@ -226,7 +226,7 @@ func TestSkipCI(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // create the repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "skip-ci", Description: "test skip ci functionality", AutoInit: true, @@ -355,7 +355,7 @@ func TestCreateDeleteRefEvent(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // create the repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "create-delete-ref-event", Description: "test create delete ref ci event", AutoInit: true, @@ -408,11 +408,11 @@ jobs: gitRepo, err := gitrepo.OpenRepository(t.Context(), repo) assert.NoError(t, err) defer gitRepo.Close() - branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch) + branch, err := git_model.GetBranch(t.Context(), repo.ID, repo.DefaultBranch) assert.NoError(t, err) // create a branch - err = repo_service.CreateNewBranchFromCommit(db.DefaultContext, user2, repo, gitRepo, branch.CommitID, "test-create-branch") + err = repo_service.CreateNewBranchFromCommit(t.Context(), user2, repo, gitRepo, branch.CommitID, "test-create-branch") assert.NoError(t, err) run := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ Title: "add workflow", @@ -425,7 +425,7 @@ jobs: assert.NotNil(t, run) // create a tag - err = release_service.CreateNewTag(db.DefaultContext, user2, repo, branch.CommitID, "test-create-tag", "test create tag event") + err = release_service.CreateNewTag(t.Context(), user2, repo, branch.CommitID, "test-create-tag", "test create tag event") assert.NoError(t, err) run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ Title: "add workflow", @@ -438,7 +438,7 @@ jobs: assert.NotNil(t, run) // delete the branch - err = repo_service.DeleteBranch(db.DefaultContext, user2, repo, gitRepo, "test-create-branch", nil) + err = repo_service.DeleteBranch(t.Context(), user2, repo, gitRepo, "test-create-branch", nil) assert.NoError(t, err) run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ Title: "add workflow", @@ -451,9 +451,9 @@ jobs: assert.NotNil(t, run) // delete the tag - tag, err := repo_model.GetRelease(db.DefaultContext, repo.ID, "test-create-tag") + tag, err := repo_model.GetRelease(t.Context(), repo.ID, "test-create-tag") assert.NoError(t, err) - err = release_service.DeleteReleaseByID(db.DefaultContext, repo, tag, user2, true) + err = release_service.DeleteReleaseByID(t.Context(), repo, tag, user2, true) assert.NoError(t, err) run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ Title: "add workflow", @@ -473,7 +473,7 @@ func TestPullRequestCommitStatusEvent(t *testing.T) { user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // contributor of the repo // create a repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "repo-pull-request", Description: "test pull-request event", AutoInit: true, @@ -553,35 +553,35 @@ jobs: Type: issues_model.PullRequestGitea, } prOpts := &pull_service.NewPullRequestOptions{Repo: repo, Issue: pullIssue, PullRequest: pullRequest} - err = pull_service.NewPullRequest(db.DefaultContext, prOpts) + err = pull_service.NewPullRequest(t.Context(), prOpts) assert.NoError(t, err) // opened checkCommitStatusAndInsertFakeStatus(t, repo, sha) // edited - err = issue_service.ChangeContent(db.DefaultContext, pullIssue, user2, "test", 0) + err = issue_service.ChangeContent(t.Context(), pullIssue, user2, "test", 0) assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) // closed - err = issue_service.CloseIssue(db.DefaultContext, pullIssue, user2, "") + err = issue_service.CloseIssue(t.Context(), pullIssue, user2, "") assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) // reopened - err = issue_service.ReopenIssue(db.DefaultContext, pullIssue, user2, "") + err = issue_service.ReopenIssue(t.Context(), pullIssue, user2, "") assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) // assign - removed, _, err := issue_service.ToggleAssigneeWithNotify(db.DefaultContext, pullIssue, user2, user4.ID) + removed, _, err := issue_service.ToggleAssigneeWithNotify(t.Context(), pullIssue, user2, user4.ID) assert.False(t, removed) assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) // unassign - removed, _, err = issue_service.ToggleAssigneeWithNotify(db.DefaultContext, pullIssue, user2, user4.ID) + removed, _, err = issue_service.ToggleAssigneeWithNotify(t.Context(), pullIssue, user2, user4.ID) assert.True(t, removed) assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) @@ -594,14 +594,14 @@ jobs: Description: "test", Color: "#e11d21", } - err = issues_model.NewLabel(db.DefaultContext, label) + err = issues_model.NewLabel(t.Context(), label) assert.NoError(t, err) - err = issue_service.AddLabel(db.DefaultContext, pullIssue, user2, label) + err = issue_service.AddLabel(t.Context(), pullIssue, user2, label) assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) // unlabeled - err = issue_service.RemoveLabel(db.DefaultContext, pullIssue, user2, label) + err = issue_service.RemoveLabel(t.Context(), pullIssue, user2, label) assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) @@ -634,7 +634,7 @@ jobs: assert.NotEmpty(t, addFileResp) sha = addFileResp.Commit.SHA assert.Eventually(t, func() bool { - latestCommitStatuses, err := git_model.GetLatestCommitStatus(db.DefaultContext, repo.ID, sha, db.ListOptionsAll) + latestCommitStatuses, err := git_model.GetLatestCommitStatus(t.Context(), repo.ID, sha, db.ListOptionsAll) assert.NoError(t, err) if len(latestCommitStatuses) == 0 { return false @@ -653,31 +653,31 @@ jobs: Content: "test", DeadlineUnix: timeutil.TimeStampNow(), } - err = issues_model.NewMilestone(db.DefaultContext, milestone) + err = issues_model.NewMilestone(t.Context(), milestone) assert.NoError(t, err) - err = issue_service.ChangeMilestoneAssign(db.DefaultContext, pullIssue, user2, milestone.ID) + err = issue_service.ChangeMilestoneAssign(t.Context(), pullIssue, user2, milestone.ID) assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) // demilestoned - err = issue_service.ChangeMilestoneAssign(db.DefaultContext, pullIssue, user2, milestone.ID) + err = issue_service.ChangeMilestoneAssign(t.Context(), pullIssue, user2, milestone.ID) assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) // review_requested - _, err = issue_service.ReviewRequest(db.DefaultContext, pullIssue, user2, nil, user4, true) + _, err = issue_service.ReviewRequest(t.Context(), pullIssue, user2, nil, user4, true) assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) // review_request_removed - _, err = issue_service.ReviewRequest(db.DefaultContext, pullIssue, user2, nil, user4, false) + _, err = issue_service.ReviewRequest(t.Context(), pullIssue, user2, nil, user4, false) assert.NoError(t, err) checkCommitStatusAndInsertFakeStatus(t, repo, sha) }) } func checkCommitStatusAndInsertFakeStatus(t *testing.T, repo *repo_model.Repository, sha string) { - latestCommitStatuses, err := git_model.GetLatestCommitStatus(db.DefaultContext, repo.ID, sha, db.ListOptionsAll) + latestCommitStatuses, err := git_model.GetLatestCommitStatus(t.Context(), repo.ID, sha, db.ListOptionsAll) assert.NoError(t, err) assert.Len(t, latestCommitStatuses, 1) assert.Equal(t, commitstatus.CommitStatusPending, latestCommitStatuses[0].State) @@ -686,7 +686,7 @@ func checkCommitStatusAndInsertFakeStatus(t *testing.T, repo *repo_model.Reposit } func insertFakeStatus(t *testing.T, repo *repo_model.Repository, sha, targetURL, context string) { - err := commitstatus_service.CreateCommitStatus(db.DefaultContext, repo, user_model.NewActionsUser(), sha, &git_model.CommitStatus{ + err := commitstatus_service.CreateCommitStatus(t.Context(), repo, user_model.NewActionsUser(), sha, &git_model.CommitStatus{ State: commitstatus.CommitStatusSuccess, TargetURL: targetURL, Context: context, @@ -701,7 +701,7 @@ func TestWorkflowDispatchPublicApi(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) // create the repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "workflow-dispatch-event", Description: "test workflow-dispatch ci event", AutoInit: true, @@ -754,7 +754,7 @@ jobs: gitRepo, err := gitrepo.OpenRepository(t.Context(), repo) assert.NoError(t, err) defer gitRepo.Close() - branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch) + branch, err := git_model.GetBranch(t.Context(), repo.ID, repo.DefaultBranch) assert.NoError(t, err) values := url.Values{} values.Set("ref", "main") @@ -781,7 +781,7 @@ func TestWorkflowDispatchPublicApiWithInputs(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) // create the repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "workflow-dispatch-event", Description: "test workflow-dispatch ci event", AutoInit: true, @@ -834,7 +834,7 @@ jobs: gitRepo, err := gitrepo.OpenRepository(t.Context(), repo) assert.NoError(t, err) defer gitRepo.Close() - branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch) + branch, err := git_model.GetBranch(t.Context(), repo.ID, repo.DefaultBranch) assert.NoError(t, err) values := url.Values{} values.Set("ref", "main") @@ -872,7 +872,7 @@ func TestWorkflowDispatchPublicApiJSON(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) // create the repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "workflow-dispatch-event", Description: "test workflow-dispatch ci event", AutoInit: true, @@ -925,7 +925,7 @@ jobs: gitRepo, err := gitrepo.OpenRepository(t.Context(), repo) assert.NoError(t, err) defer gitRepo.Close() - branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch) + branch, err := git_model.GetBranch(t.Context(), repo.ID, repo.DefaultBranch) assert.NoError(t, err) inputs := &api.CreateActionWorkflowDispatch{ Ref: "main", @@ -958,7 +958,7 @@ func TestWorkflowDispatchPublicApiWithInputsJSON(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) // create the repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "workflow-dispatch-event", Description: "test workflow-dispatch ci event", AutoInit: true, @@ -1011,7 +1011,7 @@ jobs: gitRepo, err := gitrepo.OpenRepository(t.Context(), repo) assert.NoError(t, err) defer gitRepo.Close() - branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch) + branch, err := git_model.GetBranch(t.Context(), repo.ID, repo.DefaultBranch) assert.NoError(t, err) inputs := &api.CreateActionWorkflowDispatch{ Ref: "main", @@ -1052,7 +1052,7 @@ func TestWorkflowDispatchPublicApiWithInputsNonDefaultBranchJSON(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) // create the repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "workflow-dispatch-event", Description: "test workflow-dispatch ci event", AutoInit: true, @@ -1183,7 +1183,7 @@ func TestWorkflowApi(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) // create the repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "workflow-api", Description: "test workflow apis", AutoInit: true, @@ -1339,7 +1339,7 @@ jobs: gitRepo, err := gitrepo.OpenRepository(t.Context(), repo) assert.NoError(t, err) defer gitRepo.Close() - branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch) + branch, err := git_model.GetBranch(t.Context(), repo.ID, repo.DefaultBranch) assert.NoError(t, err) inputs = &api.CreateActionWorkflowDispatch{ Ref: "main", @@ -1456,7 +1456,7 @@ func TestActionRunNameWithContextVariables(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // create the repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "action-run-name-with-variables", Description: "test action run name", AutoInit: true, @@ -1510,11 +1510,11 @@ jobs: gitRepo, err := gitrepo.OpenRepository(t.Context(), repo) assert.NoError(t, err) defer gitRepo.Close() - branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch) + branch, err := git_model.GetBranch(t.Context(), repo.ID, repo.DefaultBranch) assert.NoError(t, err) // create a branch - err = repo_service.CreateNewBranchFromCommit(db.DefaultContext, user2, repo, gitRepo, branch.CommitID, "test-action-run-name-with-variables") + err = repo_service.CreateNewBranchFromCommit(t.Context(), user2, repo, gitRepo, branch.CommitID, "test-action-run-name-with-variables") assert.NoError(t, err) run := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ Title: user2.LoginName + " is running this workflow", @@ -1533,7 +1533,7 @@ func TestActionRunName(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // create the repo - repo, err := repo_service.CreateRepository(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "action-run-name", Description: "test action run-name", AutoInit: true, @@ -1587,11 +1587,11 @@ jobs: gitRepo, err := gitrepo.OpenRepository(t.Context(), repo) assert.NoError(t, err) defer gitRepo.Close() - branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch) + branch, err := git_model.GetBranch(t.Context(), repo.ID, repo.DefaultBranch) assert.NoError(t, err) // create a branch - err = repo_service.CreateNewBranchFromCommit(db.DefaultContext, user2, repo, gitRepo, branch.CommitID, "test-action-run-name") + err = repo_service.CreateNewBranchFromCommit(t.Context(), user2, repo, gitRepo, branch.CommitID, "test-action-run-name") assert.NoError(t, err) run := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ Title: "run name without variables", diff --git a/tests/integration/api_activitypub_person_test.go b/tests/integration/api_activitypub_person_test.go index 9bb1f2736e..6dd219ab2e 100644 --- a/tests/integration/api_activitypub_person_test.go +++ b/tests/integration/api_activitypub_person_test.go @@ -9,7 +9,6 @@ import ( "net/http/httptest" "testing" - "code.gitea.io/gitea/models/db" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/activitypub" "code.gitea.io/gitea/modules/setting" @@ -73,7 +72,7 @@ func TestActivityPubPerson(t *testing.T) { user1, err := user_model.GetUserByName(ctx, username1) assert.NoError(t, err) user1url := srv.URL + "/api/v1/activitypub/user-id/1#main-key" - c, err := activitypub.NewClient(db.DefaultContext, user1, user1url) + c, err := activitypub.NewClient(t.Context(), user1, user1url) assert.NoError(t, err) user2inboxurl := srv.URL + "/api/v1/activitypub/user-id/2/inbox" diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index 16e1f2812e..7d6b872349 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -299,14 +299,14 @@ func TestAPIBranchProtection(t *testing.T) { func TestAPICreateBranchWithSyncBranches(t *testing.T) { defer tests.PrepareTestEnv(t)() - branches, err := db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ + branches, err := db.Find[git_model.Branch](t.Context(), git_model.FindBranchOptions{ RepoID: 1, }) assert.NoError(t, err) assert.Len(t, branches, 6) // make a broke repository with no branch on database - _, err = db.DeleteByBean(db.DefaultContext, git_model.Branch{RepoID: 1}) + _, err = db.DeleteByBean(t.Context(), git_model.Branch{RepoID: 1}) assert.NoError(t, err) onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { @@ -316,13 +316,13 @@ func TestAPICreateBranchWithSyncBranches(t *testing.T) { testAPICreateBranch(t, ctx.Session, "user2", "repo1", "", "new_branch", http.StatusCreated) }) - branches, err = db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ + branches, err = db.Find[git_model.Branch](t.Context(), git_model.FindBranchOptions{ RepoID: 1, }) assert.NoError(t, err) assert.Len(t, branches, 7) - branches, err = db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ + branches, err = db.Find[git_model.Branch](t.Context(), git_model.FindBranchOptions{ RepoID: 1, Keyword: "new_branch", }) diff --git a/tests/integration/api_comment_attachment_test.go b/tests/integration/api_comment_attachment_test.go index 623467938a..cddae27d94 100644 --- a/tests/integration/api_comment_attachment_test.go +++ b/tests/integration/api_comment_attachment_test.go @@ -12,7 +12,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -28,8 +27,8 @@ func TestAPIGetCommentAttachment(t *testing.T) { defer tests.PrepareTestEnv(t)() comment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 2}) - assert.NoError(t, comment.LoadIssue(db.DefaultContext)) - assert.NoError(t, comment.LoadAttachments(db.DefaultContext)) + assert.NoError(t, comment.LoadIssue(t.Context())) + assert.NoError(t, comment.LoadAttachments(t.Context())) attachment := unittest.AssertExistsAndLoadBean(t, &repo_model.Attachment{ID: comment.Attachments[0].ID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: comment.Issue.RepoID}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index 9842c358f6..c7f9c85f7c 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -10,7 +10,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -140,7 +139,7 @@ func TestAPIGetComment(t *testing.T) { defer tests.PrepareTestEnv(t)() comment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 2}) - assert.NoError(t, comment.LoadIssue(db.DefaultContext)) + assert.NoError(t, comment.LoadIssue(t.Context())) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: comment.Issue.RepoID}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) @@ -154,8 +153,8 @@ func TestAPIGetComment(t *testing.T) { var apiComment api.Comment DecodeJSON(t, resp, &apiComment) - assert.NoError(t, comment.LoadPoster(db.DefaultContext)) - expect := convert.ToAPIComment(db.DefaultContext, repo, comment) + assert.NoError(t, comment.LoadPoster(t.Context())) + expect := convert.ToAPIComment(t.Context(), repo, comment) assert.Equal(t, expect.ID, apiComment.ID) assert.Equal(t, expect.Poster.FullName, apiComment.Poster.FullName) @@ -175,7 +174,7 @@ func TestAPIGetSystemUserComment(t *testing.T) { user_model.NewActionsUser(), } { body := "Hello " + systemUser.Name - 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: systemUser, Repo: repo, @@ -192,7 +191,7 @@ func TestAPIGetSystemUserComment(t *testing.T) { if assert.NotNil(t, apiComment.Poster) { if assert.Equal(t, systemUser.ID, apiComment.Poster.ID) { - assert.NoError(t, comment.LoadPoster(db.DefaultContext)) + assert.NoError(t, comment.LoadPoster(t.Context())) assert.Equal(t, systemUser.Name, apiComment.Poster.UserName) } } diff --git a/tests/integration/api_fork_test.go b/tests/integration/api_fork_test.go index 2837c3b93e..bd2d38ef4f 100644 --- a/tests/integration/api_fork_test.go +++ b/tests/integration/api_fork_test.go @@ -8,7 +8,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" org_model "code.gitea.io/gitea/models/organization" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -36,9 +35,9 @@ func TestAPIForkListLimitedAndPrivateRepos(t *testing.T) { limitedOrg := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 22}) assert.Equal(t, api.VisibleTypeLimited, limitedOrg.Visibility) - ownerTeam1, err := org_model.OrgFromUser(limitedOrg).GetOwnerTeam(db.DefaultContext) + ownerTeam1, err := org_model.OrgFromUser(limitedOrg).GetOwnerTeam(t.Context()) assert.NoError(t, err) - assert.NoError(t, org_service.AddTeamMember(db.DefaultContext, ownerTeam1, user1)) + assert.NoError(t, org_service.AddTeamMember(t.Context(), ownerTeam1, user1)) user1Token := getTokenForLoggedInUser(t, user1Sess, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteOrganization) req := NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/forks", &api.CreateForkOption{ Organization: &limitedOrg.Name, @@ -51,9 +50,9 @@ func TestAPIForkListLimitedAndPrivateRepos(t *testing.T) { privateOrg := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 23}) assert.Equal(t, api.VisibleTypePrivate, privateOrg.Visibility) - ownerTeam2, err := org_model.OrgFromUser(privateOrg).GetOwnerTeam(db.DefaultContext) + ownerTeam2, err := org_model.OrgFromUser(privateOrg).GetOwnerTeam(t.Context()) assert.NoError(t, err) - assert.NoError(t, org_service.AddTeamMember(db.DefaultContext, ownerTeam2, user4)) + assert.NoError(t, org_service.AddTeamMember(t.Context(), ownerTeam2, user4)) user4Token := getTokenForLoggedInUser(t, user4Sess, auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteOrganization) req = NewRequestWithJSON(t, "POST", "/api/v1/repos/user2/repo1/forks", &api.CreateForkOption{ Organization: &privateOrg.Name, @@ -85,7 +84,7 @@ func TestAPIForkListLimitedAndPrivateRepos(t *testing.T) { assert.Len(t, forks, 2) assert.Equal(t, "2", resp.Header().Get("X-Total-Count")) - assert.NoError(t, org_service.AddTeamMember(db.DefaultContext, ownerTeam2, user1)) + assert.NoError(t, org_service.AddTeamMember(t.Context(), ownerTeam2, user1)) req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/forks").AddTokenAuth(user1Token) resp = MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/api_issue_reaction_test.go b/tests/integration/api_issue_reaction_test.go index 17e9f7aed5..01588f9900 100644 --- a/tests/integration/api_issue_reaction_test.go +++ b/tests/integration/api_issue_reaction_test.go @@ -10,7 +10,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -26,7 +25,7 @@ func TestAPIIssuesReactions(t *testing.T) { defer tests.PrepareTestEnv(t)() 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}) session := loginUser(t, owner.Name) @@ -73,7 +72,7 @@ func TestAPIIssuesReactions(t *testing.T) { DecodeJSON(t, resp, &apiReactions) expectResponse := make(map[int]api.Reaction) expectResponse[0] = api.Reaction{ - User: convert.ToUser(db.DefaultContext, user2, user2), + User: convert.ToUser(t.Context(), user2, user2), Reaction: "eyes", Created: time.Unix(1573248003, 0), } @@ -90,9 +89,9 @@ func TestAPICommentReactions(t *testing.T) { defer tests.PrepareTestEnv(t)() comment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 2}) - _ = comment.LoadIssue(db.DefaultContext) + _ = comment.LoadIssue(t.Context()) issue := comment.Issue - _ = issue.LoadRepo(db.DefaultContext) + _ = issue.LoadRepo(t.Context()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) session := loginUser(t, owner.Name) @@ -153,12 +152,12 @@ func TestAPICommentReactions(t *testing.T) { DecodeJSON(t, resp, &apiReactions) expectResponse := make(map[int]api.Reaction) expectResponse[0] = api.Reaction{ - User: convert.ToUser(db.DefaultContext, user2, user2), + User: convert.ToUser(t.Context(), user2, user2), Reaction: "laugh", Created: time.Unix(1573248004, 0), } expectResponse[1] = api.Reaction{ - User: convert.ToUser(db.DefaultContext, user1, user1), + User: convert.ToUser(t.Context(), user1, user1), Reaction: "laugh", Created: time.Unix(1573248005, 0), } diff --git a/tests/integration/api_issue_stopwatch_test.go b/tests/integration/api_issue_stopwatch_test.go index 3606d9a228..1cf797f221 100644 --- a/tests/integration/api_issue_stopwatch_test.go +++ b/tests/integration/api_issue_stopwatch_test.go @@ -8,7 +8,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -48,7 +47,7 @@ func TestAPIStopStopWatches(t *testing.T) { defer tests.PrepareTestEnv(t)() issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) - _ = issue.LoadRepo(db.DefaultContext) + _ = issue.LoadRepo(t.Context()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -65,7 +64,7 @@ func TestAPICancelStopWatches(t *testing.T) { defer tests.PrepareTestEnv(t)() 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}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -82,7 +81,7 @@ func TestAPIStartStopWatches(t *testing.T) { defer tests.PrepareTestEnv(t)() issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) - _ = issue.LoadRepo(db.DefaultContext) + _ = issue.LoadRepo(t.Context()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) diff --git a/tests/integration/api_issue_subscription_test.go b/tests/integration/api_issue_subscription_test.go index 74ba171c01..3862a13894 100644 --- a/tests/integration/api_issue_subscription_test.go +++ b/tests/integration/api_issue_subscription_test.go @@ -9,7 +9,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -45,7 +44,7 @@ func TestAPIIssueSubscriptions(t *testing.T) { assert.Equal(t, isWatching, wi.Subscribed) assert.Equal(t, !isWatching, wi.Ignored) - assert.Equal(t, issue.APIURL(db.DefaultContext)+"/subscriptions", wi.URL) + assert.Equal(t, issue.APIURL(t.Context())+"/subscriptions", wi.URL) assert.EqualValues(t, issue.CreatedUnix, wi.CreatedAt.Unix()) assert.Equal(t, issueRepo.APIURL(), wi.RepositoryURL) } diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index 370c90a100..4f751032f8 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -13,7 +13,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -203,7 +202,7 @@ func TestAPIEditIssue(t *testing.T) { issueBefore := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 10}) repoBefore := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issueBefore.RepoID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) - assert.NoError(t, issueBefore.LoadAttributes(db.DefaultContext)) + assert.NoError(t, issueBefore.LoadAttributes(t.Context())) assert.Equal(t, int64(1019307200), int64(issueBefore.DeadlineUnix)) assert.Equal(t, api.StateOpen, issueBefore.State()) @@ -240,7 +239,7 @@ func TestAPIEditIssue(t *testing.T) { // check deleted user assert.Equal(t, int64(500), issueAfter.PosterID) - assert.NoError(t, issueAfter.LoadAttributes(db.DefaultContext)) + assert.NoError(t, issueAfter.LoadAttributes(t.Context())) assert.Equal(t, int64(-1), issueAfter.PosterID) assert.Equal(t, int64(-1), issueBefore.PosterID) assert.Equal(t, int64(-1), apiIssue.Poster.ID) diff --git a/tests/integration/api_issue_tracked_time_test.go b/tests/integration/api_issue_tracked_time_test.go index bd562b602e..7d6992c327 100644 --- a/tests/integration/api_issue_tracked_time_test.go +++ b/tests/integration/api_issue_tracked_time_test.go @@ -10,7 +10,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -25,7 +24,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) - assert.NoError(t, issue2.LoadRepo(db.DefaultContext)) + assert.NoError(t, issue2.LoadRepo(t.Context())) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) @@ -35,7 +34,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { resp := MakeRequest(t, req, http.StatusOK) var apiTimes api.TrackedTimeList DecodeJSON(t, resp, &apiTimes) - expect, err := issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: issue2.ID}) + expect, err := issues_model.GetTrackedTimes(t.Context(), &issues_model.FindTrackedTimesOptions{IssueID: issue2.ID}) assert.NoError(t, err) assert.Len(t, apiTimes, 3) @@ -45,7 +44,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { assert.Equal(t, issue2.ID, apiTimes[i].IssueID) assert.Equal(t, time.Created.Unix(), apiTimes[i].Created.Unix()) assert.Equal(t, time.Time, apiTimes[i].Time) - user, err := user_model.GetUserByID(db.DefaultContext, time.UserID) + user, err := user_model.GetUserByID(t.Context(), time.UserID) assert.NoError(t, err) assert.Equal(t, user.Name, apiTimes[i].UserName) } @@ -69,7 +68,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { time6 := unittest.AssertExistsAndLoadBean(t, &issues_model.TrackedTime{ID: 6}) issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) - assert.NoError(t, issue2.LoadRepo(db.DefaultContext)) + assert.NoError(t, issue2.LoadRepo(t.Context())) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user2.Name) @@ -88,7 +87,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { MakeRequest(t, req, http.StatusNotFound) // Reset time of user 2 on issue 2 - trackedSeconds, err := issues_model.GetTrackedSeconds(db.DefaultContext, issues_model.FindTrackedTimesOptions{IssueID: 2, UserID: 2}) + trackedSeconds, err := issues_model.GetTrackedSeconds(t.Context(), issues_model.FindTrackedTimesOptions{IssueID: 2, UserID: 2}) assert.NoError(t, err) assert.Equal(t, int64(3661), trackedSeconds) @@ -97,7 +96,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { MakeRequest(t, req, http.StatusNoContent) MakeRequest(t, req, http.StatusNotFound) - trackedSeconds, err = issues_model.GetTrackedSeconds(db.DefaultContext, issues_model.FindTrackedTimesOptions{IssueID: 2, UserID: 2}) + trackedSeconds, err = issues_model.GetTrackedSeconds(t.Context(), issues_model.FindTrackedTimesOptions{IssueID: 2, UserID: 2}) assert.NoError(t, err) assert.Equal(t, int64(0), trackedSeconds) } @@ -106,7 +105,7 @@ func TestAPIAddTrackedTimes(t *testing.T) { defer tests.PrepareTestEnv(t)() issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) - assert.NoError(t, issue2.LoadRepo(db.DefaultContext)) + assert.NoError(t, issue2.LoadRepo(t.Context())) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) diff --git a/tests/integration/api_notification_test.go b/tests/integration/api_notification_test.go index e6bc142476..591fb69dfe 100644 --- a/tests/integration/api_notification_test.go +++ b/tests/integration/api_notification_test.go @@ -10,7 +10,6 @@ import ( activities_model "code.gitea.io/gitea/models/activities" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -26,7 +25,7 @@ func TestAPINotification(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) - assert.NoError(t, thread5.LoadAttributes(db.DefaultContext)) + assert.NoError(t, thread5.LoadAttributes(t.Context())) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteNotification, auth_model.AccessTokenScopeWriteRepository) @@ -106,7 +105,7 @@ func TestAPINotification(t *testing.T) { assert.True(t, apiN.Unread) assert.Equal(t, "issue4", apiN.Subject.Title) assert.EqualValues(t, "Issue", apiN.Subject.Type) - assert.Equal(t, thread5.Issue.APIURL(db.DefaultContext), apiN.Subject.URL) + assert.Equal(t, thread5.Issue.APIURL(t.Context()), apiN.Subject.URL) assert.Equal(t, thread5.Repository.HTMLURL(), apiN.Repository.HTMLURL) MakeRequest(t, NewRequest(t, "GET", "/api/v1/notifications/new"), http.StatusUnauthorized) @@ -162,7 +161,7 @@ func TestAPINotificationPUT(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) - assert.NoError(t, thread5.LoadAttributes(db.DefaultContext)) + assert.NoError(t, thread5.LoadAttributes(t.Context())) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteNotification) diff --git a/tests/integration/api_org_test.go b/tests/integration/api_org_test.go index 6577bd1684..6b7826fbb8 100644 --- a/tests/integration/api_org_test.go +++ b/tests/integration/api_org_test.go @@ -10,7 +10,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" org_model "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/perm" unit_model "code.gitea.io/gitea/models/unit" @@ -64,7 +63,7 @@ func TestAPIOrgCreateRename(t *testing.T) { t.Run("CheckPermission", func(t *testing.T) { // Check owner team permission - ownerTeam, _ := org_model.GetOwnerTeam(db.DefaultContext, apiOrg.ID) + ownerTeam, _ := org_model.GetOwnerTeam(t.Context(), apiOrg.ID) for _, ut := range unit_model.AllRepoUnitTypes { up := perm.AccessModeOwner if ut == unit_model.TypeExternalTracker || ut == unit_model.TypeExternalWiki { diff --git a/tests/integration/api_packages_alpine_test.go b/tests/integration/api_packages_alpine_test.go index 228f497127..3395fad213 100644 --- a/tests/integration/api_packages_alpine_test.go +++ b/tests/integration/api_packages_alpine_test.go @@ -14,7 +14,6 @@ import ( "net/http" "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" @@ -121,18 +120,18 @@ AACAX/AKARNTyAAoAAA=` AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeAlpine) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeAlpine) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &alpine_module.VersionMetadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.NotEmpty(t, pfs) assert.Condition(t, func() bool { @@ -148,7 +147,7 @@ AACAX/AKARNTyAAoAAA=` assert.True(t, pf.IsLead) - pfps, err := packages.GetProperties(db.DefaultContext, packages.PropertyTypeFile, pf.ID) + pfps, err := packages.GetProperties(t.Context(), packages.PropertyTypeFile, pf.ID) assert.NoError(t, err) for _, pfp := range pfps { diff --git a/tests/integration/api_packages_arch_test.go b/tests/integration/api_packages_arch_test.go index e5778b4203..a0e21fcfc7 100644 --- a/tests/integration/api_packages_arch_test.go +++ b/tests/integration/api_packages_arch_test.go @@ -12,7 +12,6 @@ import ( "net/http" "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" @@ -146,18 +145,18 @@ license = MIT`) AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeArch) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeArch) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &arch_module.VersionMetadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.NotEmpty(t, pfs) assert.Condition(t, func() bool { @@ -173,7 +172,7 @@ license = MIT`) assert.True(t, pf.IsLead) - pfps, err := packages.GetProperties(db.DefaultContext, packages.PropertyTypeFile, pf.ID) + pfps, err := packages.GetProperties(t.Context(), packages.PropertyTypeFile, pf.ID) assert.NoError(t, err) for _, pfp := range pfps { diff --git a/tests/integration/api_packages_cargo_test.go b/tests/integration/api_packages_cargo_test.go index 8b5caa7ea7..d7a89e446d 100644 --- a/tests/integration/api_packages_cargo_test.go +++ b/tests/integration/api_packages_cargo_test.go @@ -12,7 +12,6 @@ import ( neturl "net/url" "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/packages" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -69,15 +68,15 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { return &buf } - err := cargo_service.InitializeIndexRepository(db.DefaultContext, user, user) + err := cargo_service.InitializeIndexRepository(t.Context(), user, user) assert.NoError(t, err) - repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, user.Name, cargo_service.IndexRepositoryName) + repo, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), user.Name, cargo_service.IndexRepositoryName) assert.NotNil(t, repo) assert.NoError(t, err) readGitContent := func(t *testing.T, path string) string { - gitRepo, err := gitrepo.OpenRepository(db.DefaultContext, repo) + gitRepo, err := gitrepo.OpenRepository(t.Context(), repo) assert.NoError(t, err) defer gitRepo.Close() @@ -179,24 +178,24 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { DecodeJSON(t, resp, &status) assert.True(t, status.OK) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeCargo) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeCargo) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &cargo_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s-%s.crate", packageName, packageVersion), pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.EqualValues(t, 4, pb.Size) @@ -236,7 +235,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { t.Run("Rebuild", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - err := cargo_service.RebuildIndex(db.DefaultContext, user, user) + err := cargo_service.RebuildIndex(t.Context(), user, user) assert.NoError(t, err) _ = readGitContent(t, cargo_service.BuildPackagePath(packageName)) @@ -279,11 +278,11 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeCargo, packageName, packageVersion) + pv, err := packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeCargo, packageName, packageVersion) assert.NoError(t, err) assert.EqualValues(t, 0, pv.DownloadCount) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pv.ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pv.ID) assert.NoError(t, err) assert.Len(t, pfs, 1) @@ -293,7 +292,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { assert.Equal(t, "test", resp.Body.String()) - pv, err = packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeCargo, packageName, packageVersion) + pv, err = packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeCargo, packageName, packageVersion) assert.NoError(t, err) assert.EqualValues(t, 1, pv.DownloadCount) }) diff --git a/tests/integration/api_packages_chef_test.go b/tests/integration/api_packages_chef_test.go index 8f2c2592e7..999e8cd7b2 100644 --- a/tests/integration/api_packages_chef_test.go +++ b/tests/integration/api_packages_chef_test.go @@ -25,7 +25,6 @@ import ( "testing" "time" - "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" @@ -83,7 +82,7 @@ kPuCu6vH9brvOuYo0q8hLVNkBeXcimRpsDjLhQYzEJjoMTbaiVGnjBky+PWNiofJ nwIDAQAB -----END PUBLIC KEY-----` - err := user_model.SetUserSetting(db.DefaultContext, user.ID, chef_module.SettingPublicPem, pubPem) + err := user_model.SetUserSetting(t.Context(), user.ID, chef_module.SettingPublicPem, pubPem) assert.NoError(t, err) t.Run("Authenticate", func(t *testing.T) { @@ -306,18 +305,18 @@ nwIDAQAB uploadPackage(t, packageVersion, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeChef) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeChef) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &chef_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, packageVersion+".tar.gz", pfs[0].Name) @@ -538,7 +537,7 @@ nwIDAQAB AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) - pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeChef, packageName, "1.0.2") + pv, err := packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeChef, packageName, "1.0.2") assert.Nil(t, pv) assert.Error(t, err) }) @@ -553,7 +552,7 @@ nwIDAQAB AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusOK) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeChef) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeChef) assert.NoError(t, err) assert.Empty(t, pvs) }) diff --git a/tests/integration/api_packages_composer_test.go b/tests/integration/api_packages_composer_test.go index 54f61d91d9..a11c2e7eab 100644 --- a/tests/integration/api_packages_composer_test.go +++ b/tests/integration/api_packages_composer_test.go @@ -11,7 +11,6 @@ import ( neturl "net/url" "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/packages" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -94,24 +93,24 @@ func TestPackageComposer(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeComposer) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeComposer) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &composer_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s-%s.%s.zip", vendorName, projectName, packageVersion), pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) @@ -124,12 +123,12 @@ func TestPackageComposer(t *testing.T) { t.Run("Download", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeComposer) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeComposer) assert.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(0), pvs[0].DownloadCount) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) @@ -139,7 +138,7 @@ func TestPackageComposer(t *testing.T) { assert.Equal(t, content, resp.Body.Bytes()) - pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeComposer) + pvs, err = packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeComposer) assert.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(1), pvs[0].DownloadCount) @@ -221,12 +220,12 @@ func TestPackageComposer(t *testing.T) { // Test package linked to repository repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - userPkgs, err := packages.GetPackagesByType(db.DefaultContext, user.ID, packages.TypeComposer) + userPkgs, err := packages.GetPackagesByType(t.Context(), user.ID, packages.TypeComposer) assert.NoError(t, err) assert.Len(t, userPkgs, 1) assert.EqualValues(t, 0, userPkgs[0].RepoID) - err = packages.SetRepositoryLink(db.DefaultContext, userPkgs[0].ID, repo1.ID) + err = packages.SetRepositoryLink(t.Context(), userPkgs[0].ID, repo1.ID) assert.NoError(t, err) req = NewRequest(t, "GET", fmt.Sprintf("%s/p2/%s/%s.json", url, vendorName, projectName)). diff --git a/tests/integration/api_packages_conan_test.go b/tests/integration/api_packages_conan_test.go index 4e83c998b8..2223b9bbac 100644 --- a/tests/integration/api_packages_conan_test.go +++ b/tests/integration/api_packages_conan_test.go @@ -12,7 +12,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/packages" conan_model "code.gitea.io/gitea/models/packages/conan" "code.gitea.io/gitea/models/unittest" @@ -321,11 +320,11 @@ func TestPackageConan(t *testing.T) { t.Run("Validate", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConan) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeConan) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.Equal(t, name, pd.Package.Name) @@ -339,12 +338,12 @@ func TestPackageConan(t *testing.T) { assert.Equal(t, conanDescription, metadata.Description) assert.Equal(t, []string{conanTopic}, metadata.Keywords) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 2) for _, pf := range pfs { - pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) + pb, err := packages.GetBlobByID(t.Context(), pf.BlobID) assert.NoError(t, err) if pf.Name == conanfileName { @@ -494,7 +493,7 @@ func TestPackageConan(t *testing.T) { for i, c := range cases { rref, _ := conan_module.NewRecipeReference(name, version1, user1, c.Channel, conan_module.DefaultRevision) - references, err := conan_model.GetPackageReferences(db.DefaultContext, user.ID, rref) + references, err := conan_model.GetPackageReferences(t.Context(), user.ID, rref) assert.NoError(t, err) assert.NotEmpty(t, references) @@ -508,7 +507,7 @@ func TestPackageConan(t *testing.T) { }).AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) - references, err = conan_model.GetPackageReferences(db.DefaultContext, user.ID, rref) + references, err = conan_model.GetPackageReferences(t.Context(), user.ID, rref) assert.NoError(t, err) assert.Empty(t, references, "case %d: should be empty", i) } @@ -526,7 +525,7 @@ func TestPackageConan(t *testing.T) { for i, c := range cases { rref, _ := conan_module.NewRecipeReference(name, version1, user1, c.Channel, conan_module.DefaultRevision) - revisions, err := conan_model.GetRecipeRevisions(db.DefaultContext, user.ID, rref) + revisions, err := conan_model.GetRecipeRevisions(t.Context(), user.ID, rref) assert.NoError(t, err) assert.NotEmpty(t, revisions) @@ -538,7 +537,7 @@ func TestPackageConan(t *testing.T) { AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) - revisions, err = conan_model.GetRecipeRevisions(db.DefaultContext, user.ID, rref) + revisions, err = conan_model.GetRecipeRevisions(t.Context(), user.ID, rref) assert.NoError(t, err) assert.Empty(t, revisions, "case %d: should be empty", i) } @@ -653,7 +652,7 @@ func TestPackageConan(t *testing.T) { t.Run("Validate", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConan) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeConan) assert.NoError(t, err) assert.Len(t, pvs, 3) }) @@ -794,12 +793,12 @@ func TestPackageConan(t *testing.T) { pref, _ := conan_module.NewPackageReference(rref, conanPackageReference, conan_module.DefaultRevision) checkPackageRevisionCount := func(count int) { - revisions, err := conan_model.GetPackageRevisions(db.DefaultContext, user.ID, pref) + revisions, err := conan_model.GetPackageRevisions(t.Context(), user.ID, pref) assert.NoError(t, err) assert.Len(t, revisions, count) } checkPackageReferenceCount := func(count int) { - references, err := conan_model.GetPackageReferences(db.DefaultContext, user.ID, rref) + references, err := conan_model.GetPackageReferences(t.Context(), user.ID, rref) assert.NoError(t, err) assert.Len(t, references, count) } @@ -847,7 +846,7 @@ func TestPackageConan(t *testing.T) { rref, _ := conan_module.NewRecipeReference(name, version1, user1, channel1, conan_module.DefaultRevision) checkRecipeRevisionCount := func(count int) { - revisions, err := conan_model.GetRecipeRevisions(db.DefaultContext, user.ID, rref) + revisions, err := conan_model.GetRecipeRevisions(t.Context(), user.ID, rref) assert.NoError(t, err) assert.Len(t, revisions, count) } diff --git a/tests/integration/api_packages_conda_test.go b/tests/integration/api_packages_conda_test.go index 32f55e5435..b69a8c9066 100644 --- a/tests/integration/api_packages_conda_test.go +++ b/tests/integration/api_packages_conda_test.go @@ -12,7 +12,6 @@ import ( "net/http" "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" @@ -74,11 +73,11 @@ func TestPackageConda(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConda) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeConda) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &conda_module.VersionMetadata{}, pd.Metadata) @@ -115,11 +114,11 @@ func TestPackageConda(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusConflict) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConda) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeConda) assert.NoError(t, err) assert.Len(t, pvs, 2) - pds, err := packages.GetPackageDescriptors(db.DefaultContext, pvs) + pds, err := packages.GetPackageDescriptors(t.Context(), pvs) assert.NoError(t, err) assert.Condition(t, func() bool { @@ -212,10 +211,10 @@ func TestPackageConda(t *testing.T) { t.Run(".tar.bz2", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeConda, packageName, packageVersion) + pv, err := packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeConda, packageName, packageVersion) assert.NoError(t, err) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv) + pd, err := packages.GetPackageDescriptor(t.Context(), pv) assert.NoError(t, err) req := NewRequest(t, "GET", root+"/noarch/repodata.json") @@ -243,10 +242,10 @@ func TestPackageConda(t *testing.T) { t.Run(".conda", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeConda, channel+"/"+packageName, packageVersion) + pv, err := packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeConda, channel+"/"+packageName, packageVersion) assert.NoError(t, err) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv) + pd, err := packages.GetPackageDescriptor(t.Context(), pv) assert.NoError(t, err) req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/noarch/repodata.json", root, channel)) diff --git a/tests/integration/api_packages_container_test.go b/tests/integration/api_packages_container_test.go index 204f099bbe..7e93cb47a2 100644 --- a/tests/integration/api_packages_container_test.go +++ b/tests/integration/api_packages_container_test.go @@ -16,7 +16,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -251,14 +250,14 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, fmt.Sprintf("/v2/%s/%s/blobs/%s", user.Name, image, blobDigest), resp.Header().Get("Location")) assert.Equal(t, blobDigest, resp.Header().Get("Docker-Content-Digest")) - pv, err := packages_model.GetInternalVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, container_module.UploadVersion) + pv, err := packages_model.GetInternalVersionByNameAndVersion(t.Context(), user.ID, packages_model.TypeContainer, image, container_module.UploadVersion) assert.NoError(t, err) - pfs, err := packages_model.GetFilesByVersionID(db.DefaultContext, pv.ID) + pfs, err := packages_model.GetFilesByVersionID(t.Context(), pv.ID) assert.NoError(t, err) assert.Len(t, pfs, 1) - pb, err := packages_model.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages_model.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.EqualValues(t, len(blobContent), pb.Size) }) @@ -281,7 +280,7 @@ func TestPackageContainer(t *testing.T) { uuid := resp.Header().Get("Docker-Upload-Uuid") assert.NotEmpty(t, uuid) - pbu, err := packages_model.GetBlobUploadByID(db.DefaultContext, uuid) + pbu, err := packages_model.GetBlobUploadByID(t.Context(), uuid) assert.NoError(t, err) assert.EqualValues(t, 0, pbu.BytesReceived) @@ -325,7 +324,7 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, uploadURL, resp.Header().Get("Location")) assert.Equal(t, contentRange, resp.Header().Get("Range")) - pbu, err = packages_model.GetBlobUploadByID(db.DefaultContext, uuid) + pbu, err = packages_model.GetBlobUploadByID(t.Context(), uuid) assert.NoError(t, err) assert.EqualValues(t, len(blobContent), pbu.BytesReceived) @@ -423,10 +422,10 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, manifestDigest, resp.Header().Get("Docker-Content-Digest")) - pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag) + pv, err := packages_model.GetVersionByNameAndVersion(t.Context(), user.ID, packages_model.TypeContainer, image, tag) assert.NoError(t, err) - pd, err := packages_model.GetPackageDescriptor(db.DefaultContext, pv) + pd, err := packages_model.GetPackageDescriptor(t.Context(), pv) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.Equal(t, image, pd.Package.Name) @@ -464,7 +463,7 @@ func TestPackageContainer(t *testing.T) { AddTokenAuth(userToken) MakeRequest(t, req, http.StatusOK) - pv, err = packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag) + pv, err = packages_model.GetVersionByNameAndVersion(t.Context(), user.ID, packages_model.TypeContainer, image, tag) assert.NoError(t, err) assert.EqualValues(t, 1, pv.DownloadCount) @@ -474,7 +473,7 @@ func TestPackageContainer(t *testing.T) { SetHeader("Content-Type", oci.MediaTypeImageManifest) MakeRequest(t, req, http.StatusCreated) - pv, err = packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag) + pv, err = packages_model.GetVersionByNameAndVersion(t.Context(), user.ID, packages_model.TypeContainer, image, tag) assert.NoError(t, err) assert.EqualValues(t, 1, pv.DownloadCount) }) @@ -530,10 +529,10 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, strconv.Itoa(len(untaggedManifestContent)), resp.Header().Get("Content-Length")) assert.Equal(t, untaggedManifestDigest, resp.Header().Get("Docker-Content-Digest")) - pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, untaggedManifestDigest) + pv, err := packages_model.GetVersionByNameAndVersion(t.Context(), user.ID, packages_model.TypeContainer, image, untaggedManifestDigest) assert.NoError(t, err) - pd, err := packages_model.GetPackageDescriptor(db.DefaultContext, pv) + pd, err := packages_model.GetPackageDescriptor(t.Context(), pv) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.Equal(t, image, pd.Package.Name) @@ -563,10 +562,10 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, indexManifestDigest, resp.Header().Get("Docker-Content-Digest")) - pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, multiTag) + pv, err := packages_model.GetVersionByNameAndVersion(t.Context(), user.ID, packages_model.TypeContainer, image, multiTag) assert.NoError(t, err) - pd, err := packages_model.GetPackageDescriptor(db.DefaultContext, pv) + pd, err := packages_model.GetPackageDescriptor(t.Context(), pv) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.Equal(t, image, pd.Package.Name) diff --git a/tests/integration/api_packages_cran_test.go b/tests/integration/api_packages_cran_test.go index bd4a99f331..a52d368c3c 100644 --- a/tests/integration/api_packages_cran_test.go +++ b/tests/integration/api_packages_cran_test.go @@ -12,7 +12,6 @@ import ( "net/http" "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" @@ -83,18 +82,18 @@ func TestPackageCran(t *testing.T) { )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeCran) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeCran) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &cran_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s_%s.tar.gz", packageName, packageVersion), pfs[0].Name) @@ -182,11 +181,11 @@ func TestPackageCran(t *testing.T) { )).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeCran) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeCran) assert.NoError(t, err) assert.Len(t, pvs, 1) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 2) diff --git a/tests/integration/api_packages_debian_test.go b/tests/integration/api_packages_debian_test.go index 3ae60d2aa2..663bfb9e67 100644 --- a/tests/integration/api_packages_debian_test.go +++ b/tests/integration/api_packages_debian_test.go @@ -14,7 +14,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" @@ -103,17 +102,17 @@ func TestPackageDebian(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeDebian, packageName, packageVersion) + pv, err := packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeDebian, packageName, packageVersion) assert.NoError(t, err) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv) + pd, err := packages.GetPackageDescriptor(t.Context(), pv) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &debian_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pv.ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pv.ID) assert.NoError(t, err) assert.NotEmpty(t, pfs) assert.Condition(t, func() bool { @@ -129,7 +128,7 @@ func TestPackageDebian(t *testing.T) { assert.True(t, pf.IsLead) - pfps, err := packages.GetProperties(db.DefaultContext, packages.PropertyTypeFile, pf.ID) + pfps, err := packages.GetProperties(t.Context(), packages.PropertyTypeFile, pf.ID) assert.NoError(t, err) for _, pfp := range pfps { @@ -277,7 +276,7 @@ func TestPackageDebian(t *testing.T) { Type: packages.TypeDebian, } - _, err := packages.InsertCleanupRule(db.DefaultContext, rule) + _, err := packages.InsertCleanupRule(t.Context(), rule) assert.NoError(t, err) // When there were a lot of packages (> 50 or 100) and the code used "Iterate" to get all packages, it ever caused bugs, @@ -292,7 +291,7 @@ func TestPackageDebian(t *testing.T) { req := NewRequest(t, "GET", fmt.Sprintf("%s/dists/%s/Release", rootURL, "test")) MakeRequest(t, req, http.StatusOK) - err = packages_cleanup_service.CleanupTask(db.DefaultContext, 0) + err = packages_cleanup_service.CleanupTask(t.Context(), 0) assert.NoError(t, err) req = NewRequest(t, "GET", fmt.Sprintf("%s/dists/%s/Release", rootURL, "test")) diff --git a/tests/integration/api_packages_generic_test.go b/tests/integration/api_packages_generic_test.go index 94e2c6072c..ae0506d48b 100644 --- a/tests/integration/api_packages_generic_test.go +++ b/tests/integration/api_packages_generic_test.go @@ -10,7 +10,6 @@ import ( "net/http" "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" @@ -40,23 +39,23 @@ func TestPackageGeneric(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeGeneric) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.Nil(t, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) @@ -76,7 +75,7 @@ func TestPackageGeneric(t *testing.T) { MakeRequest(t, req, http.StatusCreated) // Check deduplication - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 2) assert.Equal(t, pfs[0].BlobID, pfs[1].BlobID) @@ -103,7 +102,7 @@ func TestPackageGeneric(t *testing.T) { defer tests.PrintCurrentTest(t)() checkDownloadCount := func(count int64) { - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeGeneric) assert.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, count, pvs[0].DownloadCount) @@ -194,7 +193,7 @@ func TestPackageGeneric(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNotFound) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeGeneric) assert.NoError(t, err) assert.Len(t, pvs, 1) @@ -205,7 +204,7 @@ func TestPackageGeneric(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeGeneric) assert.NoError(t, err) assert.Empty(t, pvs) }) @@ -225,7 +224,7 @@ func TestPackageGeneric(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeGeneric) assert.NoError(t, err) assert.Empty(t, pvs) diff --git a/tests/integration/api_packages_goproxy_test.go b/tests/integration/api_packages_goproxy_test.go index fa0ee5b901..e42e00b8b6 100644 --- a/tests/integration/api_packages_goproxy_test.go +++ b/tests/integration/api_packages_goproxy_test.go @@ -11,7 +11,6 @@ import ( "testing" "time" - "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" @@ -63,23 +62,23 @@ func TestPackageGo(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGo) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeGo) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.Nil(t, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, packageVersion+".zip", pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) diff --git a/tests/integration/api_packages_helm_test.go b/tests/integration/api_packages_helm_test.go index 8f5c6ac571..02df4ae906 100644 --- a/tests/integration/api_packages_helm_test.go +++ b/tests/integration/api_packages_helm_test.go @@ -12,7 +12,6 @@ import ( "testing" "time" - "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" @@ -72,24 +71,24 @@ dependencies: AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeHelm) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeHelm) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &helm_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) @@ -102,7 +101,7 @@ dependencies: defer tests.PrintCurrentTest(t)() checkDownloadCount := func(count int64) { - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeHelm) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeHelm) assert.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, count, pvs[0].DownloadCount) diff --git a/tests/integration/api_packages_maven_test.go b/tests/integration/api_packages_maven_test.go index 30ef1884cd..b408d7b36c 100644 --- a/tests/integration/api_packages_maven_test.go +++ b/tests/integration/api_packages_maven_test.go @@ -12,7 +12,6 @@ import ( "sync" "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" @@ -55,24 +54,24 @@ func TestPackageMaven(t *testing.T) { putFile(t, fmt.Sprintf("/%s/%s", packageVersion, filename), "test", http.StatusConflict) putFile(t, "/maven-metadata.xml", "test", http.StatusOK) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeMaven) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeMaven) require.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.Nil(t, pd.Metadata) assert.Equal(t, groupID+":"+artifactID, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.False(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) require.NoError(t, err) assert.Equal(t, int64(4), pb.Size) }) @@ -84,7 +83,7 @@ func TestPackageMaven(t *testing.T) { legacyRootLink := "/api/packages/user2/maven/com/gitea/legacy-project" req := NewRequestWithBody(t, "PUT", legacyRootLink+"/1.0.2/any-file-name?use_legacy_package_name=1", strings.NewReader("test-content")).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - p, err := packages.GetPackageByName(db.DefaultContext, user.ID, packages.TypeMaven, "com.gitea-legacy-project") + p, err := packages.GetPackageByName(t.Context(), user.ID, packages.TypeMaven, "com.gitea-legacy-project") require.NoError(t, err) assert.Equal(t, "com.gitea-legacy-project", p.Name) @@ -107,9 +106,9 @@ func TestPackageMaven(t *testing.T) { // then upload a package with correct package name (will be saved as "GroupID:ArtifactID") req = NewRequestWithBody(t, "PUT", legacyRootLink+"/1.0.3/any-file-name", strings.NewReader("test-content")).AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - _, err = packages.GetPackageByName(db.DefaultContext, user.ID, packages.TypeMaven, "com.gitea-legacy-project") + _, err = packages.GetPackageByName(t.Context(), user.ID, packages.TypeMaven, "com.gitea-legacy-project") require.ErrorIs(t, err, packages.ErrPackageNotExist) - p, err = packages.GetPackageByName(db.DefaultContext, user.ID, packages.TypeMaven, "com.gitea:legacy-project") + p, err = packages.GetPackageByName(t.Context(), user.ID, packages.TypeMaven, "com.gitea:legacy-project") require.NoError(t, err) assert.Equal(t, "com.gitea:legacy-project", p.Name) req = NewRequest(t, "HEAD", legacyRootLink+"/1.0.2/any-file-name").AddBasicAuth(user.Name) @@ -128,7 +127,7 @@ func TestPackageMaven(t *testing.T) { respBody = resp.Body.String() assert.Contains(t, respBody, "1.0.2") assert.Contains(t, respBody, "1.0.3") - require.NoError(t, packages.DeletePackageByID(db.DefaultContext, p.ID)) + require.NoError(t, packages.DeletePackageByID(t.Context(), p.ID)) }) t.Run("UploadExists", func(t *testing.T) { @@ -152,7 +151,7 @@ func TestPackageMaven(t *testing.T) { assert.Equal(t, []byte("test"), resp.Body.Bytes()) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeMaven) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeMaven) require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(0), pvs[0].DownloadCount) @@ -184,26 +183,26 @@ func TestPackageMaven(t *testing.T) { t.Run("UploadPOM", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeMaven) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeMaven) require.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) require.NoError(t, err) assert.Nil(t, pd.Metadata) putFile(t, fmt.Sprintf("/%s/%s.pom", packageVersion, filename), pomContent, http.StatusCreated) - pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeMaven) + pvs, err = packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeMaven) require.NoError(t, err) assert.Len(t, pvs, 1) - pd, err = packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err = packages.GetPackageDescriptor(t.Context(), pvs[0]) require.NoError(t, err) assert.IsType(t, &maven.Metadata{}, pd.Metadata) assert.Equal(t, packageDescription, pd.Metadata.(*maven.Metadata).Description) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) require.NoError(t, err) assert.Len(t, pfs, 2) for _, pf := range pfs { @@ -231,7 +230,7 @@ func TestPackageMaven(t *testing.T) { assert.Equal(t, []byte(pomContent), resp.Body.Bytes()) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeMaven) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeMaven) require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(1), pvs[0].DownloadCount) diff --git a/tests/integration/api_packages_npm_test.go b/tests/integration/api_packages_npm_test.go index a190ed679d..bbf7af09e3 100644 --- a/tests/integration/api_packages_npm_test.go +++ b/tests/integration/api_packages_npm_test.go @@ -12,7 +12,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -100,11 +99,11 @@ func TestPackageNpm(t *testing.T) { AddTokenAuth(token) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNpm) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &npm.Metadata{}, pd.Metadata) @@ -114,13 +113,13 @@ func TestPackageNpm(t *testing.T) { assert.Equal(t, npm.TagProperty, pd.VersionProperties[0].Name) assert.Equal(t, packageTag, pd.VersionProperties[0].Value) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.Equal(t, int64(192), pb.Size) }) @@ -149,7 +148,7 @@ func TestPackageNpm(t *testing.T) { assert.Equal(t, b, resp.Body.Bytes()) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNpm) assert.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(2), pvs[0].DownloadCount) @@ -304,7 +303,7 @@ func TestPackageNpm(t *testing.T) { t.Run("Version", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNpm) assert.NoError(t, err) assert.Len(t, pvs, 2) @@ -315,7 +314,7 @@ func TestPackageNpm(t *testing.T) { AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) - pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) + pvs, err = packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNpm) assert.NoError(t, err) assert.Len(t, pvs, 1) }) @@ -323,7 +322,7 @@ func TestPackageNpm(t *testing.T) { t.Run("Full", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNpm) assert.NoError(t, err) assert.Len(t, pvs, 1) @@ -334,7 +333,7 @@ func TestPackageNpm(t *testing.T) { AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) - pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) + pvs, err = packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNpm) assert.NoError(t, err) assert.Empty(t, pvs) }) diff --git a/tests/integration/api_packages_nuget_test.go b/tests/integration/api_packages_nuget_test.go index 529b540062..f29a43f980 100644 --- a/tests/integration/api_packages_nuget_test.go +++ b/tests/integration/api_packages_nuget_test.go @@ -19,7 +19,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -295,18 +294,18 @@ func TestPackageNuGet(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNuGet) assert.NoError(t, err) assert.Len(t, pvs, 1, "Should have one version") - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &nuget_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 2, "Should have 2 files: nuget and nuspec") for _, pf := range pfs { @@ -314,7 +313,7 @@ func TestPackageNuGet(t *testing.T) { case fmt.Sprintf("%s.%s.nupkg", packageName, packageVersion): assert.True(t, pf.IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) + pb, err := packages.GetBlobByID(t.Context(), pf.BlobID) assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) case packageName + ".nuspec": @@ -329,7 +328,7 @@ func TestPackageNuGet(t *testing.T) { MakeRequest(t, req, http.StatusConflict) // delete the package - assert.NoError(t, packageService.DeletePackageVersionAndReferences(db.DefaultContext, pvs[0])) + assert.NoError(t, packageService.DeletePackageVersionAndReferences(t.Context(), pvs[0])) // create failure with token without write access req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). @@ -341,18 +340,18 @@ func TestPackageNuGet(t *testing.T) { AddTokenAuth(writeToken) MakeRequest(t, req, http.StatusCreated) - pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) + pvs, err = packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNuGet) assert.NoError(t, err) assert.Len(t, pvs, 1, "Should have one version") - pd, err = packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err = packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &nuget_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err = packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err = packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 2, "Should have 2 files: nuget and nuspec") for _, pf := range pfs { @@ -360,7 +359,7 @@ func TestPackageNuGet(t *testing.T) { case fmt.Sprintf("%s.%s.nupkg", packageName, packageVersion): assert.True(t, pf.IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) + pb, err := packages.GetBlobByID(t.Context(), pf.BlobID) assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) case packageName + ".nuspec": @@ -416,18 +415,18 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNuGet) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &nuget_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 4, "Should have 4 files: nupkg, snupkg, nuspec and pdb") for _, pf := range pfs { @@ -435,29 +434,29 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) case fmt.Sprintf("%s.%s.nupkg", packageName, packageVersion): assert.True(t, pf.IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) + pb, err := packages.GetBlobByID(t.Context(), pf.BlobID) assert.NoError(t, err) assert.Equal(t, int64(633), pb.Size) case fmt.Sprintf("%s.%s.snupkg", packageName, packageVersion): assert.False(t, pf.IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) + pb, err := packages.GetBlobByID(t.Context(), pf.BlobID) assert.NoError(t, err) assert.Equal(t, int64(616), pb.Size) case packageName + ".nuspec": assert.False(t, pf.IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) + pb, err := packages.GetBlobByID(t.Context(), pf.BlobID) assert.NoError(t, err) assert.Equal(t, int64(1043), pb.Size) case symbolFilename: assert.False(t, pf.IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) + pb, err := packages.GetBlobByID(t.Context(), pf.BlobID) assert.NoError(t, err) assert.Equal(t, int64(160), pb.Size) - pps, err := packages.GetProperties(db.DefaultContext, packages.PropertyTypeFile, pf.ID) + pps, err := packages.GetProperties(t.Context(), packages.PropertyTypeFile, pf.ID) assert.NoError(t, err) assert.Len(t, pps, 1) assert.Equal(t, nuget_module.PropertySymbolID, pps[0].Name) @@ -477,7 +476,7 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) defer tests.PrintCurrentTest(t)() checkDownloadCount := func(count int64) { - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNuGet) assert.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, count, pvs[0].DownloadCount) @@ -907,7 +906,7 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeNuGet) assert.NoError(t, err) assert.Empty(t, pvs) }) diff --git a/tests/integration/api_packages_pub_test.go b/tests/integration/api_packages_pub_test.go index 3c1bca908e..a080ede5df 100644 --- a/tests/integration/api_packages_pub_test.go +++ b/tests/integration/api_packages_pub_test.go @@ -16,7 +16,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -100,24 +99,24 @@ description: ` + packageDescription AddTokenAuth(token) MakeRequest(t, req, http.StatusOK) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypePub) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypePub) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &pub_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) diff --git a/tests/integration/api_packages_pypi_test.go b/tests/integration/api_packages_pypi_test.go index 54db45f1ac..67786b3e03 100644 --- a/tests/integration/api_packages_pypi_test.go +++ b/tests/integration/api_packages_pypi_test.go @@ -13,7 +13,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" @@ -80,11 +79,11 @@ func TestPackagePyPI(t *testing.T) { filename := "test.whl" uploadFile(t, filename, content, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypePyPI) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypePyPI) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &pypi.Metadata{}, pd.Metadata) @@ -92,13 +91,13 @@ func TestPackagePyPI(t *testing.T) { assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.Equal(t, int64(4), pb.Size) }) @@ -109,27 +108,27 @@ func TestPackagePyPI(t *testing.T) { filename := "test.tar.gz" uploadFile(t, filename, content, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypePyPI) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypePyPI) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &pypi.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 2) - pf, err := packages.GetFileForVersionByName(db.DefaultContext, pvs[0].ID, filename, packages.EmptyFileKey) + pf, err := packages.GetFileForVersionByName(t.Context(), pvs[0].ID, filename, packages.EmptyFileKey) assert.NoError(t, err) assert.Equal(t, filename, pf.Name) assert.True(t, pf.IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) + pb, err := packages.GetBlobByID(t.Context(), pf.BlobID) assert.NoError(t, err) assert.Equal(t, int64(4), pb.Size) }) @@ -160,11 +159,11 @@ func TestPackagePyPI(t *testing.T) { uploadHelper(t, body, writer.FormDataContentType(), http.StatusCreated) - pvs, err := packages.GetVersionsByPackageName(db.DefaultContext, user.ID, packages.TypePyPI, pkgName) + pvs, err := packages.GetVersionsByPackageName(t.Context(), user.ID, packages.TypePyPI, pkgName) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.IsType(t, &pypi.Metadata{}, pd.Metadata) assert.Equal(t, projectURL, pd.Metadata.(*pypi.Metadata).ProjectURL) @@ -180,11 +179,11 @@ func TestPackagePyPI(t *testing.T) { uploadHelper(t, body, writer.FormDataContentType(), http.StatusCreated) - pvs, err := packages.GetVersionsByPackageName(db.DefaultContext, user.ID, packages.TypePyPI, pkgName) + pvs, err := packages.GetVersionsByPackageName(t.Context(), user.ID, packages.TypePyPI, pkgName) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.IsType(t, &pypi.Metadata{}, pd.Metadata) assert.Empty(t, pd.Metadata.(*pypi.Metadata).ProjectURL) @@ -204,7 +203,7 @@ func TestPackagePyPI(t *testing.T) { downloadFile("test.whl") downloadFile("test.tar.gz") - pvs, err := packages.GetVersionsByPackageName(db.DefaultContext, user.ID, packages.TypePyPI, packageName) + pvs, err := packages.GetVersionsByPackageName(t.Context(), user.ID, packages.TypePyPI, packageName) assert.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(2), pvs[0].DownloadCount) diff --git a/tests/integration/api_packages_rpm_test.go b/tests/integration/api_packages_rpm_test.go index bd1959f64e..2c9dddc7b4 100644 --- a/tests/integration/api_packages_rpm_test.go +++ b/tests/integration/api_packages_rpm_test.go @@ -15,7 +15,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" @@ -128,24 +127,24 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRpm) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeRpm) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &rpm_module.VersionMetadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s-%s.%s.rpm", packageName, packageVersion, packageArchitecture), pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) @@ -432,7 +431,7 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusNoContent) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRpm) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeRpm) assert.NoError(t, err) assert.Empty(t, pvs) req = NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", groupURL, packageName, packageVersion, packageArchitecture)). diff --git a/tests/integration/api_packages_rubygems_test.go b/tests/integration/api_packages_rubygems_test.go index ab76c52440..6236f13714 100644 --- a/tests/integration/api_packages_rubygems_test.go +++ b/tests/integration/api_packages_rubygems_test.go @@ -15,7 +15,6 @@ import ( "net/http" "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" @@ -195,24 +194,24 @@ func TestPackageRubyGems(t *testing.T) { uploadFile(t, testGemContent, http.StatusCreated) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeRubyGems) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &rubygems.Metadata{}, pd.Metadata) assert.Equal(t, testGemName, pd.Package.Name) assert.Equal(t, testGemVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s-%s.gem", testGemName, testGemVersion), pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.EqualValues(t, len(testGemContent), pb.Size) }) @@ -231,7 +230,7 @@ func TestPackageRubyGems(t *testing.T) { assert.Equal(t, testGemContent, resp.Body.Bytes()) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeRubyGems) assert.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(1), pvs[0].DownloadCount) @@ -250,7 +249,7 @@ DGAWSKc7zFhPJamg0qRK99TcYphehZLU4hKInFhGSUlBsZW+PtgZepn5+iDxECRzDUDGcfh6hoA4 gAAAAP//MS06Gw==`) assert.Equal(t, b, resp.Body.Bytes()) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeRubyGems) assert.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(1), pvs[0].DownloadCount) @@ -317,7 +316,7 @@ gitea-another 0.99 8b639e4048d282941485368ec42609be defer tests.PrintCurrentTest(t)() deleteGemPackage(t, testGemName, testGemVersion) deleteGemPackage(t, testAnotherGemName, testAnotherGemVersion) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeRubyGems) assert.NoError(t, err) assert.Empty(t, pvs) }) diff --git a/tests/integration/api_packages_swift_test.go b/tests/integration/api_packages_swift_test.go index b29e8459ff..59e1470632 100644 --- a/tests/integration/api_packages_swift_test.go +++ b/tests/integration/api_packages_swift_test.go @@ -13,7 +13,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" @@ -150,11 +149,11 @@ func TestPackageSwift(t *testing.T) { `{"name":"`+packageName+`","version":"`+packageVersion+`","description":"`+packageDescription+`","codeRepository":"`+packageRepositoryURL+`","author":{"givenName":"`+packageAuthor+`"},"repositoryURLs":["`+packageRepositoryURL+`"]}`, ) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeSwift) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeSwift) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.Equal(t, packageID, pd.Package.Name) @@ -168,7 +167,7 @@ func TestPackageSwift(t *testing.T) { assert.Len(t, pd.VersionProperties, 1) assert.Equal(t, packageRepositoryURL, pd.VersionProperties.GetByName(swift_module.PropertyRepositoryURL)) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s-%s.zip", packageName, packageVersion), pfs[0].Name) @@ -238,11 +237,11 @@ func TestPackageSwift(t *testing.T) { `{"name":"`+packageName+`","version":"`+packageVersion2+`","description":"`+packageDescription+`","codeRepository":"`+packageRepositoryURL+`","author":{"givenName":"`+packageAuthor+`"},"repositoryURLs":["`+packageRepositoryURL+`"]}`, ) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeSwift) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeSwift) assert.NoError(t, err) require.Len(t, pvs, 2) // ATTENTION: many subtests are unable to run separately, they depend on the results of previous tests thisPackageVersion := pvs[0] - pd, err := packages.GetPackageDescriptor(db.DefaultContext, thisPackageVersion) + pd, err := packages.GetPackageDescriptor(t.Context(), thisPackageVersion) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.Equal(t, packageID, pd.Package.Name) @@ -256,7 +255,7 @@ func TestPackageSwift(t *testing.T) { assert.Len(t, pd.VersionProperties, 1) assert.Equal(t, packageRepositoryURL, pd.VersionProperties.GetByName(swift_module.PropertyRepositoryURL)) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, thisPackageVersion.ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), thisPackageVersion.ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s-%s.zip", packageName, packageVersion2), pfs[0].Name) @@ -284,11 +283,11 @@ func TestPackageSwift(t *testing.T) { assert.Equal(t, "1", resp.Header().Get("Content-Version")) assert.Equal(t, "application/zip", resp.Header().Get("Content-Type")) - pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeSwift, packageID, packageVersion) + pv, err := packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeSwift, packageID, packageVersion) assert.NotNil(t, pv) assert.NoError(t, err) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv) + pd, err := packages.GetPackageDescriptor(t.Context(), pv) assert.NoError(t, err) assert.Equal(t, "sha256="+pd.Files[0].Blob.HashSHA256, resp.Header().Get("Digest")) }) @@ -337,11 +336,11 @@ func TestPackageSwift(t *testing.T) { var result *swift_router.PackageVersionMetadataResponse DecodeJSON(t, resp, &result) - pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeSwift, packageID, packageVersion) + pv, err := packages.GetVersionByNameAndVersion(t.Context(), user.ID, packages.TypeSwift, packageID, packageVersion) assert.NotNil(t, pv) assert.NoError(t, err) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv) + pd, err := packages.GetPackageDescriptor(t.Context(), pv) assert.NoError(t, err) assert.Equal(t, packageID, result.ID) diff --git a/tests/integration/api_packages_test.go b/tests/integration/api_packages_test.go index f10b098885..4fbb31b11f 100644 --- a/tests/integration/api_packages_test.go +++ b/tests/integration/api_packages_test.go @@ -119,7 +119,7 @@ func TestPackageAPI(t *testing.T) { t.Run("RepositoryLink", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - _, err := packages_model.GetPackageByName(db.DefaultContext, user.ID, packages_model.TypeGeneric, packageName) + _, err := packages_model.GetPackageByName(t.Context(), user.ID, packages_model.TypeGeneric, packageName) assert.NoError(t, err) // no repository link @@ -132,7 +132,7 @@ func TestPackageAPI(t *testing.T) { assert.Nil(t, ap1.Repository) // create a repository - newRepo, err := repo_service.CreateRepository(db.DefaultContext, user, user, repo_service.CreateRepoOptions{ + newRepo, err := repo_service.CreateRepository(t.Context(), user, user, repo_service.CreateRepoOptions{ Name: "repo4", }) assert.NoError(t, err) @@ -168,7 +168,7 @@ func TestPackageAPI(t *testing.T) { // force link to a repository the currently logged-in user doesn't have access to privateRepoID := int64(6) - assert.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, ap1.ID, privateRepoID)) + assert.NoError(t, packages_model.SetRepositoryLink(t.Context(), ap1.ID, privateRepoID)) req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)).AddTokenAuth(tokenReadPackage) resp = MakeRequest(t, req, http.StatusOK) @@ -177,7 +177,7 @@ func TestPackageAPI(t *testing.T) { DecodeJSON(t, resp, &ap4) assert.Nil(t, ap4.Repository) - assert.NoError(t, packages_model.UnlinkRepositoryFromAllPackages(db.DefaultContext, privateRepoID)) + assert.NoError(t, packages_model.UnlinkRepositoryFromAllPackages(t.Context(), privateRepoID)) }) t.Run("ListPackageFiles", func(t *testing.T) { @@ -534,21 +534,21 @@ func TestPackageCleanup(t *testing.T) { AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusCreated) - pbs, err := packages_model.FindExpiredUnreferencedBlobs(db.DefaultContext, duration) + pbs, err := packages_model.FindExpiredUnreferencedBlobs(t.Context(), duration) assert.NoError(t, err) assert.NotEmpty(t, pbs) - _, err = packages_model.GetInternalVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, "cleanup-test", container_module.UploadVersion) + _, err = packages_model.GetInternalVersionByNameAndVersion(t.Context(), user.ID, packages_model.TypeContainer, "cleanup-test", container_module.UploadVersion) assert.NoError(t, err) - err = packages_cleanup_service.CleanupTask(db.DefaultContext, duration) + err = packages_cleanup_service.CleanupTask(t.Context(), duration) assert.NoError(t, err) - pbs, err = packages_model.FindExpiredUnreferencedBlobs(db.DefaultContext, duration) + pbs, err = packages_model.FindExpiredUnreferencedBlobs(t.Context(), duration) assert.NoError(t, err) assert.Empty(t, pbs) - _, err = packages_model.GetInternalVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, "cleanup-test", container_module.UploadVersion) + _, err = packages_model.GetInternalVersionByNameAndVersion(t.Context(), user.ID, packages_model.TypeContainer, "cleanup-test", container_module.UploadVersion) assert.ErrorIs(t, err, packages_model.ErrPackageNotExist) }) @@ -667,9 +667,9 @@ func TestPackageCleanup(t *testing.T) { MakeRequest(t, req, http.StatusCreated) if v.Created != 0 { - pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeGeneric, "package", v.Version) + pv, err := packages_model.GetVersionByNameAndVersion(t.Context(), user.ID, packages_model.TypeGeneric, "package", v.Version) assert.NoError(t, err) - _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE package_version SET created_unix = ? WHERE id = ?", v.Created, pv.ID) + _, err = db.GetEngine(t.Context()).Exec("UPDATE package_version SET created_unix = ? WHERE id = ?", v.Created, pv.ID) assert.NoError(t, err) } } @@ -677,24 +677,24 @@ func TestPackageCleanup(t *testing.T) { c.Rule.OwnerID = user.ID c.Rule.Type = packages_model.TypeGeneric - pcr, err := packages_model.InsertCleanupRule(db.DefaultContext, c.Rule) + pcr, err := packages_model.InsertCleanupRule(t.Context(), c.Rule) assert.NoError(t, err) - err = packages_cleanup_service.CleanupTask(db.DefaultContext, duration) + err = packages_cleanup_service.CleanupTask(t.Context(), duration) assert.NoError(t, err) for _, v := range c.Versions { - pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeGeneric, "package", v.Version) + pv, err := packages_model.GetVersionByNameAndVersion(t.Context(), user.ID, packages_model.TypeGeneric, "package", v.Version) if v.ShouldExist { assert.NoError(t, err) - err = packages_service.DeletePackageVersionAndReferences(db.DefaultContext, pv) + err = packages_service.DeletePackageVersionAndReferences(t.Context(), pv) assert.NoError(t, err) } else { assert.ErrorIs(t, err, packages_model.ErrPackageNotExist, v.Version) } } - assert.NoError(t, packages_model.DeleteCleanupRuleByID(db.DefaultContext, pcr.ID)) + assert.NoError(t, packages_model.DeleteCleanupRuleByID(t.Context(), pcr.ID)) }) } }) diff --git a/tests/integration/api_packages_vagrant_test.go b/tests/integration/api_packages_vagrant_test.go index 1743e37222..22412a8558 100644 --- a/tests/integration/api_packages_vagrant_test.go +++ b/tests/integration/api_packages_vagrant_test.go @@ -13,7 +13,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -90,24 +89,24 @@ func TestPackageVagrant(t *testing.T) { resp := MakeRequest(t, req, http.StatusOK) assert.True(t, strings.HasPrefix(resp.Header().Get("Content-Type"), "application/json")) - pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeVagrant) + pvs, err := packages.GetVersionsByPackageType(t.Context(), user.ID, packages.TypeVagrant) assert.NoError(t, err) assert.Len(t, pvs, 1) - pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) + pd, err := packages.GetPackageDescriptor(t.Context(), pvs[0]) assert.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &vagrant_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) - pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) + pfs, err := packages.GetFilesByVersionID(t.Context(), pvs[0].ID) assert.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) - pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) + pb, err := packages.GetBlobByID(t.Context(), pfs[0].BlobID) assert.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) diff --git a/tests/integration/api_pull_commits_test.go b/tests/integration/api_pull_commits_test.go index f43ad7d3be..05143fcf25 100644 --- a/tests/integration/api_pull_commits_test.go +++ b/tests/integration/api_pull_commits_test.go @@ -7,7 +7,6 @@ import ( "net/http" "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" @@ -21,7 +20,7 @@ import ( func TestAPIPullCommits(t *testing.T) { defer tests.PrepareTestEnv(t)() pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + assert.NoError(t, pr.LoadIssue(t.Context())) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pr.HeadRepoID}) req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/commits", repo.OwnerName, repo.Name, pr.Index) diff --git a/tests/integration/api_pull_review_test.go b/tests/integration/api_pull_review_test.go index a6dab1d40a..9ffbd9a267 100644 --- a/tests/integration/api_pull_review_test.go +++ b/tests/integration/api_pull_review_test.go @@ -28,7 +28,7 @@ import ( func TestAPIPullReview(t *testing.T) { defer tests.PrepareTestEnv(t)() pullIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) - assert.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) + assert.NoError(t, pullIssue.LoadAttributes(t.Context())) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.RepoID}) // test ListPullReviews @@ -84,7 +84,7 @@ func TestAPIPullReview(t *testing.T) { assert.Equal(t, "a review from a deleted user", reviewComments[0].Body) assert.Equal(t, comment.ID, reviewComments[0].ID) assert.EqualValues(t, comment.UpdatedUnix, reviewComments[0].Updated.Unix()) - assert.Equal(t, comment.HTMLURL(db.DefaultContext), reviewComments[0].HTMLURL) + assert.Equal(t, comment.HTMLURL(t.Context()), reviewComments[0].HTMLURL) // test CreatePullReview req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/reviews", repo.OwnerName, repo.Name, pullIssue.Index), &api.CreatePullReviewOptions{ @@ -212,7 +212,7 @@ func TestAPIPullReview(t *testing.T) { // test get review requests // to make it simple, use same api with get review pullIssue12 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 12}) - assert.NoError(t, pullIssue12.LoadAttributes(db.DefaultContext)) + assert.NoError(t, pullIssue12.LoadAttributes(t.Context())) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue12.RepoID}) req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews", repo3.OwnerName, repo3.Name, pullIssue12.Index). @@ -237,7 +237,7 @@ func TestAPIPullReview(t *testing.T) { func TestAPIPullReviewRequest(t *testing.T) { defer tests.PrepareTestEnv(t)() pullIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) - assert.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) + assert.NoError(t, pullIssue.LoadAttributes(t.Context())) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.RepoID}) // Test add Review Request @@ -282,7 +282,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // a collaborator can add/remove a review request pullIssue21 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 21}) - assert.NoError(t, pullIssue21.LoadAttributes(db.DefaultContext)) + assert.NoError(t, pullIssue21.LoadAttributes(t.Context())) pull21Repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue21.RepoID}) // repo60 user38Session := loginUser(t, "user38") user38Token := getTokenForLoggedInUser(t, user38Session, auth_model.AccessTokenScopeWriteRepository) @@ -311,7 +311,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // user with read permission on pull requests unit can add/remove a review request pullIssue22 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 22}) - assert.NoError(t, pullIssue22.LoadAttributes(db.DefaultContext)) + assert.NoError(t, pullIssue22.LoadAttributes(t.Context())) pull22Repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue22.RepoID}) // repo61 req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", pull22Repo.OwnerName, pull22Repo.Name, pullIssue22.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user38"}, @@ -325,7 +325,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test team review request pullIssue12 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 12}) - assert.NoError(t, pullIssue12.LoadAttributes(db.DefaultContext)) + assert.NoError(t, pullIssue12.LoadAttributes(t.Context())) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue12.RepoID}) // Test add Team Review Request @@ -367,7 +367,7 @@ func TestAPIPullReviewStayDismissed(t *testing.T) { // where old reviews surface after a review request got dismissed. defer tests.PrepareTestEnv(t)() pullIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) - assert.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) + assert.NoError(t, pullIssue.LoadAttributes(t.Context())) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.RepoID}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session2 := loginUser(t, user2.LoginName) @@ -408,7 +408,7 @@ func TestAPIPullReviewStayDismissed(t *testing.T) { pullIssue.ID, user8.ID, 0, 0, 1, true) // emulate of auto-dismiss lgtm on a protected branch that where a pull just got an update - _, err := db.GetEngine(db.DefaultContext).Where("issue_id = ? AND reviewer_id = ?", pullIssue.ID, user8.ID). + _, err := db.GetEngine(t.Context()).Where("issue_id = ? AND reviewer_id = ?", pullIssue.ID, user8.ID). Cols("dismissed").Update(&issues_model.Review{Dismissed: true}) assert.NoError(t, err) @@ -423,9 +423,9 @@ func TestAPIPullReviewStayDismissed(t *testing.T) { pullIssue.ID, user8.ID, 1, 1, 2, false) // user8 dismiss review - permUser8, err := access_model.GetUserRepoPermission(db.DefaultContext, pullIssue.Repo, user8) + permUser8, err := access_model.GetUserRepoPermission(t.Context(), pullIssue.Repo, user8) assert.NoError(t, err) - _, err = issue_service.ReviewRequest(db.DefaultContext, pullIssue, user8, &permUser8, user8, false) + _, err = issue_service.ReviewRequest(t.Context(), pullIssue, user8, &permUser8, user8, false) assert.NoError(t, err) reviewsCountCheck(t, diff --git a/tests/integration/api_pull_test.go b/tests/integration/api_pull_test.go index 71d59352e2..8376fd2717 100644 --- a/tests/integration/api_pull_test.go +++ b/tests/integration/api_pull_test.go @@ -14,7 +14,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" @@ -169,11 +168,11 @@ func TestAPIMergePullWIP(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{Status: issues_model.PullRequestStatusMergeable}, unittest.Cond("has_merged = ?", false)) - pr.LoadIssue(db.DefaultContext) - issue_service.ChangeTitle(db.DefaultContext, pr.Issue, owner, setting.Repository.PullRequest.WorkInProgressPrefixes[0]+" "+pr.Issue.Title) + pr.LoadIssue(t.Context()) + issue_service.ChangeTitle(t.Context(), pr.Issue, owner, setting.Repository.PullRequest.WorkInProgressPrefixes[0]+" "+pr.Issue.Title) // force reload - pr.LoadAttributes(db.DefaultContext) + pr.LoadAttributes(t.Context()) assert.Contains(t, pr.Issue.Title, setting.Repository.PullRequest.WorkInProgressPrefixes[0]) @@ -386,7 +385,7 @@ func TestAPIEditPull(t *testing.T) { assert.Equal(t, "feature/1", apiPull.Base.Name) // check comment history pull := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: apiPull.ID}) - err := pull.LoadIssue(db.DefaultContext) + err := pull.LoadIssue(t.Context()) assert.NoError(t, err) unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{IssueID: pull.Issue.ID, OldTitle: title, NewTitle: newTitle}) unittest.AssertExistsAndLoadBean(t, &issues_model.ContentHistory{IssueID: pull.Issue.ID, ContentText: newBody, IsFirstCreated: false}) diff --git a/tests/integration/api_repo_edit_test.go b/tests/integration/api_repo_edit_test.go index 7fe59c0d09..34d6990497 100644 --- a/tests/integration/api_repo_edit_test.go +++ b/tests/integration/api_repo_edit_test.go @@ -4,13 +4,13 @@ package integration import ( + "context" "fmt" "net/http" "net/url" "testing" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/models/unittest" @@ -22,6 +22,7 @@ import ( // getRepoEditOptionFromRepo gets the options for an existing repo exactly as is func getRepoEditOptionFromRepo(repo *repo_model.Repository) *api.EditRepoOption { + ctx := context.TODO() name := repo.Name description := repo.Description website := repo.Website @@ -29,7 +30,7 @@ func getRepoEditOptionFromRepo(repo *repo_model.Repository) *api.EditRepoOption hasIssues := false var internalTracker *api.InternalTracker var externalTracker *api.ExternalTracker - if unit, err := repo.GetUnit(db.DefaultContext, unit_model.TypeIssues); err == nil { + if unit, err := repo.GetUnit(ctx, unit_model.TypeIssues); err == nil { config := unit.IssuesConfig() hasIssues = true internalTracker = &api.InternalTracker{ @@ -37,7 +38,7 @@ func getRepoEditOptionFromRepo(repo *repo_model.Repository) *api.EditRepoOption AllowOnlyContributorsToTrackTime: config.AllowOnlyContributorsToTrackTime, EnableIssueDependencies: config.EnableDependencies, } - } else if unit, err := repo.GetUnit(db.DefaultContext, unit_model.TypeExternalTracker); err == nil { + } else if unit, err := repo.GetUnit(ctx, unit_model.TypeExternalTracker); err == nil { config := unit.ExternalTrackerConfig() hasIssues = true externalTracker = &api.ExternalTracker{ @@ -49,9 +50,9 @@ func getRepoEditOptionFromRepo(repo *repo_model.Repository) *api.EditRepoOption } hasWiki := false var externalWiki *api.ExternalWiki - if _, err := repo.GetUnit(db.DefaultContext, unit_model.TypeWiki); err == nil { + if _, err := repo.GetUnit(ctx, unit_model.TypeWiki); err == nil { hasWiki = true - } else if unit, err := repo.GetUnit(db.DefaultContext, unit_model.TypeExternalWiki); err == nil { + } else if unit, err := repo.GetUnit(ctx, unit_model.TypeExternalWiki); err == nil { hasWiki = true externalWiki = &api.ExternalWiki{ ExternalWikiURL: unit.ExternalWikiConfig().ExternalWikiURL, @@ -65,7 +66,7 @@ func getRepoEditOptionFromRepo(repo *repo_model.Repository) *api.EditRepoOption allowRebaseMerge := false allowSquash := false allowFastForwardOnly := false - if unit, err := repo.GetUnit(db.DefaultContext, unit_model.TypePullRequests); err == nil { + if unit, err := repo.GetUnit(ctx, unit_model.TypePullRequests); err == nil { config := unit.PullRequestsConfig() hasPullRequests = true ignoreWhitespaceConflicts = config.IgnoreWhitespaceConflicts @@ -78,16 +79,16 @@ func getRepoEditOptionFromRepo(repo *repo_model.Repository) *api.EditRepoOption archived := repo.IsArchived hasProjects := false var projectsMode *string - if unit, err := repo.GetUnit(db.DefaultContext, unit_model.TypeProjects); err == nil && unit != nil { + if unit, err := repo.GetUnit(ctx, unit_model.TypeProjects); err == nil && unit != nil { hasProjects = true pm := string(unit.ProjectsConfig().ProjectsMode) projectsMode = &pm } - hasCode := repo.UnitEnabled(db.DefaultContext, unit_model.TypeCode) - hasPackages := repo.UnitEnabled(db.DefaultContext, unit_model.TypePackages) - hasReleases := repo.UnitEnabled(db.DefaultContext, unit_model.TypeReleases) + hasCode := repo.UnitEnabled(ctx, unit_model.TypeCode) + hasPackages := repo.UnitEnabled(ctx, unit_model.TypePackages) + hasReleases := repo.UnitEnabled(ctx, unit_model.TypeReleases) hasActions := false - if unit, err := repo.GetUnit(db.DefaultContext, unit_model.TypeActions); err == nil && unit != nil { + if unit, err := repo.GetUnit(ctx, unit_model.TypeActions); err == nil && unit != nil { hasActions = true // TODO: expose action config of repo to api // actionsConfig = &api.RepoActionsConfig{ diff --git a/tests/integration/api_repo_lfs_test.go b/tests/integration/api_repo_lfs_test.go index ec6a3a3b57..da4c89a1b7 100644 --- a/tests/integration/api_repo_lfs_test.go +++ b/tests/integration/api_repo_lfs_test.go @@ -12,7 +12,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" @@ -64,7 +63,7 @@ func createLFSTestRepository(t *testing.T, name string) *repo_model.Repository { ctx := NewAPITestContext(t, "user2", "lfs-"+name+"-repo", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) t.Run("CreateRepo", doAPICreateRepository(ctx, false)) - repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "lfs-"+name+"-repo") + repo, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), "user2", "lfs-"+name+"-repo") assert.NoError(t, err) return repo @@ -79,7 +78,7 @@ func TestAPILFSBatch(t *testing.T) { content := []byte("dummy1") oid := storeObjectInRepo(t, repo.ID, &content) - defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) + defer git_model.RemoveLFSMetaObjectByOid(t.Context(), repo.ID, oid) session := loginUser(t, "user2") @@ -258,7 +257,7 @@ func TestAPILFSBatch(t *testing.T) { content := []byte("dummy0") storeObjectInRepo(t, repo2.ID, &content) - meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(t.Context(), repo.ID, p.Oid) assert.Nil(t, meta) assert.Equal(t, git_model.ErrLFSObjectNotExist, err) @@ -273,7 +272,7 @@ func TestAPILFSBatch(t *testing.T) { assert.Nil(t, br.Objects[0].Error) assert.Empty(t, br.Objects[0].Actions) - meta, err = git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) + meta, err = git_model.GetLFSMetaObjectByOid(t.Context(), repo.ID, p.Oid) assert.NoError(t, err) assert.NotNil(t, meta) @@ -334,7 +333,7 @@ func TestAPILFSUpload(t *testing.T) { content := []byte("dummy3") oid := storeObjectInRepo(t, repo.ID, &content) - defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) + defer git_model.RemoveLFSMetaObjectByOid(t.Context(), repo.ID, oid) session := loginUser(t, "user2") @@ -362,7 +361,7 @@ func TestAPILFSUpload(t *testing.T) { err = contentStore.Put(p, bytes.NewReader([]byte("dummy5"))) assert.NoError(t, err) - meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(t.Context(), repo.ID, p.Oid) assert.Nil(t, meta) assert.Equal(t, git_model.ErrLFSObjectNotExist, err) @@ -375,7 +374,7 @@ func TestAPILFSUpload(t *testing.T) { req := newRequest(t, p, "dummy5") session.MakeRequest(t, req, http.StatusOK) - meta, err = git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) + meta, err = git_model.GetLFSMetaObjectByOid(t.Context(), repo.ID, p.Oid) assert.NoError(t, err) assert.NotNil(t, meta) }) @@ -423,7 +422,7 @@ func TestAPILFSUpload(t *testing.T) { assert.NoError(t, err) assert.True(t, exist) - meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) + meta, err := git_model.GetLFSMetaObjectByOid(t.Context(), repo.ID, p.Oid) assert.NoError(t, err) assert.NotNil(t, meta) }) @@ -438,7 +437,7 @@ func TestAPILFSVerify(t *testing.T) { content := []byte("dummy3") oid := storeObjectInRepo(t, repo.ID, &content) - defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) + defer git_model.RemoveLFSMetaObjectByOid(t.Context(), repo.ID, oid) session := loginUser(t, "user2") diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index a2c3a467c6..1478cb9bff 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -10,7 +10,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" access_model "code.gitea.io/gitea/models/perm/access" repo_model "code.gitea.io/gitea/models/repo" unit_model "code.gitea.io/gitea/models/unit" @@ -223,7 +222,7 @@ func TestAPISearchRepo(t *testing.T) { assert.Len(t, repoNames, expected.count) for _, repo := range body.Data { r := getRepo(t, repo.ID) - hasAccess, err := access_model.HasAnyUnitAccess(db.DefaultContext, userID, r) + hasAccess, err := access_model.HasAnyUnitAccess(t.Context(), userID, r) assert.NoError(t, err, "Error when checking if User: %d has access to %s: %v", userID, repo.FullName, err) assert.True(t, hasAccess, "User: %d does not have access to %s", userID, repo.FullName) @@ -337,10 +336,10 @@ func TestAPIOrgReposWithCodeUnitDisabled(t *testing.T) { var units []unit_model.Type units = append(units, unit_model.TypeCode) - err := repo_service.UpdateRepositoryUnits(db.DefaultContext, repo21, nil, units) + err := repo_service.UpdateRepositoryUnits(t.Context(), repo21, nil, units) assert.NoError(t, err, "should have been able to delete code repository unit") - assert.False(t, repo21.UnitEnabled(db.DefaultContext, unit_model.TypeCode)) + assert.False(t, repo21.UnitEnabled(t.Context(), unit_model.TypeCode)) session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadOrganization) @@ -429,7 +428,7 @@ func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) { httpContext.Reponame = "repo-tmp-17" t.Run("CreateRepo", doAPICreateRepository(httpContext, false)) - user, err := user_model.GetUserByName(db.DefaultContext, httpContext.Username) + user, err := user_model.GetUserByName(t.Context(), httpContext.Username) assert.NoError(t, err) userID := user.ID @@ -586,7 +585,7 @@ func TestAPIRepoTransfer(t *testing.T) { // cleanup repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: apiRepo.ID}) - _ = repo_service.DeleteRepositoryDirectly(db.DefaultContext, repo.ID) + _ = repo_service.DeleteRepositoryDirectly(t.Context(), repo.ID) } func transfer(t *testing.T) *repo_model.Repository { diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index e54203ed50..8c3c31b2bf 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -10,7 +10,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/perm" "code.gitea.io/gitea/models/repo" @@ -42,7 +41,7 @@ func TestAPITeam(t *testing.T) { DecodeJSON(t, resp, &apiTeam) assert.Equal(t, team.ID, apiTeam.ID) assert.Equal(t, team.Name, apiTeam.Name) - assert.Equal(t, convert.ToOrganization(db.DefaultContext, org), apiTeam.Organization) + assert.Equal(t, convert.ToOrganization(t.Context(), org), apiTeam.Organization) // non team member user will not access the teams details teamUser2 := unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{ID: 3}) @@ -119,7 +118,7 @@ func TestAPITeam(t *testing.T) { // Read team. teamRead := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, teamRead.LoadUnits(db.DefaultContext)) + assert.NoError(t, teamRead.LoadUnits(t.Context())) req = NewRequestf(t, "GET", "/api/v1/teams/%d", teamID). AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) @@ -195,7 +194,7 @@ func TestAPITeam(t *testing.T) { resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) - assert.NoError(t, teamRead.LoadUnits(db.DefaultContext)) + assert.NoError(t, teamRead.LoadUnits(t.Context())) checkTeamResponse(t, "ReadTeam2", &apiTeam, teamRead.Name, *teamToEditDesc.Description, teamRead.IncludesAllRepositories, teamRead.AccessMode.ToString(), teamRead.GetUnitNames(), teamRead.GetUnitsMap()) @@ -257,8 +256,8 @@ func checkTeamResponse(t *testing.T, testName string, apiTeam *api.Team, name, d func checkTeamBean(t *testing.T, id int64, name, description string, includesAllRepositories bool, permission string, units []string, unitsMap map[string]string) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: id}) - assert.NoError(t, team.LoadUnits(db.DefaultContext), "LoadUnits") - apiTeam, err := convert.ToTeam(db.DefaultContext, team) + assert.NoError(t, team.LoadUnits(t.Context()), "LoadUnits") + apiTeam, err := convert.ToTeam(t.Context(), team) assert.NoError(t, err) checkTeamResponse(t, fmt.Sprintf("checkTeamBean/%s_%s", name, description), apiTeam, name, description, includesAllRepositories, permission, units, unitsMap) } diff --git a/tests/integration/api_team_user_test.go b/tests/integration/api_team_user_test.go index cbbbe00a9e..39c9616eae 100644 --- a/tests/integration/api_team_user_test.go +++ b/tests/integration/api_team_user_test.go @@ -9,7 +9,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" @@ -38,7 +37,7 @@ func TestAPITeamUser(t *testing.T) { user2.Created = user2.Created.In(time.Local) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"}) - expectedUser := convert.ToUser(db.DefaultContext, user, user) + expectedUser := convert.ToUser(t.Context(), user, user) // test time via unix timestamp assert.Equal(t, expectedUser.LastLogin.Unix(), user2.LastLogin.Unix()) diff --git a/tests/integration/api_twofa_test.go b/tests/integration/api_twofa_test.go index 938feba61a..960b3425f3 100644 --- a/tests/integration/api_twofa_test.go +++ b/tests/integration/api_twofa_test.go @@ -9,7 +9,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/tests" @@ -39,7 +38,7 @@ func TestAPITwoFactor(t *testing.T) { } assert.NoError(t, tfa.SetSecret(otpKey.Secret())) - assert.NoError(t, auth_model.NewTwoFactor(db.DefaultContext, tfa)) + assert.NoError(t, auth_model.NewTwoFactor(t.Context(), tfa)) req = NewRequest(t, "GET", "/api/v1/user"). AddBasicAuth(user.Name) diff --git a/tests/integration/api_user_block_test.go b/tests/integration/api_user_block_test.go index 6f73b089df..b6cec24ecc 100644 --- a/tests/integration/api_user_block_test.go +++ b/tests/integration/api_user_block_test.go @@ -22,7 +22,7 @@ func TestBlockUser(t *testing.T) { defer tests.PrepareTestEnv(t)() countStars := func(t *testing.T, repoOwnerID, starrerID int64) int64 { - count, err := db.Count[repo_model.Repository](db.DefaultContext, &repo_model.StarredReposOptions{ + count, err := db.Count[repo_model.Repository](t.Context(), &repo_model.StarredReposOptions{ StarrerID: starrerID, RepoOwnerID: repoOwnerID, IncludePrivate: true, @@ -32,7 +32,7 @@ func TestBlockUser(t *testing.T) { } countWatches := func(t *testing.T, repoOwnerID, watcherID int64) int64 { - count, err := db.Count[repo_model.Repository](db.DefaultContext, &repo_model.WatchedReposOptions{ + count, err := db.Count[repo_model.Repository](t.Context(), &repo_model.WatchedReposOptions{ WatcherID: watcherID, RepoOwnerID: repoOwnerID, }) @@ -41,7 +41,7 @@ func TestBlockUser(t *testing.T) { } countRepositoryTransfers := func(t *testing.T, senderID, recipientID int64) int64 { - transfers, err := repo_model.GetPendingRepositoryTransfers(db.DefaultContext, &repo_model.PendingRepositoryTransferOptions{ + transfers, err := repo_model.GetPendingRepositoryTransfers(t.Context(), &repo_model.PendingRepositoryTransferOptions{ SenderID: senderID, RecipientID: recipientID, }) @@ -50,7 +50,7 @@ func TestBlockUser(t *testing.T) { } countAssignedIssues := func(t *testing.T, repoOwnerID, assigneeID int64) int64 { - _, count, err := issues_model.GetAssignedIssues(db.DefaultContext, &issues_model.AssignedIssuesOptions{ + _, count, err := issues_model.GetAssignedIssues(t.Context(), &issues_model.AssignedIssuesOptions{ AssigneeID: assigneeID, RepoOwnerID: repoOwnerID, }) @@ -59,7 +59,7 @@ func TestBlockUser(t *testing.T) { } countCollaborations := func(t *testing.T, repoOwnerID, collaboratorID int64) int64 { - count, err := db.Count[repo_model.Collaboration](db.DefaultContext, &repo_model.FindCollaborationOptions{ + count, err := db.Count[repo_model.Collaboration](t.Context(), &repo_model.FindCollaborationOptions{ CollaboratorID: collaboratorID, RepoOwnerID: repoOwnerID, }) diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index 9b8726c6c2..983d397b2b 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -9,7 +9,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" api "code.gitea.io/gitea/modules/structs" @@ -38,7 +37,7 @@ func TestUserOrgs(t *testing.T) { UserName: org17.Name, FullName: org17.FullName, Email: org17.Email, - AvatarURL: org17.AvatarLink(db.DefaultContext), + AvatarURL: org17.AvatarLink(t.Context()), Description: "", Website: "", Location: "", @@ -50,7 +49,7 @@ func TestUserOrgs(t *testing.T) { UserName: org3.Name, FullName: org3.FullName, Email: org3.Email, - AvatarURL: org3.AvatarLink(db.DefaultContext), + AvatarURL: org3.AvatarLink(t.Context()), Description: "", Website: "", Location: "", @@ -62,7 +61,7 @@ func TestUserOrgs(t *testing.T) { UserName: org35.Name, FullName: org35.FullName, Email: org35.Email, - AvatarURL: org35.AvatarLink(db.DefaultContext), + AvatarURL: org35.AvatarLink(t.Context()), Description: "", Website: "", Location: "", @@ -124,7 +123,7 @@ func TestMyOrgs(t *testing.T) { UserName: org17.Name, FullName: org17.FullName, Email: org17.Email, - AvatarURL: org17.AvatarLink(db.DefaultContext), + AvatarURL: org17.AvatarLink(t.Context()), Description: "", Website: "", Location: "", @@ -136,7 +135,7 @@ func TestMyOrgs(t *testing.T) { UserName: org3.Name, FullName: org3.FullName, Email: org3.Email, - AvatarURL: org3.AvatarLink(db.DefaultContext), + AvatarURL: org3.AvatarLink(t.Context()), Description: "", Website: "", Location: "", @@ -148,7 +147,7 @@ func TestMyOrgs(t *testing.T) { UserName: org35.Name, FullName: org35.FullName, Email: org35.Email, - AvatarURL: org35.AvatarLink(db.DefaultContext), + AvatarURL: org35.AvatarLink(t.Context()), Description: "", Website: "", Location: "", diff --git a/tests/integration/auth_ldap_test.go b/tests/integration/auth_ldap_test.go index 24f0c03bed..c8b694d817 100644 --- a/tests/integration/auth_ldap_test.go +++ b/tests/integration/auth_ldap_test.go @@ -243,7 +243,7 @@ func TestLDAPUserSync(t *testing.T) { // Check if users exists for _, gitLDAPUser := range te.gitLDAPUsers { - dbUser, err := user_model.GetUserByName(db.DefaultContext, gitLDAPUser.UserName) + dbUser, err := user_model.GetUserByName(t.Context(), gitLDAPUser.UserName) assert.NoError(t, err) assert.Equal(t, gitLDAPUser.UserName, dbUser.Name) assert.Equal(t, gitLDAPUser.Email, dbUser.Email) @@ -253,7 +253,7 @@ func TestLDAPUserSync(t *testing.T) { // Check if no users exist for _, otherLDAPUser := range te.otherLDAPUsers { - _, err := user_model.GetUserByName(db.DefaultContext, otherLDAPUser.UserName) + _, err := user_model.GetUserByName(t.Context(), otherLDAPUser.UserName) assert.True(t, user_model.IsErrUserNotExist(err)) } } @@ -349,7 +349,7 @@ func TestLDAPUserSyncWithGroupFilter(t *testing.T) { }) ldapConfig := ldapSource.Cfg.(*ldap.Source) ldapConfig.GroupFilter = "(cn=ship_crew)" - require.NoError(t, auth_model.UpdateSource(db.DefaultContext, ldapSource)) + require.NoError(t, auth_model.UpdateSource(t.Context(), ldapSource)) require.NoError(t, auth.SyncExternalUsers(t.Context(), true)) @@ -428,37 +428,37 @@ func TestLDAPGroupTeamSyncAddMember(t *testing.T) { groupTeamMap: `{"cn=ship_crew,ou=people,dc=planetexpress,dc=com":{"org26": ["team11"]},"cn=admin_staff,ou=people,dc=planetexpress,dc=com": {"non-existent": ["non-existent"]}}`, groupTeamMapRemoval: "on", }) - org, err := organization.GetOrgByName(db.DefaultContext, "org26") + org, err := organization.GetOrgByName(t.Context(), "org26") assert.NoError(t, err) - team, err := organization.GetTeam(db.DefaultContext, org.ID, "team11") + team, err := organization.GetTeam(t.Context(), org.ID, "team11") assert.NoError(t, err) require.NoError(t, auth.SyncExternalUsers(t.Context(), true)) for _, gitLDAPUser := range te.gitLDAPUsers { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ Name: gitLDAPUser.UserName, }) - usersOrgs, err := db.Find[organization.Organization](db.DefaultContext, organization.FindOrgOptions{ + usersOrgs, err := db.Find[organization.Organization](t.Context(), organization.FindOrgOptions{ UserID: user.ID, IncludeVisibility: structs.VisibleTypePrivate, }) assert.NoError(t, err) - allOrgTeams, err := organization.GetUserOrgTeams(db.DefaultContext, org.ID, user.ID) + allOrgTeams, err := organization.GetUserOrgTeams(t.Context(), org.ID, user.ID) assert.NoError(t, err) if user.Name == "fry" || user.Name == "leela" || user.Name == "bender" { // assert members of LDAP group "cn=ship_crew" are added to mapped teams assert.Len(t, usersOrgs, 1, "User [%s] should be member of one organization", user.Name) assert.Equal(t, "org26", usersOrgs[0].Name, "Membership should be added to the right organization") - isMember, err := organization.IsTeamMember(db.DefaultContext, usersOrgs[0].ID, team.ID, user.ID) + isMember, err := organization.IsTeamMember(t.Context(), usersOrgs[0].ID, team.ID, user.ID) assert.NoError(t, err) assert.True(t, isMember, "Membership should be added to the right team") - err = org_service.RemoveTeamMember(db.DefaultContext, team, user) + err = org_service.RemoveTeamMember(t.Context(), team, user) assert.NoError(t, err) - err = org_service.RemoveOrgUser(db.DefaultContext, usersOrgs[0], user) + err = org_service.RemoveOrgUser(t.Context(), usersOrgs[0], user) assert.NoError(t, err) } else { // assert members of LDAP group "cn=admin_staff" keep initial team membership since mapped team does not exist assert.Empty(t, usersOrgs, "User should be member of no organization") - isMember, err := organization.IsTeamMember(db.DefaultContext, org.ID, team.ID, user.ID) + isMember, err := organization.IsTeamMember(t.Context(), org.ID, team.ID, user.ID) assert.NoError(t, err) assert.False(t, isMember, "User should no be added to this team") assert.Empty(t, allOrgTeams, "User should not be added to any team") @@ -476,30 +476,30 @@ func TestLDAPGroupTeamSyncRemoveMember(t *testing.T) { groupTeamMap: `{"cn=dispatch,ou=people,dc=planetexpress,dc=com": {"org26": ["team11"]}}`, groupTeamMapRemoval: "on", }) - org, err := organization.GetOrgByName(db.DefaultContext, "org26") + org, err := organization.GetOrgByName(t.Context(), "org26") assert.NoError(t, err) - team, err := organization.GetTeam(db.DefaultContext, org.ID, "team11") + team, err := organization.GetTeam(t.Context(), org.ID, "team11") assert.NoError(t, err) loginUserWithPassword(t, te.gitLDAPUsers[0].UserName, te.gitLDAPUsers[0].Password) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ Name: te.gitLDAPUsers[0].UserName, }) - err = organization.AddOrgUser(db.DefaultContext, org.ID, user.ID) + err = organization.AddOrgUser(t.Context(), org.ID, user.ID) assert.NoError(t, err) - err = org_service.AddTeamMember(db.DefaultContext, team, user) + err = org_service.AddTeamMember(t.Context(), team, user) assert.NoError(t, err) - isMember, err := organization.IsOrganizationMember(db.DefaultContext, org.ID, user.ID) + isMember, err := organization.IsOrganizationMember(t.Context(), org.ID, user.ID) assert.NoError(t, err) assert.True(t, isMember, "User should be member of this organization") - isMember, err = organization.IsTeamMember(db.DefaultContext, org.ID, team.ID, user.ID) + isMember, err = organization.IsTeamMember(t.Context(), org.ID, team.ID, user.ID) assert.NoError(t, err) assert.True(t, isMember, "User should be member of this team") // assert team member "professor" gets removed from org26 team11 loginUserWithPassword(t, te.gitLDAPUsers[0].UserName, te.gitLDAPUsers[0].Password) - isMember, err = organization.IsOrganizationMember(db.DefaultContext, org.ID, user.ID) + isMember, err = organization.IsOrganizationMember(t.Context(), org.ID, user.ID) assert.NoError(t, err) assert.False(t, isMember, "User membership should have been removed from organization") - isMember, err = organization.IsTeamMember(db.DefaultContext, org.ID, team.ID, user.ID) + isMember, err = organization.IsTeamMember(t.Context(), org.ID, team.ID, user.ID) assert.NoError(t, err) assert.False(t, isMember, "User membership should have been removed from team") } diff --git a/tests/integration/compare_test.go b/tests/integration/compare_test.go index 0648777fed..a3cb538d5b 100644 --- a/tests/integration/compare_test.go +++ b/tests/integration/compare_test.go @@ -10,7 +10,6 @@ import ( "strings" "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/test" @@ -128,7 +127,7 @@ func TestCompareBranches(t *testing.T) { func TestCompareCodeExpand(t *testing.T) { onGiteaRun(t, func(t *testing.T, u *url.URL) { user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - repo, err := repo_service.CreateRepositoryDirectly(db.DefaultContext, user1, user1, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepositoryDirectly(t.Context(), user1, user1, repo_service.CreateRepoOptions{ Name: "test_blob_excerpt", Readme: "Default", AutoInit: true, diff --git a/tests/integration/db_collation_test.go b/tests/integration/db_collation_test.go index 339bfce71c..4f922f8a39 100644 --- a/tests/integration/db_collation_test.go +++ b/tests/integration/db_collation_test.go @@ -7,11 +7,11 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" - "xorm.io/xorm" ) type TestCollationTbl struct { @@ -20,7 +20,7 @@ type TestCollationTbl struct { } func TestDatabaseCollation(t *testing.T) { - x := db.GetEngine(db.DefaultContext).(*xorm.Engine) + x := unittest.GetXORMEngine() // all created tables should use case-sensitive collation by default _, _ = x.Exec("DROP TABLE IF EXISTS test_collation_tbl") diff --git a/tests/integration/empty_repo_test.go b/tests/integration/empty_repo_test.go index 127df5919d..4901488122 100644 --- a/tests/integration/empty_repo_test.go +++ b/tests/integration/empty_repo_test.go @@ -111,7 +111,7 @@ func TestEmptyRepoAddFile(t *testing.T) { user30EmptyRepo.IsEmpty = isEmpty user30EmptyRepo.Status = util.Iif(isBroken, repo_model.RepositoryBroken, repo_model.RepositoryReady) user30EmptyRepo.DefaultBranch = "no-such" - _, err := db.GetEngine(db.DefaultContext).ID(user30EmptyRepo.ID).Cols("is_empty", "status", "default_branch").Update(user30EmptyRepo) + _, err := db.GetEngine(t.Context()).ID(user30EmptyRepo.ID).Cols("is_empty", "status", "default_branch").Update(user30EmptyRepo) require.NoError(t, err) user30EmptyRepo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: 30, Name: "empty"}) assert.Equal(t, isEmpty, user30EmptyRepo.IsEmpty) diff --git a/tests/integration/eventsource_test.go b/tests/integration/eventsource_test.go index 2ef4218977..a13a8c346a 100644 --- a/tests/integration/eventsource_test.go +++ b/tests/integration/eventsource_test.go @@ -11,7 +11,6 @@ import ( activities_model "code.gitea.io/gitea/models/activities" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -58,7 +57,7 @@ func TestEventSourceManagerRun(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) - assert.NoError(t, thread5.LoadAttributes(db.DefaultContext)) + assert.NoError(t, thread5.LoadAttributes(t.Context())) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteNotification, auth_model.AccessTokenScopeWriteRepository) diff --git a/tests/integration/git_general_test.go b/tests/integration/git_general_test.go index 2bc3dbd21b..1f6d3c940f 100644 --- a/tests/integration/git_general_test.go +++ b/tests/integration/git_general_test.go @@ -22,7 +22,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" issues_model "code.gitea.io/gitea/models/issues" "code.gitea.io/gitea/models/perm" repo_model "code.gitea.io/gitea/models/repo" @@ -516,7 +515,7 @@ func doProtectBranchExt(ctx APITestContext, ruleName string, opts doProtectBranc } if opts.UserToWhitelistPush != "" { - user, err := user_model.GetUserByName(db.DefaultContext, opts.UserToWhitelistPush) + user, err := user_model.GetUserByName(t.Context(), opts.UserToWhitelistPush) assert.NoError(t, err) formData["whitelist_users"] = strconv.FormatInt(user.ID, 10) formData["enable_push"] = "whitelist" @@ -524,7 +523,7 @@ func doProtectBranchExt(ctx APITestContext, ruleName string, opts doProtectBranc } if opts.UserToWhitelistForcePush != "" { - user, err := user_model.GetUserByName(db.DefaultContext, opts.UserToWhitelistForcePush) + user, err := user_model.GetUserByName(t.Context(), opts.UserToWhitelistForcePush) assert.NoError(t, err) formData["force_push_allowlist_users"] = strconv.FormatInt(user.ID, 10) formData["enable_force_push"] = "whitelist" @@ -675,7 +674,7 @@ func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) { t.Run("SuccessfullyPushAndCreateTestRepository", doGitPushTestRepository(tmpDir, "origin", "master")) // Finally, fetch repo from database and ensure the correct repository has been created - repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, ctx.Username, ctx.Reponame) + repo, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), ctx.Username, ctx.Reponame) assert.NoError(t, err) assert.False(t, repo.IsEmpty) assert.True(t, repo.IsPrivate) @@ -815,7 +814,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string pr1, pr2 *issues_model.PullRequest commit string ) - repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, ctx.Username, ctx.Reponame) + repo, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), ctx.Username, ctx.Reponame) require.NoError(t, err) pullNum := unittest.GetCount(t, &issues_model.PullRequest{}) diff --git a/tests/integration/git_misc_test.go b/tests/integration/git_misc_test.go index 24cc0e8659..eb039c7c1c 100644 --- a/tests/integration/git_misc_test.go +++ b/tests/integration/git_misc_test.go @@ -11,7 +11,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -29,7 +28,7 @@ func TestDataAsyncDoubleRead_Issue29101(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) testContent := bytes.Repeat([]byte{'a'}, 10000) - resp, err := files_service.ChangeRepoFiles(db.DefaultContext, repo, user, &files_service.ChangeRepoFilesOptions{ + resp, err := files_service.ChangeRepoFiles(t.Context(), repo, user, &files_service.ChangeRepoFilesOptions{ Files: []*files_service.ChangeRepoFile{ { Operation: "create", @@ -44,7 +43,7 @@ func TestDataAsyncDoubleRead_Issue29101(t *testing.T) { sha := resp.Commit.SHA - gitRepo, err := gitrepo.OpenRepository(db.DefaultContext, repo) + gitRepo, err := gitrepo.OpenRepository(t.Context(), repo) assert.NoError(t, err) commit, err := gitRepo.GetCommit(sha) @@ -109,7 +108,7 @@ func TestAgitPullPush(t *testing.T) { // check pull request exist pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{BaseRepoID: 1, Flow: issues_model.PullRequestFlowAGit, HeadBranch: "user2/test-agit-push"}) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + assert.NoError(t, pr.LoadIssue(t.Context())) assert.Equal(t, "test-title", pr.Issue.Title) assert.Equal(t, "test-description", pr.Issue.Content) @@ -168,7 +167,7 @@ func TestAgitReviewStaleness(t *testing.T) { Flow: issues_model.PullRequestFlowAGit, HeadBranch: "user2/test-agit-review", }) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + assert.NoError(t, pr.LoadIssue(t.Context())) // Get initial commit ID for the review initialCommitID := pr.HeadCommitID @@ -176,7 +175,7 @@ func TestAgitReviewStaleness(t *testing.T) { // Create a review on the PR (as user1 reviewing user2's PR) reviewer := 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{ Type: issues_model.ReviewTypeApprove, Reviewer: reviewer, Issue: pr.Issue, @@ -188,7 +187,7 @@ func TestAgitReviewStaleness(t *testing.T) { assert.False(t, review.Stale, "New review should not be stale") // Verify review exists and is not stale - reviews, err := issues_model.FindReviews(db.DefaultContext, issues_model.FindReviewOptions{ + reviews, err := issues_model.FindReviews(t.Context(), issues_model.FindReviewOptions{ IssueID: pr.IssueID, }) assert.NoError(t, err) @@ -209,11 +208,11 @@ func TestAgitReviewStaleness(t *testing.T) { Flow: issues_model.PullRequestFlowAGit, HeadBranch: "user2/test-agit-review", }) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + assert.NoError(t, pr.LoadIssue(t.Context())) // For AGit PRs, HeadCommitID must be loaded from git references baseRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - baseGitRepo, err := gitrepo.OpenRepository(db.DefaultContext, baseRepo) + baseGitRepo, err := gitrepo.OpenRepository(t.Context(), baseRepo) assert.NoError(t, err) defer baseGitRepo.Close() @@ -225,7 +224,7 @@ func TestAgitReviewStaleness(t *testing.T) { assert.NotEqual(t, initialCommitID, updatedCommitID, "PR should have new commit ID after update") // Check that the review is now marked as stale - reviews, err = issues_model.FindReviews(db.DefaultContext, issues_model.FindReviewOptions{ + reviews, err = issues_model.FindReviews(t.Context(), issues_model.FindReviewOptions{ IssueID: pr.IssueID, }) assert.NoError(t, err) diff --git a/tests/integration/git_push_test.go b/tests/integration/git_push_test.go index e07367bab6..b6ba0136cd 100644 --- a/tests/integration/git_push_test.go +++ b/tests/integration/git_push_test.go @@ -137,7 +137,7 @@ func testGitPush(t *testing.T, u *url.URL) { func runTestGitPush(t *testing.T, u *url.URL, gitOperation func(t *testing.T, gitPath string) (pushed, deleted []string)) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - repo, err := repo_service.CreateRepository(db.DefaultContext, user, user, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user, user, repo_service.CreateRepoOptions{ Name: "repo-to-push", Description: "test git push", AutoInit: false, @@ -169,7 +169,7 @@ func runTestGitPush(t *testing.T, u *url.URL, gitOperation func(t *testing.T, gi pushedBranches, deletedBranches := gitOperation(t, gitPath) dbBranches := make([]*git_model.Branch, 0) - require.NoError(t, db.GetEngine(db.DefaultContext).Where("repo_id=?", repo.ID).Find(&dbBranches)) + require.NoError(t, db.GetEngine(t.Context()).Where("repo_id=?", repo.ID).Find(&dbBranches)) assert.Lenf(t, dbBranches, len(pushedBranches), "mismatched number of branches in db") dbBranchesMap := make(map[string]*git_model.Branch, len(dbBranches)) for _, branch := range dbBranches { @@ -191,7 +191,7 @@ func runTestGitPush(t *testing.T, u *url.URL, gitOperation func(t *testing.T, gi assert.Equal(t, commitID, branch.CommitID) } - require.NoError(t, repo_service.DeleteRepositoryDirectly(db.DefaultContext, repo.ID)) + require.NoError(t, repo_service.DeleteRepositoryDirectly(t.Context(), repo.ID)) } func TestPushPullRefs(t *testing.T) { diff --git a/tests/integration/incoming_email_test.go b/tests/integration/incoming_email_test.go index 6ccf82a9eb..09872fe857 100644 --- a/tests/integration/incoming_email_test.go +++ b/tests/integration/incoming_email_test.go @@ -12,7 +12,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" @@ -44,15 +43,15 @@ func TestIncomingEmail(t *testing.T) { commentPayload, err := incoming_payload.CreateReferencePayload(comment) assert.NoError(t, err) - _, err = incoming_payload.GetReferenceFromPayload(db.DefaultContext, []byte{1, 2, 3}) + _, err = incoming_payload.GetReferenceFromPayload(t.Context(), []byte{1, 2, 3}) assert.Error(t, err) - ref, err := incoming_payload.GetReferenceFromPayload(db.DefaultContext, issuePayload) + ref, err := incoming_payload.GetReferenceFromPayload(t.Context(), issuePayload) assert.NoError(t, err) assert.IsType(t, ref, new(issues_model.Issue)) assert.Equal(t, issue.ID, ref.(*issues_model.Issue).ID) - ref, err = incoming_payload.GetReferenceFromPayload(db.DefaultContext, commentPayload) + ref, err = incoming_payload.GetReferenceFromPayload(t.Context(), commentPayload) assert.NoError(t, err) assert.IsType(t, ref, new(issues_model.Comment)) assert.Equal(t, comment.ID, ref.(*issues_model.Comment).ID) @@ -67,7 +66,7 @@ func TestIncomingEmail(t *testing.T) { assert.NoError(t, err) assert.NotEmpty(t, token) - ht, u, p, err := token_service.ExtractToken(db.DefaultContext, token) + ht, u, p, err := token_service.ExtractToken(t.Context(), token) assert.NoError(t, err) assert.Equal(t, token_service.ReplyHandlerType, ht) assert.Equal(t, user.ID, u.ID) @@ -84,8 +83,8 @@ func TestIncomingEmail(t *testing.T) { payload, err := incoming_payload.CreateReferencePayload(issue) assert.NoError(t, err) - assert.Error(t, handler.Handle(db.DefaultContext, &incoming.MailContent{}, nil, payload)) - assert.NoError(t, handler.Handle(db.DefaultContext, &incoming.MailContent{}, user, payload)) + assert.Error(t, handler.Handle(t.Context(), &incoming.MailContent{}, nil, payload)) + assert.NoError(t, handler.Handle(t.Context(), &incoming.MailContent{}, user, payload)) content := &incoming.MailContent{ Content: "reply by mail", @@ -97,9 +96,9 @@ func TestIncomingEmail(t *testing.T) { }, } - assert.NoError(t, handler.Handle(db.DefaultContext, content, user, payload)) + assert.NoError(t, handler.Handle(t.Context(), content, user, payload)) - comments, err := issues_model.FindComments(db.DefaultContext, &issues_model.FindCommentsOptions{ + comments, err := issues_model.FindComments(t.Context(), &issues_model.FindCommentsOptions{ IssueID: issue.ID, Type: issues_model.CommentTypeComment, }) @@ -108,7 +107,7 @@ func TestIncomingEmail(t *testing.T) { comment := comments[len(comments)-1] assert.Equal(t, user.ID, comment.PosterID) assert.Equal(t, content.Content, comment.Content) - assert.NoError(t, comment.LoadAttachments(db.DefaultContext)) + assert.NoError(t, comment.LoadAttachments(t.Context())) assert.Len(t, comment.Attachments, 1) attachment := comment.Attachments[0] assert.Equal(t, content.Attachments[0].Name, attachment.Name) @@ -135,9 +134,9 @@ func TestIncomingEmail(t *testing.T) { payload, err := incoming_payload.CreateReferencePayload(comment) assert.NoError(t, err) - assert.NoError(t, handler.Handle(db.DefaultContext, content, user, payload)) + assert.NoError(t, handler.Handle(t.Context(), content, user, payload)) - comments, err := issues_model.FindComments(db.DefaultContext, &issues_model.FindCommentsOptions{ + comments, err := issues_model.FindComments(t.Context(), &issues_model.FindCommentsOptions{ IssueID: issue.ID, Type: issues_model.CommentTypeCode, }) @@ -146,7 +145,7 @@ func TestIncomingEmail(t *testing.T) { comment = comments[len(comments)-1] assert.Equal(t, user.ID, comment.PosterID) assert.Equal(t, content.Content, comment.Content) - assert.NoError(t, comment.LoadAttachments(db.DefaultContext)) + assert.NoError(t, comment.LoadAttachments(t.Context())) assert.Len(t, comment.Attachments, 1) attachment := comment.Attachments[0] assert.Equal(t, content.Attachments[0].Name, attachment.Name) @@ -157,7 +156,7 @@ func TestIncomingEmail(t *testing.T) { t.Run("Unsubscribe", func(t *testing.T) { defer tests.PrintCurrentTest(t)() - watching, err := issues_model.CheckIssueWatch(db.DefaultContext, user, issue) + watching, err := issues_model.CheckIssueWatch(t.Context(), user, issue) assert.NoError(t, err) assert.True(t, watching) @@ -170,9 +169,9 @@ func TestIncomingEmail(t *testing.T) { payload, err := incoming_payload.CreateReferencePayload(issue) assert.NoError(t, err) - assert.NoError(t, handler.Handle(db.DefaultContext, content, user, payload)) + assert.NoError(t, handler.Handle(t.Context(), content, user, payload)) - watching, err = issues_model.CheckIssueWatch(db.DefaultContext, user, issue) + watching, err = issues_model.CheckIssueWatch(t.Context(), user, issue) assert.NoError(t, err) assert.False(t, watching) }) @@ -201,7 +200,7 @@ func TestIncomingEmail(t *testing.T) { assert.NoError(t, err) assert.Eventually(t, func() bool { - comments, err := issues_model.FindComments(db.DefaultContext, &issues_model.FindCommentsOptions{ + comments, err := issues_model.FindComments(t.Context(), &issues_model.FindCommentsOptions{ IssueID: issue.ID, Type: issues_model.CommentTypeComment, }) diff --git a/tests/integration/issue_test.go b/tests/integration/issue_test.go index b5dca58357..3b5f1534ef 100644 --- a/tests/integration/issue_test.go +++ b/tests/integration/issue_test.go @@ -14,7 +14,6 @@ import ( "testing" "time" - "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" @@ -646,7 +645,7 @@ func TestGetIssueInfo(t *testing.T) { issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 10}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - assert.NoError(t, issue.LoadAttributes(db.DefaultContext)) + assert.NoError(t, issue.LoadAttributes(t.Context())) assert.Equal(t, int64(1019307200), int64(issue.DeadlineUnix)) assert.Equal(t, api.StateOpen, issue.State()) @@ -671,7 +670,7 @@ func TestUpdateIssueDeadline(t *testing.T) { issueBefore := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 10}) repoBefore := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issueBefore.RepoID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) - assert.NoError(t, issueBefore.LoadAttributes(db.DefaultContext)) + assert.NoError(t, issueBefore.LoadAttributes(t.Context())) assert.Equal(t, "2002-04-20", issueBefore.DeadlineUnix.FormatDate()) assert.Equal(t, api.StateOpen, issueBefore.State()) diff --git a/tests/integration/lfs_getobject_test.go b/tests/integration/lfs_getobject_test.go index a87f38be8a..5f13229ba2 100644 --- a/tests/integration/lfs_getobject_test.go +++ b/tests/integration/lfs_getobject_test.go @@ -12,7 +12,6 @@ import ( "testing" "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/modules/json" @@ -29,7 +28,7 @@ func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string pointer, err := lfs.GeneratePointer(bytes.NewReader(*content)) assert.NoError(t, err) - _, err = git_model.NewLFSMetaObject(db.DefaultContext, repositoryID, pointer) + _, err = git_model.NewLFSMetaObject(t.Context(), repositoryID, pointer) assert.NoError(t, err) contentStore := lfs.NewContentStore() exist, err := contentStore.Exists(pointer) @@ -42,10 +41,10 @@ func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string } func storeAndGetLfsToken(t *testing.T, content *[]byte, extraHeader *http.Header, expectedStatus int, ts ...auth.AccessTokenScope) *httptest.ResponseRecorder { - repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") + repo, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), "user2", "repo1") assert.NoError(t, err) oid := storeObjectInRepo(t, repo.ID, content) - defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) + defer git_model.RemoveLFSMetaObjectByOid(t.Context(), repo.ID, oid) token := getUserToken(t, "user2", ts...) @@ -67,10 +66,10 @@ func storeAndGetLfsToken(t *testing.T, content *[]byte, extraHeader *http.Header } func storeAndGetLfs(t *testing.T, content *[]byte, extraHeader *http.Header, expectedStatus int) *httptest.ResponseRecorder { - repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") + repo, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), "user2", "repo1") assert.NoError(t, err) oid := storeObjectInRepo(t, repo.ID, content) - defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) + defer git_model.RemoveLFSMetaObjectByOid(t.Context(), repo.ID, oid) session := loginUser(t, "user2") diff --git a/tests/integration/lfs_view_test.go b/tests/integration/lfs_view_test.go index c26ece22be..3140f491c9 100644 --- a/tests/integration/lfs_view_test.go +++ b/tests/integration/lfs_view_test.go @@ -103,7 +103,7 @@ func TestLFSRender(t *testing.T) { assert.Contains(t, content, "Testing documents in LFS") // then make it disappear - assert.NoError(t, db.TruncateBeans(db.DefaultContext, &git.LFSMetaObject{})) + assert.NoError(t, db.TruncateBeans(t.Context(), &git.LFSMetaObject{})) req = NewRequest(t, "GET", "/user2/lfs/src/branch/master/CONTRIBUTING.md") resp = session.MakeRequest(t, req, http.StatusOK) content = NewHTMLParser(t, resp.Body).Find("div.file-view").Text() diff --git a/tests/integration/linguist_test.go b/tests/integration/linguist_test.go index d587c54dcb..2c4c74d2a7 100644 --- a/tests/integration/linguist_test.go +++ b/tests/integration/linguist_test.go @@ -10,7 +10,6 @@ import ( "testing" "time" - "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" @@ -220,7 +219,7 @@ func TestLinguist(t *testing.T) { for i, c := range cases { t.Run("Case-"+strconv.Itoa(i), func(t *testing.T) { defer tests.PrintCurrentTest(t)() - repo, err := repo_service.CreateRepository(db.DefaultContext, user, user, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepository(t.Context(), user, user, repo_service.CreateRepoOptions{ Name: "linguist-test-" + strconv.Itoa(i), }) assert.NoError(t, err) @@ -246,7 +245,7 @@ func TestLinguist(t *testing.T) { assert.NoError(t, stats.UpdateRepoIndexer(repo)) assert.NoError(t, queue.GetManager().FlushAll(t.Context(), 10*time.Second)) - stats, err := repo_model.GetTopLanguageStats(db.DefaultContext, repo, len(c.FilesToAdd)) + stats, err := repo_model.GetTopLanguageStats(t.Context(), repo, len(c.FilesToAdd)) assert.NoError(t, err) languages := make([]string, 0, len(stats)) diff --git a/tests/integration/migrate_test.go b/tests/integration/migrate_test.go index a89dc8b85c..d67b2db5d0 100644 --- a/tests/integration/migrate_test.go +++ b/tests/integration/migrate_test.go @@ -13,7 +13,6 @@ import ( "testing" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -110,6 +109,6 @@ func TestMigrateGiteaForm(t *testing.T) { func Test_UpdateCommentsMigrationsByType(t *testing.T) { assert.NoError(t, unittest.PrepareTestDatabase()) - err := issues_model.UpdateCommentsMigrationsByType(db.DefaultContext, structs.GithubService, "1", 1) + err := issues_model.UpdateCommentsMigrationsByType(t.Context(), structs.GithubService, "1", 1) assert.NoError(t, err) } diff --git a/tests/integration/mirror_pull_test.go b/tests/integration/mirror_pull_test.go index b75b51634e..7902dc10cb 100644 --- a/tests/integration/mirror_pull_test.go +++ b/tests/integration/mirror_pull_test.go @@ -69,7 +69,7 @@ func TestMirrorPull(t *testing.T) { IncludeTags: true, RepoID: mirrorRepo.ID, } - initCount, err := db.Count[repo_model.Release](db.DefaultContext, findOptions) + initCount, err := db.Count[repo_model.Release](t.Context(), findOptions) assert.NoError(t, err) assert.Zero(t, initCount) // no sync yet, so even though there is a tag in source repo, the mirror's release table is still empty @@ -96,18 +96,18 @@ func TestMirrorPull(t *testing.T) { // actually there is a tag in the source repo, so after "sync", that tag will also come into the mirror initCount++ - count, err := db.Count[repo_model.Release](db.DefaultContext, findOptions) + count, err := db.Count[repo_model.Release](t.Context(), findOptions) assert.NoError(t, err) assert.Equal(t, initCount+1, count) - release, err := repo_model.GetRelease(db.DefaultContext, repo.ID, "v0.2") + release, err := repo_model.GetRelease(t.Context(), repo.ID, "v0.2") assert.NoError(t, err) assert.NoError(t, release_service.DeleteReleaseByID(ctx, repo, release, user, true)) ok = mirror_service.SyncPullMirror(ctx, mirrorRepo.ID) assert.True(t, ok) - count, err = db.Count[repo_model.Release](db.DefaultContext, findOptions) + count, err = db.Count[repo_model.Release](t.Context(), findOptions) assert.NoError(t, err) assert.Equal(t, initCount, count) } diff --git a/tests/integration/mirror_push_test.go b/tests/integration/mirror_push_test.go index 4b8abaa89f..c468228b82 100644 --- a/tests/integration/mirror_push_test.go +++ b/tests/integration/mirror_push_test.go @@ -33,11 +33,11 @@ func testMirrorPush(t *testing.T, u *url.URL) { setting.Migrations.AllowLocalNetworks = true assert.NoError(t, migrations.Init()) - _ = db.TruncateBeans(db.DefaultContext, &repo_model.PushMirror{}) + _ = db.TruncateBeans(t.Context(), &repo_model.PushMirror{}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) srcRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - mirrorRepo, err := repo_service.CreateRepositoryDirectly(db.DefaultContext, user, user, repo_service.CreateRepoOptions{ + mirrorRepo, err := repo_service.CreateRepositoryDirectly(t.Context(), user, user, repo_service.CreateRepoOptions{ Name: "test-push-mirror", }, true) assert.NoError(t, err) @@ -47,7 +47,7 @@ func testMirrorPush(t *testing.T, u *url.URL) { pushMirrorURL := fmt.Sprintf("%s%s/%s", u.String(), url.PathEscape(user.Name), url.PathEscape(mirrorRepo.Name)) testCreatePushMirror(t, session, user.Name, srcRepo.Name, pushMirrorURL, user.LowerName, userPassword, "0") - mirrors, _, err := repo_model.GetPushMirrorsByRepoID(db.DefaultContext, srcRepo.ID, db.ListOptions{}) + mirrors, _, err := repo_model.GetPushMirrorsByRepoID(t.Context(), srcRepo.ID, db.ListOptions{}) assert.NoError(t, err) assert.Len(t, mirrors, 1) @@ -72,7 +72,7 @@ func testMirrorPush(t *testing.T, u *url.URL) { // Cleanup assert.True(t, doRemovePushMirror(t, session, user.Name, srcRepo.Name, mirrors[0].ID)) - mirrors, _, err = repo_model.GetPushMirrorsByRepoID(db.DefaultContext, srcRepo.ID, db.ListOptions{}) + mirrors, _, err = repo_model.GetPushMirrorsByRepoID(t.Context(), srcRepo.ID, db.ListOptions{}) assert.NoError(t, err) assert.Empty(t, mirrors) } @@ -124,7 +124,7 @@ func TestRepoSettingPushMirrorUpdate(t *testing.T) { repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) testCreatePushMirror(t, session, "user2", "repo2", "https://127.0.0.1/user1/repo1.git", "", "", "24h") - pushMirrors, cnt, err := repo_model.GetPushMirrorsByRepoID(db.DefaultContext, repo2.ID, db.ListOptions{}) + pushMirrors, cnt, err := repo_model.GetPushMirrorsByRepoID(t.Context(), repo2.ID, db.ListOptions{}) assert.NoError(t, err) assert.EqualValues(t, 1, cnt) assert.Equal(t, 24*time.Hour, pushMirrors[0].Interval) diff --git a/tests/integration/oauth_test.go b/tests/integration/oauth_test.go index a2247801f7..eab95ba688 100644 --- a/tests/integration/oauth_test.go +++ b/tests/integration/oauth_test.go @@ -526,7 +526,7 @@ func TestOAuth_GrantScopesReadUserFailRepos(t *testing.T) { Scope: "openid read:user", } - err := db.Insert(db.DefaultContext, grant) + err := db.Insert(t.Context(), grant) require.NoError(t, err) assert.Contains(t, grant.Scope, "openid read:user") @@ -607,7 +607,7 @@ func TestOAuth_GrantScopesReadRepositoryFailOrganization(t *testing.T) { Scope: "openid read:user read:repository", } - err := db.Insert(db.DefaultContext, grant) + err := db.Insert(t.Context(), grant) require.NoError(t, err) assert.Contains(t, grant.Scope, "openid read:user read:repository") @@ -747,7 +747,7 @@ func TestOAuth_GrantScopesClaimPublicOnlyGroups(t *testing.T) { Scope: "openid groups read:user public-only", } - err := db.Insert(db.DefaultContext, grant) + err := db.Insert(t.Context(), grant) require.NoError(t, err) assert.ElementsMatch(t, []string{"openid", "groups", "read:user", "public-only"}, strings.Split(grant.Scope, " ")) @@ -848,7 +848,7 @@ func TestOAuth_GrantScopesClaimAllGroups(t *testing.T) { Scope: "openid groups", } - err := db.Insert(db.DefaultContext, grant) + err := db.Insert(t.Context(), grant) require.NoError(t, err) assert.ElementsMatch(t, []string{"openid", "groups"}, strings.Split(grant.Scope, " ")) @@ -940,7 +940,7 @@ func testOAuth2WellKnown(t *testing.T) { func addOAuth2Source(t *testing.T, authName string, cfg oauth2.Source) { cfg.Provider = util.IfZero(cfg.Provider, "gitea") - err := auth_model.CreateSource(db.DefaultContext, &auth_model.Source{ + err := auth_model.CreateSource(t.Context(), &auth_model.Source{ Type: auth_model.OAuth2, Name: authName, IsActive: true, diff --git a/tests/integration/org_count_test.go b/tests/integration/org_count_test.go index c48008e627..6a2cf53ed4 100644 --- a/tests/integration/org_count_test.go +++ b/tests/integration/org_count_test.go @@ -119,7 +119,7 @@ func doCheckOrgCounts(username string, orgCounts map[string]int, strict bool, ca Name: username, }) - orgs, err := db.Find[organization.Organization](db.DefaultContext, organization.FindOrgOptions{ + orgs, err := db.Find[organization.Organization](t.Context(), organization.FindOrgOptions{ UserID: user.ID, IncludeVisibility: api.VisibleTypePrivate, }) diff --git a/tests/integration/org_team_invite_test.go b/tests/integration/org_team_invite_test.go index 7444980ea8..b51b8f43ee 100644 --- a/tests/integration/org_team_invite_test.go +++ b/tests/integration/org_team_invite_test.go @@ -10,7 +10,6 @@ import ( "strings" "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" @@ -33,7 +32,7 @@ func TestOrgTeamEmailInvite(t *testing.T) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) - isMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) + isMember, err := organization.IsTeamMember(t.Context(), team.OrgID, team.ID, user.ID) assert.NoError(t, err) assert.False(t, isMember) @@ -51,7 +50,7 @@ func TestOrgTeamEmailInvite(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) // get the invite token - invites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID) + invites, err := organization.GetInvitesByTeamID(t.Context(), team.ID) assert.NoError(t, err) assert.Len(t, invites, 1) @@ -67,7 +66,7 @@ func TestOrgTeamEmailInvite(t *testing.T) { req = NewRequest(t, "GET", test.RedirectURL(resp)) session.MakeRequest(t, req, http.StatusOK) - isMember, err = organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) + isMember, err = organization.IsTeamMember(t.Context(), team.OrgID, team.ID, user.ID) assert.NoError(t, err) assert.True(t, isMember) } @@ -85,7 +84,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) - isMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) + isMember, err := organization.IsTeamMember(t.Context(), team.OrgID, team.ID, user.ID) assert.NoError(t, err) assert.False(t, isMember) @@ -103,7 +102,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) // get the invite token - invites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID) + invites, err := organization.GetInvitesByTeamID(t.Context(), team.ID) assert.NoError(t, err) assert.Len(t, invites, 1) @@ -143,7 +142,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) { req = NewRequest(t, "GET", test.RedirectURL(resp)) session.MakeRequest(t, req, http.StatusOK) - isMember, err = organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) + isMember, err = organization.IsTeamMember(t.Context(), team.OrgID, team.ID, user.ID) assert.NoError(t, err) assert.True(t, isMember) } @@ -174,7 +173,7 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) // get the invite token - invites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID) + invites, err := organization.GetInvitesByTeamID(t.Context(), team.ID) assert.NoError(t, err) assert.Len(t, invites, 1) @@ -217,10 +216,10 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) // get the new user - newUser, err := user_model.GetUserByName(db.DefaultContext, "doesnotexist") + newUser, err := user_model.GetUserByName(t.Context(), "doesnotexist") assert.NoError(t, err) - isMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, newUser.ID) + isMember, err := organization.IsTeamMember(t.Context(), team.OrgID, team.ID, newUser.ID) assert.NoError(t, err) assert.True(t, isMember) } @@ -253,7 +252,7 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) // get the invite token - invites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID) + invites, err := organization.GetInvitesByTeamID(t.Context(), team.ID) assert.NoError(t, err) assert.Len(t, invites, 1) @@ -271,7 +270,7 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) { }) session.MakeRequest(t, req, http.StatusOK) - user, err := user_model.GetUserByName(db.DefaultContext, "doesnotexist") + user, err := user_model.GetUserByName(t.Context(), "doesnotexist") assert.NoError(t, err) activationCode := user_model.GenerateUserTimeLimitCode(&user_model.TimeLimitCodeOptions{Purpose: user_model.TimeLimitCodeActivateAccount}, user) @@ -291,7 +290,7 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) { req = NewRequest(t, "GET", test.RedirectURL(resp)) session.MakeRequest(t, req, http.StatusOK) - isMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) + isMember, err := organization.IsTeamMember(t.Context(), team.OrgID, team.ID, user.ID) assert.NoError(t, err) assert.True(t, isMember) } @@ -311,7 +310,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) - isMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) + isMember, err := organization.IsTeamMember(t.Context(), team.OrgID, team.ID, user.ID) assert.NoError(t, err) assert.False(t, isMember) @@ -329,7 +328,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) // get the invite token - invites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID) + invites, err := organization.GetInvitesByTeamID(t.Context(), team.ID) assert.NoError(t, err) assert.Len(t, invites, 1) @@ -350,7 +349,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) { req = NewRequest(t, "GET", test.RedirectURL(resp)) session.MakeRequest(t, req, http.StatusOK) - isMember, err = organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) + isMember, err = organization.IsTeamMember(t.Context(), team.OrgID, team.ID, user.ID) assert.NoError(t, err) assert.True(t, isMember) } diff --git a/tests/integration/org_worktime_test.go b/tests/integration/org_worktime_test.go index fb5216be8d..9d2280ac7e 100644 --- a/tests/integration/org_worktime_test.go +++ b/tests/integration/org_worktime_test.go @@ -6,7 +6,6 @@ package integration_test import ( "testing" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/unittest" @@ -87,9 +86,9 @@ func testTimesByRepos(t *testing.T) { // Run test kases for _, kase := range kases { t.Run(kase.name, func(t *testing.T) { - org, err := organization.GetOrgByID(db.DefaultContext, kase.orgname) + org, err := organization.GetOrgByID(t.Context(), kase.orgname) assert.NoError(t, err) - results, err := organization.GetWorktimeByRepos(org, kase.unixfrom, kase.unixto) + results, err := organization.GetWorktimeByRepos(t.Context(), org, kase.unixfrom, kase.unixto) assert.NoError(t, err) assert.Equal(t, kase.expected, results) }) @@ -191,9 +190,9 @@ func testTimesByMilestones(t *testing.T) { // Run test kases for _, kase := range kases { t.Run(kase.name, func(t *testing.T) { - org, err := organization.GetOrgByID(db.DefaultContext, kase.orgname) + org, err := organization.GetOrgByID(t.Context(), kase.orgname) require.NoError(t, err) - results, err := organization.GetWorktimeByMilestones(org, kase.unixfrom, kase.unixto) + results, err := organization.GetWorktimeByMilestones(t.Context(), org, kase.unixfrom, kase.unixto) if assert.NoError(t, err) { assert.Equal(t, kase.expected, results) } @@ -275,9 +274,9 @@ func testTimesByMembers(t *testing.T) { // Run test kases for _, kase := range kases { t.Run(kase.name, func(t *testing.T) { - org, err := organization.GetOrgByID(db.DefaultContext, kase.orgname) + org, err := organization.GetOrgByID(t.Context(), kase.orgname) assert.NoError(t, err) - results, err := organization.GetWorktimeByMembers(org, kase.unixfrom, kase.unixto) + results, err := organization.GetWorktimeByMembers(t.Context(), org, kase.unixfrom, kase.unixto) assert.NoError(t, err) assert.Equal(t, kase.expected, results) }) diff --git a/tests/integration/project_test.go b/tests/integration/project_test.go index 43a489d4c4..116850fd15 100644 --- a/tests/integration/project_test.go +++ b/tests/integration/project_test.go @@ -8,7 +8,6 @@ import ( "net/http" "testing" - "code.gitea.io/gitea/models/db" project_model "code.gitea.io/gitea/models/project" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" @@ -35,7 +34,7 @@ func TestMoveRepoProjectColumns(t *testing.T) { repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - projectsUnit := repo2.MustGetUnit(db.DefaultContext, unit.TypeProjects) + projectsUnit := repo2.MustGetUnit(t.Context(), unit.TypeProjects) assert.True(t, projectsUnit.ProjectsConfig().IsProjectsAllowed(repo_model.ProjectsModeRepo)) project1 := project_model.Project{ @@ -44,18 +43,18 @@ func TestMoveRepoProjectColumns(t *testing.T) { Type: project_model.TypeRepository, TemplateType: project_model.TemplateTypeNone, } - err := project_model.NewProject(db.DefaultContext, &project1) + err := project_model.NewProject(t.Context(), &project1) assert.NoError(t, err) for i := range 3 { - err = project_model.NewColumn(db.DefaultContext, &project_model.Column{ + err = project_model.NewColumn(t.Context(), &project_model.Column{ Title: fmt.Sprintf("column %d", i+1), ProjectID: project1.ID, }) assert.NoError(t, err) } - 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) @@ -76,12 +75,12 @@ func TestMoveRepoProjectColumns(t *testing.T) { }) sess.MakeRequest(t, req, http.StatusOK) - 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) assert.Equal(t, columns[2].ID, columnsAfter[1].ID) assert.Equal(t, columns[0].ID, columnsAfter[2].ID) - assert.NoError(t, project_model.DeleteProjectByID(db.DefaultContext, project1.ID)) + assert.NoError(t, project_model.DeleteProjectByID(t.Context(), project1.ID)) } diff --git a/tests/integration/pull_compare_test.go b/tests/integration/pull_compare_test.go index f95a2f1690..01989e8f89 100644 --- a/tests/integration/pull_compare_test.go +++ b/tests/integration/pull_compare_test.go @@ -9,7 +9,6 @@ import ( "net/url" "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" @@ -77,7 +76,7 @@ func TestPullCompare(t *testing.T) { repoForked := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerName: "user1", Name: "repo1"}) // delete the head repository and revisit the PR diff view - err := repo_service.DeleteRepositoryDirectly(db.DefaultContext, repoForked.ID) + err := repo_service.DeleteRepositoryDirectly(t.Context(), repoForked.ID) assert.NoError(t, err) req = NewRequest(t, "GET", prFilesURL) diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index f1b976a85c..56395a5ba2 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -18,7 +18,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" git_model "code.gitea.io/gitea/models/git" issues_model "code.gitea.io/gitea/models/issues" pull_model "code.gitea.io/gitea/models/pull" @@ -91,7 +90,7 @@ func testPullCleanUp(t *testing.T, session *TestSession, user, repo, pullnum str func TestPullMerge(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(db.DefaultContext, 1, 1) // Retrieve previous hook number + hookTasks, err := webhook.HookTasks(t.Context(), 1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -105,7 +104,7 @@ func TestPullMerge(t *testing.T) { assert.Equal(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleMerge, false) - hookTasks, err = webhook.HookTasks(db.DefaultContext, 1, 1) + hookTasks, err = webhook.HookTasks(t.Context(), 1, 1) assert.NoError(t, err) assert.Len(t, hookTasks, hookTasksLenBefore+1) }) @@ -113,7 +112,7 @@ func TestPullMerge(t *testing.T) { func TestPullRebase(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(db.DefaultContext, 1, 1) // Retrieve previous hook number + hookTasks, err := webhook.HookTasks(t.Context(), 1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -127,7 +126,7 @@ func TestPullRebase(t *testing.T) { assert.Equal(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleRebase, false) - hookTasks, err = webhook.HookTasks(db.DefaultContext, 1, 1) + hookTasks, err = webhook.HookTasks(t.Context(), 1, 1) assert.NoError(t, err) assert.Len(t, hookTasks, hookTasksLenBefore+1) }) @@ -135,7 +134,7 @@ func TestPullRebase(t *testing.T) { func TestPullRebaseMerge(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(db.DefaultContext, 1, 1) // Retrieve previous hook number + hookTasks, err := webhook.HookTasks(t.Context(), 1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -149,7 +148,7 @@ func TestPullRebaseMerge(t *testing.T) { assert.Equal(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleRebaseMerge, false) - hookTasks, err = webhook.HookTasks(db.DefaultContext, 1, 1) + hookTasks, err = webhook.HookTasks(t.Context(), 1, 1) assert.NoError(t, err) assert.Len(t, hookTasks, hookTasksLenBefore+1) }) @@ -157,7 +156,7 @@ func TestPullRebaseMerge(t *testing.T) { func TestPullSquash(t *testing.T) { onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { - hookTasks, err := webhook.HookTasks(db.DefaultContext, 1, 1) // Retrieve previous hook number + hookTasks, err := webhook.HookTasks(t.Context(), 1, 1) // Retrieve previous hook number assert.NoError(t, err) hookTasksLenBefore := len(hookTasks) @@ -172,7 +171,7 @@ func TestPullSquash(t *testing.T) { assert.Equal(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4], repo_model.MergeStyleSquash, false) - hookTasks, err = webhook.HookTasks(db.DefaultContext, 1, 1) + hookTasks, err = webhook.HookTasks(t.Context(), 1, 1) assert.NoError(t, err) assert.Len(t, hookTasks, hookTasksLenBefore+1) }) @@ -462,7 +461,7 @@ func TestConflictChecking(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Create new clean repo to test conflict checking. - baseRepo, err := repo_service.CreateRepository(db.DefaultContext, user, user, repo_service.CreateRepoOptions{ + baseRepo, err := repo_service.CreateRepository(t.Context(), user, user, repo_service.CreateRepoOptions{ Name: "conflict-checking", Description: "Tempo repo", AutoInit: true, @@ -525,7 +524,7 @@ func TestConflictChecking(t *testing.T) { assert.NoError(t, err) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: "PR with conflict!"}) - assert.NoError(t, issue.LoadPullRequest(db.DefaultContext)) + assert.NoError(t, issue.LoadPullRequest(t.Context())) conflictingPR := issue.PullRequest // Ensure conflictedFiles is populated. @@ -533,7 +532,7 @@ func TestConflictChecking(t *testing.T) { // Check if status is correct. assert.Equal(t, issues_model.PullRequestStatusConflict, conflictingPR.Status) // Ensure that mergeable returns false - assert.False(t, conflictingPR.Mergeable(db.DefaultContext)) + assert.False(t, conflictingPR.Mergeable(t.Context())) }) } @@ -744,7 +743,7 @@ func TestPullAutoMergeAfterCommitStatusSucceed(t *testing.T) { addToQueueShaChan <- sha } // first time insert automerge record, return true - scheduled, err := automerge.ScheduleAutoMerge(db.DefaultContext, user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) + scheduled, err := automerge.ScheduleAutoMerge(t.Context(), user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) assert.NoError(t, err) assert.True(t, scheduled) // and the pr should be added to automergequeue, in case it is already "mergeable" @@ -756,7 +755,7 @@ func TestPullAutoMergeAfterCommitStatusSucceed(t *testing.T) { automergequeue.AddToQueue = oldAutoMergeAddToQueue // second time insert automerge record, return false because it does exist - scheduled, err = automerge.ScheduleAutoMerge(db.DefaultContext, user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) + scheduled, err = automerge.ScheduleAutoMerge(t.Context(), user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) assert.Error(t, err) assert.False(t, scheduled) @@ -766,7 +765,7 @@ func TestPullAutoMergeAfterCommitStatusSucceed(t *testing.T) { assert.Empty(t, pr.MergedCommitID) // update commit status to success, then it should be merged automatically - baseGitRepo, err := gitrepo.OpenRepository(db.DefaultContext, baseRepo) + baseGitRepo, err := gitrepo.OpenRepository(t.Context(), baseRepo) assert.NoError(t, err) sha, err := baseGitRepo.GetRefCommitID(pr.GetGitHeadRefName()) assert.NoError(t, err) @@ -781,7 +780,7 @@ func TestPullAutoMergeAfterCommitStatusSucceed(t *testing.T) { testResetRepo(t, baseRepo.RepoPath(), "master", masterCommitID) }() - err = commitstatus_service.CreateCommitStatus(db.DefaultContext, baseRepo, user1, sha, &git_model.CommitStatus{ + err = commitstatus_service.CreateCommitStatus(t.Context(), baseRepo, user1, sha, &git_model.CommitStatus{ State: commitstatus.CommitStatusSuccess, TargetURL: "https://gitea.com", Context: "gitea/actions", @@ -833,12 +832,12 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApproval(t *testing.T) { session.MakeRequest(t, req, http.StatusSeeOther) // first time insert automerge record, return true - scheduled, err := automerge.ScheduleAutoMerge(db.DefaultContext, user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) + scheduled, err := automerge.ScheduleAutoMerge(t.Context(), user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) assert.NoError(t, err) assert.True(t, scheduled) // second time insert automerge record, return false because it does exist - scheduled, err = automerge.ScheduleAutoMerge(db.DefaultContext, user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) + scheduled, err = automerge.ScheduleAutoMerge(t.Context(), user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) assert.Error(t, err) assert.False(t, scheduled) @@ -848,7 +847,7 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApproval(t *testing.T) { assert.Empty(t, pr.MergedCommitID) // update commit status to success, then it should be merged automatically - baseGitRepo, err := gitrepo.OpenRepository(db.DefaultContext, baseRepo) + baseGitRepo, err := gitrepo.OpenRepository(t.Context(), baseRepo) assert.NoError(t, err) sha, err := baseGitRepo.GetRefCommitID(pr.GetGitHeadRefName()) assert.NoError(t, err) @@ -859,7 +858,7 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApproval(t *testing.T) { testResetRepo(t, baseRepo.RepoPath(), "master", masterCommitID) }() - err = commitstatus_service.CreateCommitStatus(db.DefaultContext, baseRepo, user1, sha, &git_model.CommitStatus{ + err = commitstatus_service.CreateCommitStatus(t.Context(), baseRepo, user1, sha, &git_model.CommitStatus{ State: commitstatus.CommitStatusSuccess, TargetURL: "https://gitea.com", Context: "gitea/actions", @@ -962,12 +961,12 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing. user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) // first time insert automerge record, return true - scheduled, err := automerge.ScheduleAutoMerge(db.DefaultContext, user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) + scheduled, err := automerge.ScheduleAutoMerge(t.Context(), user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) assert.NoError(t, err) assert.True(t, scheduled) // second time insert automerge record, return false because it does exist - scheduled, err = automerge.ScheduleAutoMerge(db.DefaultContext, user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) + scheduled, err = automerge.ScheduleAutoMerge(t.Context(), user1, pr, repo_model.MergeStyleMerge, "auto merge test", false) assert.Error(t, err) assert.False(t, scheduled) @@ -977,7 +976,7 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing. assert.Empty(t, pr.MergedCommitID) // update commit status to success, then it should be merged automatically - baseGitRepo, err := gitrepo.OpenRepository(db.DefaultContext, baseRepo) + baseGitRepo, err := gitrepo.OpenRepository(t.Context(), baseRepo) assert.NoError(t, err) sha, err := baseGitRepo.GetRefCommitID(pr.GetGitHeadRefName()) assert.NoError(t, err) @@ -988,7 +987,7 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing. testResetRepo(t, baseRepo.RepoPath(), "master", masterCommitID) }() - err = commitstatus_service.CreateCommitStatus(db.DefaultContext, baseRepo, user1, sha, &git_model.CommitStatus{ + err = commitstatus_service.CreateCommitStatus(t.Context(), baseRepo, user1, sha, &git_model.CommitStatus{ State: commitstatus.CommitStatusSuccess, TargetURL: "https://gitea.com", Context: "gitea/actions", diff --git a/tests/integration/pull_review_test.go b/tests/integration/pull_review_test.go index 1121751c88..be946b7c68 100644 --- a/tests/integration/pull_review_test.go +++ b/tests/integration/pull_review_test.go @@ -39,7 +39,7 @@ func TestPullView_ReviewerMissed(t *testing.T) { assert.True(t, test.IsNormalPageCompleted(resp.Body.String())) // if some reviews are missing, the page shouldn't fail - err := db.TruncateBeans(db.DefaultContext, &issues_model.Review{}) + err := db.TruncateBeans(t.Context(), &issues_model.Review{}) assert.NoError(t, err) req = NewRequest(t, "GET", "/user2/repo1/pulls/2") resp = session.MakeRequest(t, req, http.StatusOK) @@ -51,7 +51,7 @@ func TestPullView_CodeOwner(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Create the repo. - repo, err := repo_service.CreateRepositoryDirectly(db.DefaultContext, user2, user2, repo_service.CreateRepoOptions{ + repo, err := repo_service.CreateRepositoryDirectly(t.Context(), user2, user2, repo_service.CreateRepoOptions{ Name: "test_codeowner", Readme: "Default", AutoInit: true, @@ -61,7 +61,7 @@ func TestPullView_CodeOwner(t *testing.T) { assert.NoError(t, err) // add CODEOWNERS to default branch - _, err = files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{ + _, err = files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{ OldBranch: repo.DefaultBranch, Files: []*files_service.ChangeRepoFile{ { @@ -75,7 +75,7 @@ func TestPullView_CodeOwner(t *testing.T) { t.Run("First Pull Request", func(t *testing.T) { // create a new branch to prepare for pull request - _, err := files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{ + _, err := files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{ NewBranch: "codeowner-basebranch", Files: []*files_service.ChangeRepoFile{ { @@ -93,10 +93,10 @@ func TestPullView_CodeOwner(t *testing.T) { pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{BaseRepoID: repo.ID, HeadRepoID: repo.ID, HeadBranch: "codeowner-basebranch"}) unittest.AssertExistsAndLoadBean(t, &issues_model.Review{IssueID: pr.IssueID, Type: issues_model.ReviewTypeRequest, ReviewerID: 5}) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + assert.NoError(t, pr.LoadIssue(t.Context())) // update the file on the pr branch - _, err = files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{ + _, err = files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{ OldBranch: "codeowner-basebranch", Files: []*files_service.ChangeRepoFile{ { @@ -108,26 +108,26 @@ func TestPullView_CodeOwner(t *testing.T) { }) assert.NoError(t, err) - reviewNotifiers, err := issue_service.PullRequestCodeOwnersReview(db.DefaultContext, pr) + reviewNotifiers, err := issue_service.PullRequestCodeOwnersReview(t.Context(), pr) assert.NoError(t, err) assert.Len(t, reviewNotifiers, 1) assert.EqualValues(t, 8, reviewNotifiers[0].Reviewer.ID) - err = issue_service.ChangeTitle(db.DefaultContext, pr.Issue, user2, "[WIP] Test Pull Request") + err = issue_service.ChangeTitle(t.Context(), pr.Issue, user2, "[WIP] Test Pull Request") assert.NoError(t, err) prUpdated1 := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID}) - assert.NoError(t, prUpdated1.LoadIssue(db.DefaultContext)) + assert.NoError(t, prUpdated1.LoadIssue(t.Context())) assert.Equal(t, "[WIP] Test Pull Request", prUpdated1.Issue.Title) - err = issue_service.ChangeTitle(db.DefaultContext, prUpdated1.Issue, user2, "Test Pull Request2") + err = issue_service.ChangeTitle(t.Context(), prUpdated1.Issue, user2, "Test Pull Request2") assert.NoError(t, err) prUpdated2 := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID}) - assert.NoError(t, prUpdated2.LoadIssue(db.DefaultContext)) + assert.NoError(t, prUpdated2.LoadIssue(t.Context())) assert.Equal(t, "Test Pull Request2", prUpdated2.Issue.Title) }) // change the default branch CODEOWNERS file to change README.md's codeowner - _, err = files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{ + _, err = files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{ Files: []*files_service.ChangeRepoFile{ { Operation: "update", @@ -140,7 +140,7 @@ func TestPullView_CodeOwner(t *testing.T) { t.Run("Second Pull Request", func(t *testing.T) { // create a new branch to prepare for pull request - _, err = files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{ + _, err = files_service.ChangeRepoFiles(t.Context(), repo, user2, &files_service.ChangeRepoFilesOptions{ NewBranch: "codeowner-basebranch2", Files: []*files_service.ChangeRepoFile{ { @@ -162,14 +162,14 @@ func TestPullView_CodeOwner(t *testing.T) { t.Run("Forked Repo Pull Request", func(t *testing.T) { user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) - forkedRepo, err := repo_service.ForkRepository(db.DefaultContext, user2, user5, repo_service.ForkRepoOptions{ + forkedRepo, err := repo_service.ForkRepository(t.Context(), user2, user5, repo_service.ForkRepoOptions{ BaseRepo: repo, Name: "test_codeowner", }) assert.NoError(t, err) // create a new branch to prepare for pull request - _, err = files_service.ChangeRepoFiles(db.DefaultContext, forkedRepo, user5, &files_service.ChangeRepoFilesOptions{ + _, err = files_service.ChangeRepoFiles(t.Context(), forkedRepo, user5, &files_service.ChangeRepoFilesOptions{ NewBranch: "codeowner-basebranch-forked", Files: []*files_service.ChangeRepoFile{ { diff --git a/tests/integration/pull_update_test.go b/tests/integration/pull_update_test.go index f33e7380c0..f4565d8c9c 100644 --- a/tests/integration/pull_update_test.go +++ b/tests/integration/pull_update_test.go @@ -11,7 +11,6 @@ import ( "time" auth_model "code.gitea.io/gitea/models/auth" - "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" @@ -34,8 +33,8 @@ func TestAPIPullUpdate(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 1, diffCount.Behind) assert.Equal(t, 1, diffCount.Ahead) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + assert.NoError(t, pr.LoadBaseRepo(t.Context())) + assert.NoError(t, pr.LoadIssue(t.Context())) session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) @@ -63,8 +62,8 @@ func TestAPIPullUpdateByRebase(t *testing.T) { assert.NoError(t, err) assert.Equal(t, 1, diffCount.Behind) assert.Equal(t, 1, diffCount.Ahead) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + assert.NoError(t, pr.LoadBaseRepo(t.Context())) + assert.NoError(t, pr.LoadIssue(t.Context())) session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) @@ -81,7 +80,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) { } func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_model.PullRequest { - baseRepo, err := repo_service.CreateRepository(db.DefaultContext, actor, actor, repo_service.CreateRepoOptions{ + baseRepo, err := repo_service.CreateRepository(t.Context(), actor, actor, repo_service.CreateRepoOptions{ Name: "repo-pr-update", Description: "repo-tmp-pr-update description", AutoInit: true, @@ -177,7 +176,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_mod assert.NoError(t, err) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: "Test Pull -to-update-"}) - assert.NoError(t, issue.LoadPullRequest(db.DefaultContext)) + assert.NoError(t, issue.LoadPullRequest(t.Context())) return issue.PullRequest } diff --git a/tests/integration/repo_fork_test.go b/tests/integration/repo_fork_test.go index 95325eefeb..e24f31adf2 100644 --- a/tests/integration/repo_fork_test.go +++ b/tests/integration/repo_fork_test.go @@ -10,7 +10,6 @@ import ( "strconv" "testing" - "code.gitea.io/gitea/models/db" org_model "code.gitea.io/gitea/models/organization" "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" @@ -92,9 +91,9 @@ func TestForkListLimitedAndPrivateRepos(t *testing.T) { // fork to a limited org limitedOrg := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 22}) assert.Equal(t, structs.VisibleTypeLimited, limitedOrg.Visibility) - ownerTeam1, err := org_model.OrgFromUser(limitedOrg).GetOwnerTeam(db.DefaultContext) + ownerTeam1, err := org_model.OrgFromUser(limitedOrg).GetOwnerTeam(t.Context()) assert.NoError(t, err) - assert.NoError(t, org_service.AddTeamMember(db.DefaultContext, ownerTeam1, user1)) + assert.NoError(t, org_service.AddTeamMember(t.Context(), ownerTeam1, user1)) testRepoFork(t, user1Sess, "user2", "repo1", limitedOrg.Name, "repo1", "") // fork to a private org @@ -102,9 +101,9 @@ func TestForkListLimitedAndPrivateRepos(t *testing.T) { user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user4"}) privateOrg := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 23}) assert.Equal(t, structs.VisibleTypePrivate, privateOrg.Visibility) - ownerTeam2, err := org_model.OrgFromUser(privateOrg).GetOwnerTeam(db.DefaultContext) + ownerTeam2, err := org_model.OrgFromUser(privateOrg).GetOwnerTeam(t.Context()) assert.NoError(t, err) - assert.NoError(t, org_service.AddTeamMember(db.DefaultContext, ownerTeam2, user4)) + assert.NoError(t, org_service.AddTeamMember(t.Context(), ownerTeam2, user4)) testRepoFork(t, user4Sess, "user2", "repo1", privateOrg.Name, "repo1", "") t.Run("Anonymous", func(t *testing.T) { @@ -124,7 +123,7 @@ func TestForkListLimitedAndPrivateRepos(t *testing.T) { // since user1 is an admin, he can get both of the forked repositories assert.Equal(t, 2, htmlDoc.Find(forkItemSelector).Length()) - assert.NoError(t, org_service.AddTeamMember(db.DefaultContext, ownerTeam2, user1)) + assert.NoError(t, org_service.AddTeamMember(t.Context(), ownerTeam2, user1)) resp = user1Sess.MakeRequest(t, req, http.StatusOK) htmlDoc = NewHTMLParser(t, resp.Body) assert.Equal(t, 2, htmlDoc.Find(forkItemSelector).Length()) diff --git a/tests/integration/repo_merge_upstream_test.go b/tests/integration/repo_merge_upstream_test.go index d33d31c646..17e8083399 100644 --- a/tests/integration/repo_merge_upstream_test.go +++ b/tests/integration/repo_merge_upstream_test.go @@ -118,7 +118,7 @@ func TestRepoMergeUpstream(t *testing.T) { // make sure the base branch's update time is before the fork, to make it test the complete logic baseBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: baseRepo.ID, Name: "master"}) forkBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: forkRepo.ID, Name: "fork-branch"}) - _, err := db.GetEngine(db.DefaultContext).ID(forkBranch.ID).Update(&git_model.Branch{UpdatedUnix: baseBranch.UpdatedUnix + 1}) + _, err := db.GetEngine(t.Context()).ID(forkBranch.ID).Update(&git_model.Branch{UpdatedUnix: baseBranch.UpdatedUnix + 1}) require.NoError(t, err) // the repo shows a prompt to "sync fork" diff --git a/tests/integration/repo_search_test.go b/tests/integration/repo_search_test.go index 36a2e81f3b..eafb600990 100644 --- a/tests/integration/repo_search_test.go +++ b/tests/integration/repo_search_test.go @@ -7,7 +7,6 @@ import ( "net/http" "testing" - "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" code_indexer "code.gitea.io/gitea/modules/indexer/code" "code.gitea.io/gitea/modules/setting" @@ -29,7 +28,7 @@ func resultFilenames(doc *HTMLDoc) []string { func TestSearchRepo(t *testing.T) { defer tests.PrepareTestEnv(t)() - repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") + repo, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), "user2", "repo1") assert.NoError(t, err) code_indexer.UpdateRepoIndexer(repo) @@ -39,7 +38,7 @@ func TestSearchRepo(t *testing.T) { setting.Indexer.IncludePatterns = setting.IndexerGlobFromString("**.txt") setting.Indexer.ExcludePatterns = setting.IndexerGlobFromString("**/y/**") - repo, err = repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "glob") + repo, err = repo_model.GetRepositoryByOwnerAndName(t.Context(), "user2", "glob") assert.NoError(t, err) code_indexer.UpdateRepoIndexer(repo) diff --git a/tests/integration/repo_tag_test.go b/tests/integration/repo_tag_test.go index 86080aeb8e..2ee492c4b5 100644 --- a/tests/integration/repo_tag_test.go +++ b/tests/integration/repo_tag_test.go @@ -99,7 +99,7 @@ func TestCreateNewTagProtected(t *testing.T) { }) // Cleanup - releases, err := db.Find[repo_model.Release](db.DefaultContext, repo_model.FindReleasesOptions{ + releases, err := db.Find[repo_model.Release](t.Context(), repo_model.FindReleasesOptions{ IncludeTags: true, TagNames: []string{"v-1", "v-1.1"}, RepoID: repo.ID, @@ -107,15 +107,15 @@ func TestCreateNewTagProtected(t *testing.T) { assert.NoError(t, err) for _, release := range releases { - _, err = db.DeleteByID[repo_model.Release](db.DefaultContext, release.ID) + _, err = db.DeleteByID[repo_model.Release](t.Context(), release.ID) assert.NoError(t, err) } - protectedTags, err := git_model.GetProtectedTags(db.DefaultContext, repo.ID) + protectedTags, err := git_model.GetProtectedTags(t.Context(), repo.ID) assert.NoError(t, err) for _, protectedTag := range protectedTags { - err = git_model.DeleteProtectedTag(db.DefaultContext, protectedTag) + err = git_model.DeleteProtectedTag(t.Context(), protectedTag) assert.NoError(t, err) } } diff --git a/tests/integration/repo_test.go b/tests/integration/repo_test.go index 7aceaec473..d12addb127 100644 --- a/tests/integration/repo_test.go +++ b/tests/integration/repo_test.go @@ -13,7 +13,6 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unit" "code.gitea.io/gitea/models/unittest" @@ -539,14 +538,14 @@ func TestGenerateRepository(t *testing.T) { unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerName: user2.Name, Name: generatedRepo.Name}) - err = repo_service.DeleteRepositoryDirectly(db.DefaultContext, generatedRepo.ID) + err = repo_service.DeleteRepositoryDirectly(t.Context(), generatedRepo.ID) assert.NoError(t, err) // a failed creating because some mock data // create the repository directory so that the creation will fail after database record created. assert.NoError(t, os.MkdirAll(repo_model.RepoPath(user2.Name, "generated-from-template-44"), os.ModePerm)) - generatedRepo2, err := repo_service.GenerateRepository(db.DefaultContext, user2, user2, repo44, repo_service.GenerateRepoOptions{ + generatedRepo2, err := repo_service.GenerateRepository(t.Context(), user2, user2, repo44, repo_service.GenerateRepoOptions{ Name: "generated-from-template-44", GitContent: true, }) diff --git a/tests/integration/session_test.go b/tests/integration/session_test.go index f72e2e24b7..981b88ae45 100644 --- a/tests/integration/session_test.go +++ b/tests/integration/session_test.go @@ -7,7 +7,6 @@ import ( "testing" "code.gitea.io/gitea/models/auth" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/tests" @@ -21,16 +20,16 @@ func Test_RegenerateSession(t *testing.T) { key := "new_key890123456" // it must be 16 characters long key2 := "new_key890123457" // it must be 16 characters - exist, err := auth.ExistSession(db.DefaultContext, key) + exist, err := auth.ExistSession(t.Context(), key) assert.NoError(t, err) assert.False(t, exist) - sess, err := auth.RegenerateSession(db.DefaultContext, "", key) + sess, err := auth.RegenerateSession(t.Context(), "", key) assert.NoError(t, err) assert.Equal(t, key, sess.Key) assert.Empty(t, sess.Data) - sess, err = auth.ReadSession(db.DefaultContext, key2) + sess, err = auth.ReadSession(t.Context(), key2) assert.NoError(t, err) assert.Equal(t, key2, sess.Key) assert.Empty(t, sess.Data) diff --git a/tests/integration/signin_test.go b/tests/integration/signin_test.go index fa37145d98..a9b4402119 100644 --- a/tests/integration/signin_test.go +++ b/tests/integration/signin_test.go @@ -50,7 +50,7 @@ func TestSignin(t *testing.T) { user.Name = "testuser" user.LowerName = strings.ToLower(user.Name) user.ID = 0 - require.NoError(t, db.Insert(db.DefaultContext, user)) + require.NoError(t, db.Insert(t.Context(), user)) samples := []struct { username string diff --git a/tests/integration/signup_test.go b/tests/integration/signup_test.go index c08f57d33e..06c513f616 100644 --- a/tests/integration/signup_test.go +++ b/tests/integration/signup_test.go @@ -125,7 +125,7 @@ func TestSignupEmailActive(t *testing.T) { // generate an activation code from lower-cased email activationCode := user_model.GenerateUserTimeLimitCode(&user_model.TimeLimitCodeOptions{Purpose: user_model.TimeLimitCodeActivateAccount}, user) // and update the user email to case-sensitive, it shouldn't affect the verification later - _, _ = db.Exec(db.DefaultContext, "UPDATE `user` SET email=? WHERE id=?", "EmAiL-changed@example.com", user.ID) + _, _ = db.Exec(t.Context(), "UPDATE `user` SET email=? WHERE id=?", "EmAiL-changed@example.com", user.ID) user = unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "Test-User-1"}) assert.Equal(t, "EmAiL-changed@example.com", user.Email) diff --git a/tests/integration/user_avatar_test.go b/tests/integration/user_avatar_test.go index 14ea012ac8..bf28afade0 100644 --- a/tests/integration/user_avatar_test.go +++ b/tests/integration/user_avatar_test.go @@ -11,7 +11,6 @@ import ( "net/http" "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/avatar" @@ -74,7 +73,7 @@ func TestUserAvatar(t *testing.T) { user2 = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // owner of the repo3, is an org - req = NewRequest(t, "GET", user2.AvatarLinkWithSize(db.DefaultContext, 0)) + req = NewRequest(t, "GET", user2.AvatarLinkWithSize(t.Context(), 0)) _ = session.MakeRequest(t, req, http.StatusOK) testGetAvatarRedirect(t, user2) diff --git a/tests/test_utils.go b/tests/test_utils.go index eda00c9c78..e63eb75846 100644 --- a/tests/test_utils.go +++ b/tests/test_utils.go @@ -216,7 +216,7 @@ func PrepareLFSStorage(t testing.TB) { func PrepareCleanPackageData(t testing.TB) { // clear all package data - assert.NoError(t, db.TruncateBeans(db.DefaultContext, + assert.NoError(t, db.TruncateBeans(t.Context(), &packages_model.Package{}, &packages_model.PackageVersion{}, &packages_model.PackageFile{},