From 7f802631c54d2e91301158380b273b872d62bd80 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 12 Nov 2021 20:37:45 +0800 Subject: [PATCH 01/24] Fix some incorrect async functions, improve frontend document. (#17597) --- .../doc/developers/guidelines-frontend.md | 59 +++++++++++++++++++ web_src/js/features/clipboard.js | 22 ++++--- web_src/js/features/notification.js | 35 +++++------ web_src/js/features/repo-graph.js | 19 +++--- web_src/js/features/repo-legacy.js | 2 +- web_src/js/features/repo-projects.js | 4 +- web_src/js/features/stopwatch.js | 10 ++-- 7 files changed, 107 insertions(+), 44 deletions(-) diff --git a/docs/content/doc/developers/guidelines-frontend.md b/docs/content/doc/developers/guidelines-frontend.md index f30b0d1cbd88..c937cfb7b4dd 100644 --- a/docs/content/doc/developers/guidelines-frontend.md +++ b/docs/content/doc/developers/guidelines-frontend.md @@ -39,6 +39,65 @@ We recommend [Google HTML/CSS Style Guide](https://google.github.io/styleguide/h 6. The backend can pass complex data to the frontend by using `ctx.PageData["myModuleData"] = map[]{}` 7. Simple pages and SEO-related pages use Go HTML Template render to generate static Fomantic-UI HTML output. Complex pages can use Vue2 (or Vue3 in future). + +### `async` Functions + +Only mark a function as `async` if and only if there are `await` calls +or `Promise` returns inside the function. + +It's not recommended to use `async` event listeners, which may lead to problems. +The reason is that the code after await is executed outside the event dispatch. +Reference: https://github.com/github/eslint-plugin-github/blob/main/docs/rules/async-preventdefault.md + +If we want to call an `async` function in a non-async context, +it's recommended to use `const _promise = asyncFoo()` to tell readers +that this is done by purpose, we want to call the async function and ignore the Promise. +Some lint rules and IDEs also have warnings if the returned Promise is not handled. + +#### DOM Event Listener + +```js +el.addEventListener('click', (e) => { + (async () => { + await asyncFoo(); // recommended + // then we shound't do e.preventDefault() after await, no effect + })(); + + const _promise = asyncFoo(); // recommended + + e.preventDefault(); // correct +}); + +el.addEventListener('async', async (e) => { // not recommended but acceptable + e.preventDefault(); // acceptable + await asyncFoo(); // skip out event dispath + e.preventDefault(); // WRONG +}); +``` + +#### jQuery Event Listener + +```js +$('#el').on('click', (e) => { + (async () => { + await asyncFoo(); // recommended + // then we shound't do e.preventDefault() after await, no effect + })(); + + const _promise = asyncFoo(); // recommended + + e.preventDefault(); // correct + return false; // correct +}); + +$('#el').on('click', async (e) => { // not recommended but acceptable + e.preventDefault(); // acceptable + return false; // WRONG, jQuery expects the returned value is a boolean, not a Promise + await asyncFoo(); // skip out event dispath + return false; // WRONG +}); +``` + ### Vue2/Vue3 and JSX Gitea is using Vue2 now, we plan to upgrade to Vue3. We decided not to introduce JSX to keep the HTML and the JavaScript code separated. diff --git a/web_src/js/features/clipboard.js b/web_src/js/features/clipboard.js index 8d28b4e281c5..89aface93aca 100644 --- a/web_src/js/features/clipboard.js +++ b/web_src/js/features/clipboard.js @@ -46,7 +46,7 @@ function fallbackCopyToClipboard(text) { } export default function initGlobalCopyToClipboardListener() { - document.addEventListener('click', async (e) => { + document.addEventListener('click', (e) => { let target = e.target; // in case , so we just search up to 3 levels for performance. for (let i = 0; i < 3 && target; i++) { @@ -58,16 +58,20 @@ export default function initGlobalCopyToClipboardListener() { } if (text) { e.preventDefault(); - try { - await navigator.clipboard.writeText(text); - onSuccess(target); - } catch { - if (fallbackCopyToClipboard(text)) { + + (async() => { + try { + await navigator.clipboard.writeText(text); onSuccess(target); - } else { - onError(target); + } catch { + if (fallbackCopyToClipboard(text)) { + onSuccess(target); + } else { + onError(target); + } } - } + })(); + break; } target = target.parentElement; diff --git a/web_src/js/features/notification.js b/web_src/js/features/notification.js index f4c31c5ede92..1e483b16c8ba 100644 --- a/web_src/js/features/notification.js +++ b/web_src/js/features/notification.js @@ -3,21 +3,22 @@ const {appSubUrl, csrfToken, notificationSettings} = window.config; let notificationSequenceNumber = 0; export function initNotificationsTable() { - $('#notification_table .button').on('click', async function () { - const data = await updateNotification( - $(this).data('url'), - $(this).data('status'), - $(this).data('page'), - $(this).data('q'), - $(this).data('notification-id'), - ); - - if ($(data).data('sequence-number') === notificationSequenceNumber) { - $('#notification_div').replaceWith(data); - initNotificationsTable(); - } - await updateNotificationCount(); - + $('#notification_table .button').on('click', function () { + (async () => { + const data = await updateNotification( + $(this).data('url'), + $(this).data('status'), + $(this).data('page'), + $(this).data('q'), + $(this).data('notification-id'), + ); + + if ($(data).data('sequence-number') === notificationSequenceNumber) { + $('#notification_div').replaceWith(data); + initNotificationsTable(); + } + await updateNotificationCount(); + })(); return false; }); } @@ -104,8 +105,8 @@ export function initNotificationCount() { } const fn = (timeout, lastCount) => { - setTimeout(async () => { - await updateNotificationCountWithCallback(fn, timeout, lastCount); + setTimeout(() => { + const _promise = updateNotificationCountWithCallback(fn, timeout, lastCount); }, timeout); }; diff --git a/web_src/js/features/repo-graph.js b/web_src/js/features/repo-graph.js index 007cf9b38daf..73bde5facd69 100644 --- a/web_src/js/features/repo-graph.js +++ b/web_src/js/features/repo-graph.js @@ -48,7 +48,7 @@ export default function initRepoGraphGit() { }); const url = new URL(window.location); const params = url.searchParams; - const updateGraph = async () => { + const updateGraph = () => { const queryString = params.toString(); const ajaxUrl = new URL(url); ajaxUrl.searchParams.set('div-only', 'true'); @@ -57,14 +57,15 @@ export default function initRepoGraphGit() { $('#rel-container').addClass('hide'); $('#rev-container').addClass('hide'); $('#loading-indicator').removeClass('hide'); - - const div = $(await $.ajax(String(ajaxUrl))); - $('#pagination').html(div.find('#pagination').html()); - $('#rel-container').html(div.find('#rel-container').html()); - $('#rev-container').html(div.find('#rev-container').html()); - $('#loading-indicator').addClass('hide'); - $('#rel-container').removeClass('hide'); - $('#rev-container').removeClass('hide'); + (async () => { + const div = $(await $.ajax(String(ajaxUrl))); + $('#pagination').html(div.find('#pagination').html()); + $('#rel-container').html(div.find('#rel-container').html()); + $('#rev-container').html(div.find('#rev-container').html()); + $('#loading-indicator').addClass('hide'); + $('#rel-container').removeClass('hide'); + $('#rev-container').removeClass('hide'); + })(); }; const dropdownSelected = params.getAll('branch'); if (params.has('hide-pr-refs') && params.get('hide-pr-refs') === 'true') { diff --git a/web_src/js/features/repo-legacy.js b/web_src/js/features/repo-legacy.js index f4a8c0cf3e9f..8945360cd580 100644 --- a/web_src/js/features/repo-legacy.js +++ b/web_src/js/features/repo-legacy.js @@ -351,6 +351,7 @@ export function initRepository() { // Edit issue or comment content $(document).on('click', '.edit-content', async function (event) { + event.preventDefault(); $(this).closest('.dropdown').find('.menu').toggle('visible'); const $segment = $(this).closest('.header').next(); const $editContentZone = $segment.find('.edit-content-zone'); @@ -511,7 +512,6 @@ export function initRepository() { $textarea.focus(); $simplemde.codemirror.focus(); }); - event.preventDefault(); }); initRepoIssueCommentDelete(); diff --git a/web_src/js/features/repo-projects.js b/web_src/js/features/repo-projects.js index 995b971be552..270d54671304 100644 --- a/web_src/js/features/repo-projects.js +++ b/web_src/js/features/repo-projects.js @@ -63,9 +63,7 @@ export default function initRepoProject() { return; } - (async () => { - await initRepoProjectSortable(); - })(); + const _promise = initRepoProjectSortable(); $('.edit-project-board').each(function () { const projectHeader = $(this).closest('.board-column-header'); diff --git a/web_src/js/features/stopwatch.js b/web_src/js/features/stopwatch.js index ff3edaf8cc8a..f6185f7ff73a 100644 --- a/web_src/js/features/stopwatch.js +++ b/web_src/js/features/stopwatch.js @@ -82,8 +82,8 @@ export function initStopwatch() { } const fn = (timeout) => { - setTimeout(async () => { - await updateStopwatchWithCallback(fn, timeout); + setTimeout(() => { + const _promise = updateStopwatchWithCallback(fn, timeout); }, timeout); }; @@ -122,7 +122,7 @@ async function updateStopwatch() { return updateStopwatchData(data); } -async function updateStopwatchData(data) { +function updateStopwatchData(data) { const watch = data[0]; const btnEl = $('.active-stopwatch-trigger'); if (!watch) { @@ -135,14 +135,14 @@ async function updateStopwatchData(data) { $('.stopwatch-cancel').attr('action', `${issueUrl}/times/stopwatch/cancel`); $('.stopwatch-issue').text(`${repo_owner_name}/${repo_name}#${issue_index}`); $('.stopwatch-time').text(prettyMilliseconds(seconds * 1000)); - await updateStopwatchTime(seconds); + updateStopwatchTime(seconds); btnEl.removeClass('hidden'); } return !!data.length; } -async function updateStopwatchTime(seconds) { +function updateStopwatchTime(seconds) { const secs = parseInt(seconds); if (!Number.isFinite(secs)) return; From df64fa486555de6f403a795fd16c2e9e1d59e535 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Fri, 12 Nov 2021 22:36:47 +0800 Subject: [PATCH 02/24] Decouple unit test code from business code (#17623) --- contrib/fixtures/fixture_generation.go | 6 +- contrib/pr/checkout.go | 7 +- integrations/api_issue_label_test.go | 10 +- integrations/integration_test.go | 11 +- integrations/migrate_test.go | 4 +- integrations/repofiles_delete_test.go | 9 +- models/access_test.go | 15 +- models/action_test.go | 9 +- models/admin_test.go | 17 +- models/attachment_test.go | 15 +- models/branches_test.go | 17 +- models/commit_status_test.go | 3 +- models/consistency.go | 155 ++++++------- models/consistency_test.go | 3 +- models/db/engine.go | 5 +- models/db/{ => paginator}/main_test.go | 6 +- models/db/paginator/paginator.go | 8 + .../paginator_test.go} | 13 +- models/db/unit_tests.go | 206 ++++-------------- models/engine_test.go | 3 +- models/fixture_test.go | 6 +- models/gpg_key_test.go | 3 +- models/issue_assignees_test.go | 5 +- models/issue_comment_test.go | 5 +- models/issue_dependency_test.go | 3 +- models/issue_label_test.go | 47 ++-- models/issue_list_test.go | 5 +- models/issue_milestone_test.go | 33 +-- models/issue_reaction_test.go | 15 +- models/issue_stopwatch_test.go | 9 +- models/issue_test.go | 33 +-- models/issue_tracked_time_test.go | 7 +- models/issue_user_test.go | 7 +- models/issue_watch_test.go | 7 +- models/issue_xref_test.go | 7 +- models/issues/content_history_test.go | 3 +- models/issues/main_test.go | 4 +- models/login/main_test.go | 4 +- models/login/oauth2_application_test.go | 31 +-- models/login/source_test.go | 3 +- models/login/u2f_test.go | 13 +- models/main_test.go | 16 +- models/migrations/migrations_test.go | 7 +- models/notification_test.go | 15 +- models/org_team_test.go | 47 ++-- models/org_test.go | 73 ++++--- models/project_test.go | 6 +- models/protected_tag_test.go | 5 +- models/pull_test.go | 39 ++-- models/repo_collaboration_test.go | 11 +- models/repo_list_test.go | 5 +- models/repo_permission_test.go | 9 +- models/repo_pushmirror_test.go | 4 +- models/repo_redirect_test.go | 9 +- models/repo_test.go | 27 +-- models/repo_transfer_test.go | 3 +- models/repo_watch_test.go | 15 +- models/review_test.go | 17 +- models/star_test.go | 15 +- models/token_test.go | 13 +- models/topic_test.go | 3 +- models/unittest/bridge.go | 54 +++++ .../test_fixtures.go => unittest/fixtures.go} | 23 +- models/unittest/testdb.go | 154 +++++++++++++ models/user/email_address_test.go | 13 +- models/user/main_test.go | 4 +- models/user/redirect_test.go | 5 +- models/user_email_test.go | 7 +- models/user_follow_test.go | 7 +- models/user_heatmap_test.go | 3 +- models/user_openid_test.go | 9 +- models/user_test.go | 33 +-- models/userlist_test.go | 9 +- models/webhook/main_test.go | 4 +- models/webhook/webhook_test.go | 41 ++-- models/wiki_test.go | 9 +- modules/appstate/appstate_test.go | 6 +- modules/convert/git_commit_test.go | 3 +- modules/convert/issue_test.go | 3 +- modules/convert/main_test.go | 4 +- modules/convert/pull_test.go | 3 +- modules/convert/user_test.go | 3 +- modules/indexer/code/bleve_test.go | 4 +- modules/indexer/code/elastic_search_test.go | 5 +- modules/indexer/code/indexer_test.go | 5 +- modules/indexer/issues/indexer_test.go | 8 +- modules/indexer/stats/indexer_test.go | 6 +- modules/migrations/gitea_uploader_test.go | 3 +- modules/migrations/main_test.go | 4 +- modules/migrations/migrate_test.go | 3 +- modules/notification/action/action_test.go | 5 +- modules/repofiles/action_test.go | 13 +- modules/repofiles/blob_test.go | 5 +- modules/repofiles/content_test.go | 17 +- modules/repofiles/diff_test.go | 6 +- modules/repofiles/file_test.go | 4 +- modules/repofiles/tree_test.go | 5 +- modules/repository/commits_test.go | 5 +- modules/repository/create_test.go | 3 +- modules/repository/fork_test.go | 3 +- modules/repository/main_test.go | 4 +- modules/unittestbridge/unittestbridge.go | 46 ++++ routers/api/v1/repo/hook_test.go | 3 +- routers/api/v1/repo/main_test.go | 4 +- routers/api/v1/repo/repo_test.go | 5 +- routers/web/admin/main_test.go | 4 +- routers/web/admin/users_test.go | 11 +- routers/web/repo/editor_test.go | 8 +- routers/web/repo/issue_label_test.go | 15 +- routers/web/repo/main_test.go | 4 +- routers/web/repo/projects_test.go | 4 +- routers/web/repo/release_test.go | 3 +- routers/web/repo/settings_test.go | 23 +- routers/web/repo/wiki_test.go | 20 +- routers/web/user/home_test.go | 12 +- routers/web/user/main_test.go | 4 +- routers/web/user/oauth_test.go | 3 +- routers/web/user/setting/account_test.go | 4 +- routers/web/user/setting/main_test.go | 4 +- services/archiver/archiver_test.go | 6 +- services/attachment/attachment_test.go | 5 +- services/gitdiff/gitdiff_test.go | 3 +- services/gitdiff/main_test.go | 4 +- services/issue/assignee_test.go | 4 +- services/issue/label_test.go | 5 +- services/issue/main_test.go | 4 +- services/mailer/mail_test.go | 3 +- services/mailer/main_test.go | 4 +- services/pull/check_test.go | 3 +- services/pull/main_test.go | 4 +- services/release/release_test.go | 11 +- services/repository/main_test.go | 4 +- services/repository/transfer_test.go | 5 +- services/webhook/main_test.go | 4 +- services/webhook/webhook_test.go | 7 +- services/wiki/wiki_test.go | 17 +- 136 files changed, 1057 insertions(+), 829 deletions(-) rename models/db/{ => paginator}/main_test.go (67%) create mode 100644 models/db/paginator/paginator.go rename models/db/{list_options_test.go => paginator/paginator_test.go} (79%) create mode 100644 models/unittest/bridge.go rename models/{db/test_fixtures.go => unittest/fixtures.go} (89%) create mode 100644 models/unittest/testdb.go create mode 100644 modules/unittestbridge/unittestbridge.go diff --git a/contrib/fixtures/fixture_generation.go b/contrib/fixtures/fixture_generation.go index 5e7dd39a78fb..74996a1f3599 100644 --- a/contrib/fixtures/fixture_generation.go +++ b/contrib/fixtures/fixture_generation.go @@ -10,7 +10,7 @@ import ( "path/filepath" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) // To generate derivative fixtures, execute the following from Gitea's repository base dir: @@ -31,13 +31,13 @@ var ( func main() { pathToGiteaRoot := "." fixturesDir = filepath.Join(pathToGiteaRoot, "models", "fixtures") - if err := db.CreateTestEngine(db.FixturesOptions{ + if err := unittest.CreateTestEngine(unittest.FixturesOptions{ Dir: fixturesDir, }); err != nil { fmt.Printf("CreateTestEngine: %+v", err) os.Exit(1) } - if err := db.PrepareTestDatabase(); err != nil { + if err := unittest.PrepareTestDatabase(); err != nil { fmt.Printf("PrepareTestDatabase: %+v\n", err) os.Exit(1) } diff --git a/contrib/pr/checkout.go b/contrib/pr/checkout.go index 89d92c852612..1e2a9714e38a 100644 --- a/contrib/pr/checkout.go +++ b/contrib/pr/checkout.go @@ -26,6 +26,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" gitea_git "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/markup" "code.gitea.io/gitea/modules/markup/external" @@ -99,8 +100,8 @@ func runPR() { }) db.HasEngine = true //x.ShowSQL(true) - err = db.InitFixtures( - db.FixturesOptions{ + err = unittest.InitFixtures( + unittest.FixturesOptions{ Dir: path.Join(curDir, "models/fixtures/"), }, ) @@ -108,7 +109,7 @@ func runPR() { fmt.Printf("Error initializing test database: %v\n", err) os.Exit(1) } - db.LoadFixtures() + unittest.LoadFixtures() util.RemoveAll(setting.RepoRootPath) util.RemoveAll(models.LocalCopyPath()) util.CopyDir(path.Join(curDir, "integrations/gitea-repositories-meta"), setting.RepoRootPath) diff --git a/integrations/api_issue_label_test.go b/integrations/api_issue_label_test.go index 4508069e1764..f9c297a18e8e 100644 --- a/integrations/api_issue_label_test.go +++ b/integrations/api_issue_label_test.go @@ -10,6 +10,8 @@ import ( "strings" "testing" + "code.gitea.io/gitea/models/unittest" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" api "code.gitea.io/gitea/modules/structs" @@ -18,7 +20,7 @@ import ( ) func TestAPIModifyLabels(t *testing.T) { - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) @@ -88,7 +90,7 @@ func TestAPIModifyLabels(t *testing.T) { } func TestAPIAddIssueLabels(t *testing.T) { - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) issue := db.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repo.ID}).(*models.Issue) @@ -111,7 +113,7 @@ func TestAPIAddIssueLabels(t *testing.T) { } func TestAPIReplaceIssueLabels(t *testing.T) { - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) issue := db.AssertExistsAndLoadBean(t, &models.Issue{RepoID: repo.ID}).(*models.Issue) @@ -137,7 +139,7 @@ func TestAPIReplaceIssueLabels(t *testing.T) { } func TestAPIModifyOrgLabels(t *testing.T) { - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) owner := db.AssertExistsAndLoadBean(t, &models.User{ID: repo.OwnerID}).(*models.User) diff --git a/integrations/integration_test.go b/integrations/integration_test.go index 1429893270b0..69c4ca4ae5e6 100644 --- a/integrations/integration_test.go +++ b/integrations/integration_test.go @@ -25,7 +25,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/graceful" @@ -84,6 +84,7 @@ func NewNilResponseHashSumRecorder() *NilResponseHashSumRecorder { func TestMain(m *testing.M) { defer log.Close() + unittest.InitUnitTestBridge() managerCtx, cancel := context.WithCancel(context.Background()) graceful.InitManager(managerCtx) defer cancel() @@ -112,8 +113,8 @@ func TestMain(m *testing.M) { } } - err := db.InitFixtures( - db.FixturesOptions{ + err := unittest.InitFixtures( + unittest.FixturesOptions{ Dir: filepath.Join(filepath.Dir(setting.AppPath), "models/fixtures/"), }, ) @@ -250,7 +251,7 @@ func prepareTestEnv(t testing.TB, skip ...int) func() { ourSkip += skip[0] } deferFn := PrintCurrentTest(t, ourSkip) - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath)) @@ -527,7 +528,7 @@ func GetCSRF(t testing.TB, session *TestSession, urlStr string) string { // within a single test this is required func resetFixtures(t *testing.T) { assert.NoError(t, queue.GetManager().FlushAll(context.Background(), -1)) - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath)) } diff --git a/integrations/migrate_test.go b/integrations/migrate_test.go index c0d5d4fc75a9..b9fcfb282745 100644 --- a/integrations/migrate_test.go +++ b/integrations/migrate_test.go @@ -8,6 +8,8 @@ import ( "os" "testing" + "code.gitea.io/gitea/models/unittest" + "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/migrations" @@ -17,7 +19,7 @@ import ( ) func TestMigrateLocalPath(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) adminUser := db.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User) diff --git a/integrations/repofiles_delete_test.go b/integrations/repofiles_delete_test.go index 22fef4b03ef6..8150673e2b32 100644 --- a/integrations/repofiles_delete_test.go +++ b/integrations/repofiles_delete_test.go @@ -8,8 +8,9 @@ import ( "net/url" "testing" + "code.gitea.io/gitea/models/unittest" + "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/repofiles" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/test" @@ -67,7 +68,7 @@ func TestDeleteRepoFile(t *testing.T) { func testDeleteRepoFile(t *testing.T, u *url.URL) { // setup - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -106,7 +107,7 @@ func TestDeleteRepoFileWithoutBranchNames(t *testing.T) { func testDeleteRepoFileWithoutBranchNames(t *testing.T, u *url.URL) { // setup - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -136,7 +137,7 @@ func testDeleteRepoFileWithoutBranchNames(t *testing.T, u *url.URL) { func TestDeleteRepoFileErrors(t *testing.T) { // setup - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) diff --git a/models/access_test.go b/models/access_test.go index 2f641bb9b573..af799ebcdea2 100644 --- a/models/access_test.go +++ b/models/access_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestAccessLevel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user5 := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) @@ -63,7 +64,7 @@ func TestAccessLevel(t *testing.T) { } func TestHasAccess(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user2 := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) @@ -89,7 +90,7 @@ func TestHasAccess(t *testing.T) { } func TestUser_GetRepositoryAccesses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) accesses, err := user1.GetRepositoryAccesses() @@ -103,7 +104,7 @@ func TestUser_GetRepositoryAccesses(t *testing.T) { } func TestUser_GetAccessibleRepositories(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) repos, err := user1.GetAccessibleRepositories(0) @@ -123,7 +124,7 @@ func TestUser_GetAccessibleRepositories(t *testing.T) { func TestRepository_RecalculateAccesses(t *testing.T) { // test with organization repo - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) assert.NoError(t, repo1.GetOwner()) @@ -140,7 +141,7 @@ func TestRepository_RecalculateAccesses(t *testing.T) { func TestRepository_RecalculateAccesses2(t *testing.T) { // test with non-organization repo - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) assert.NoError(t, repo1.GetOwner()) @@ -154,7 +155,7 @@ func TestRepository_RecalculateAccesses2(t *testing.T) { } func TestRepository_RecalculateAccesses3(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) team5 := db.AssertExistsAndLoadBean(t, &Team{ID: 5}).(*Team) user29 := db.AssertExistsAndLoadBean(t, &User{ID: 29}).(*User) diff --git a/models/action_test.go b/models/action_test.go index 78090e3aadbb..85b8290cb2d0 100644 --- a/models/action_test.go +++ b/models/action_test.go @@ -9,13 +9,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestAction_GetRepoPath(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{}).(*Repository) owner := db.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) action := &Action{RepoID: repo.ID} @@ -23,7 +24,7 @@ func TestAction_GetRepoPath(t *testing.T) { } func TestAction_GetRepoLink(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{}).(*Repository) owner := db.AssertExistsAndLoadBean(t, &User{ID: repo.OwnerID}).(*User) action := &Action{RepoID: repo.ID} @@ -34,7 +35,7 @@ func TestAction_GetRepoLink(t *testing.T) { func TestGetFeeds(t *testing.T) { // test with an individual user - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) actions, err := GetFeeds(GetFeedsOptions{ @@ -62,7 +63,7 @@ func TestGetFeeds(t *testing.T) { func TestGetFeeds2(t *testing.T) { // test with an organization user - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) diff --git a/models/admin_test.go b/models/admin_test.go index 316ed5cb683d..ea060f97261e 100644 --- a/models/admin_test.go +++ b/models/admin_test.go @@ -8,6 +8,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) @@ -20,7 +21,7 @@ func TestNotice_TrStr(t *testing.T) { } func TestCreateNotice(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) noticeBean := &Notice{ Type: NoticeRepository, @@ -32,7 +33,7 @@ func TestCreateNotice(t *testing.T) { } func TestCreateRepositoryNotice(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) noticeBean := &Notice{ Type: NoticeRepository, @@ -46,12 +47,12 @@ func TestCreateRepositoryNotice(t *testing.T) { // TODO TestRemoveAllWithNotice func TestCountNotices(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.Equal(t, int64(3), CountNotices()) } func TestNotices(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) notices, err := Notices(1, 2) assert.NoError(t, err) @@ -68,7 +69,7 @@ func TestNotices(t *testing.T) { } func TestDeleteNotice(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) db.AssertExistsAndLoadBean(t, &Notice{ID: 3}) assert.NoError(t, DeleteNotice(3)) @@ -77,7 +78,7 @@ func TestDeleteNotice(t *testing.T) { func TestDeleteNotices(t *testing.T) { // delete a non-empty range - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) db.AssertExistsAndLoadBean(t, &Notice{ID: 1}) db.AssertExistsAndLoadBean(t, &Notice{ID: 2}) @@ -90,7 +91,7 @@ func TestDeleteNotices(t *testing.T) { func TestDeleteNotices2(t *testing.T) { // delete an empty range - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) db.AssertExistsAndLoadBean(t, &Notice{ID: 1}) db.AssertExistsAndLoadBean(t, &Notice{ID: 2}) @@ -102,7 +103,7 @@ func TestDeleteNotices2(t *testing.T) { } func TestDeleteNoticesByIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) db.AssertExistsAndLoadBean(t, &Notice{ID: 1}) db.AssertExistsAndLoadBean(t, &Notice{ID: 2}) diff --git a/models/attachment_test.go b/models/attachment_test.go index c7f456341cdc..bc8114fa67b6 100644 --- a/models/attachment_test.go +++ b/models/attachment_test.go @@ -9,11 +9,12 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestIncreaseDownloadCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) attachment, err := GetAttachmentByUUID("a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11") assert.NoError(t, err) @@ -29,7 +30,7 @@ func TestIncreaseDownloadCount(t *testing.T) { } func TestGetByCommentOrIssueID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // count of attachments from issue ID attachments, err := GetAttachmentsByIssueID(1) @@ -42,7 +43,7 @@ func TestGetByCommentOrIssueID(t *testing.T) { } func TestDeleteAttachments(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) count, err := DeleteAttachmentsByIssue(4, false) assert.NoError(t, err) @@ -62,7 +63,7 @@ func TestDeleteAttachments(t *testing.T) { } func TestGetAttachmentByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) attach, err := GetAttachmentByID(1) assert.NoError(t, err) @@ -78,7 +79,7 @@ func TestAttachment_DownloadURL(t *testing.T) { } func TestUpdateAttachment(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) attach, err := GetAttachmentByID(1) assert.NoError(t, err) @@ -91,7 +92,7 @@ func TestUpdateAttachment(t *testing.T) { } func TestGetAttachmentsByUUIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) attachList, err := GetAttachmentsByUUIDs(db.DefaultContext, []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"}) assert.NoError(t, err) @@ -103,7 +104,7 @@ func TestGetAttachmentsByUUIDs(t *testing.T) { } func TestLinkedRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testCases := []struct { name string attachID int64 diff --git a/models/branches_test.go b/models/branches_test.go index e9a32666f9da..d7233fba6538 100644 --- a/models/branches_test.go +++ b/models/branches_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestAddDeletedBranch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) @@ -21,7 +22,7 @@ func TestAddDeletedBranch(t *testing.T) { } func TestGetDeletedBranches(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) branches, err := repo.GetDeletedBranches() @@ -30,14 +31,14 @@ func TestGetDeletedBranches(t *testing.T) { } func TestGetDeletedBranch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) assert.NotNil(t, getDeletedBranch(t, firstBranch)) } func TestDeletedBranchLoadUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) secondBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 2}).(*DeletedBranch) @@ -56,7 +57,7 @@ func TestDeletedBranchLoadUser(t *testing.T) { } func TestRemoveDeletedBranch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) firstBranch := db.AssertExistsAndLoadBean(t, &DeletedBranch{ID: 1}).(*DeletedBranch) @@ -81,7 +82,7 @@ func getDeletedBranch(t *testing.T, branch *DeletedBranch) *DeletedBranch { } func TestFindRenamedBranch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) branch, exist, err := FindRenamedBranch(1, "dev") assert.NoError(t, err) assert.Equal(t, true, exist) @@ -93,7 +94,7 @@ func TestFindRenamedBranch(t *testing.T) { } func TestRenameBranch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) _isDefault := false @@ -130,7 +131,7 @@ func TestRenameBranch(t *testing.T) { } func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Get deletedBranch with ID of 1 on repo with ID 2. // This should return a nil branch as this deleted branch diff --git a/models/commit_status_test.go b/models/commit_status_test.go index 7f4709144ceb..b113346a41f6 100644 --- a/models/commit_status_test.go +++ b/models/commit_status_test.go @@ -8,12 +8,13 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" ) func TestGetCommitStatuses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) diff --git a/models/consistency.go b/models/consistency.go index ab814569160d..64c6b240a206 100644 --- a/models/consistency.go +++ b/models/consistency.go @@ -7,29 +7,16 @@ package models import ( "reflect" "strings" - "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/modules/unittestbridge" - "github.com/stretchr/testify/assert" "xorm.io/builder" ) -// CheckConsistencyForAll test that the entire database is consistent -func CheckConsistencyForAll(t *testing.T) { - CheckConsistencyFor(t, - &User{}, - &Repository{}, - &Issue{}, - &PullRequest{}, - &Milestone{}, - &Label{}, - &Team{}, - &Action{}) -} - // CheckConsistencyFor test that all matching database entries are consistent -func CheckConsistencyFor(t *testing.T, beansToCheck ...interface{}) { +func CheckConsistencyFor(t unittestbridge.Tester, beansToCheck ...interface{}) { + ta := unittestbridge.NewAsserter(t) for _, bean := range beansToCheck { sliceType := reflect.SliceOf(reflect.TypeOf(bean)) sliceValue := reflect.MakeSlice(sliceType, 0, 10) @@ -37,133 +24,133 @@ func CheckConsistencyFor(t *testing.T, beansToCheck ...interface{}) { ptrToSliceValue := reflect.New(sliceType) ptrToSliceValue.Elem().Set(sliceValue) - assert.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface())) + ta.NoError(db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface())) sliceValue = ptrToSliceValue.Elem() for i := 0; i < sliceValue.Len(); i++ { entity := sliceValue.Index(i).Interface() - checkForConsistency(entity, t) + checkForConsistency(ta, entity) } } } -func checkForConsistency(bean interface{}, t *testing.T) { +func checkForConsistency(ta unittestbridge.Asserter, bean interface{}) { switch b := bean.(type) { case *User: - checkForUserConsistency(b, t) + checkForUserConsistency(b, ta) case *Repository: - checkForRepoConsistency(b, t) + checkForRepoConsistency(b, ta) case *Issue: - checkForIssueConsistency(b, t) + checkForIssueConsistency(b, ta) case *PullRequest: - checkForPullRequestConsistency(b, t) + checkForPullRequestConsistency(b, ta) case *Milestone: - checkForMilestoneConsistency(b, t) + checkForMilestoneConsistency(b, ta) case *Label: - checkForLabelConsistency(b, t) + checkForLabelConsistency(b, ta) case *Team: - checkForTeamConsistency(b, t) + checkForTeamConsistency(b, ta) case *Action: - checkForActionConsistency(b, t) + checkForActionConsistency(b, ta) default: - t.Errorf("unknown bean type: %#v", bean) + ta.Errorf("unknown bean type: %#v", bean) } } // getCount get the count of database entries matching bean -func getCount(t *testing.T, e db.Engine, bean interface{}) int64 { +func getCount(ta unittestbridge.Asserter, e db.Engine, bean interface{}) int64 { count, err := e.Count(bean) - assert.NoError(t, err) + ta.NoError(err) return count } // assertCount test the count of database entries matching bean -func assertCount(t *testing.T, bean interface{}, expected int) { - assert.EqualValues(t, expected, getCount(t, db.GetEngine(db.DefaultContext), bean), +func assertCount(ta unittestbridge.Asserter, bean interface{}, expected int) { + ta.EqualValues(expected, getCount(ta, db.GetEngine(db.DefaultContext), bean), "Failed consistency test, the counted bean (of type %T) was %+v", bean, bean) } -func checkForUserConsistency(user *User, t *testing.T) { - assertCount(t, &Repository{OwnerID: user.ID}, user.NumRepos) - assertCount(t, &Star{UID: user.ID}, user.NumStars) - assertCount(t, &OrgUser{OrgID: user.ID}, user.NumMembers) - assertCount(t, &Team{OrgID: user.ID}, user.NumTeams) - assertCount(t, &Follow{UserID: user.ID}, user.NumFollowing) - assertCount(t, &Follow{FollowID: user.ID}, user.NumFollowers) +func checkForUserConsistency(user *User, ta unittestbridge.Asserter) { + assertCount(ta, &Repository{OwnerID: user.ID}, user.NumRepos) + assertCount(ta, &Star{UID: user.ID}, user.NumStars) + assertCount(ta, &OrgUser{OrgID: user.ID}, user.NumMembers) + assertCount(ta, &Team{OrgID: user.ID}, user.NumTeams) + assertCount(ta, &Follow{UserID: user.ID}, user.NumFollowing) + assertCount(ta, &Follow{FollowID: user.ID}, user.NumFollowers) if user.Type != UserTypeOrganization { - assert.EqualValues(t, 0, user.NumMembers) - assert.EqualValues(t, 0, user.NumTeams) + ta.EqualValues(0, user.NumMembers) + ta.EqualValues(0, user.NumTeams) } } -func checkForRepoConsistency(repo *Repository, t *testing.T) { - assert.Equal(t, repo.LowerName, strings.ToLower(repo.Name), "repo: %+v", repo) - assertCount(t, &Star{RepoID: repo.ID}, repo.NumStars) - assertCount(t, &Milestone{RepoID: repo.ID}, repo.NumMilestones) - assertCount(t, &Repository{ForkID: repo.ID}, repo.NumForks) +func checkForRepoConsistency(repo *Repository, ta unittestbridge.Asserter) { + ta.Equal(repo.LowerName, strings.ToLower(repo.Name), "repo: %+v", repo) + assertCount(ta, &Star{RepoID: repo.ID}, repo.NumStars) + assertCount(ta, &Milestone{RepoID: repo.ID}, repo.NumMilestones) + assertCount(ta, &Repository{ForkID: repo.ID}, repo.NumForks) if repo.IsFork { - db.AssertExistsAndLoadBean(t, &Repository{ID: repo.ForkID}) + db.AssertExistsAndLoadBean(ta, &Repository{ID: repo.ForkID}) } - actual := getCount(t, db.GetEngine(db.DefaultContext).Where("Mode<>?", RepoWatchModeDont), &Watch{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumWatches, actual, + actual := getCount(ta, db.GetEngine(db.DefaultContext).Where("Mode<>?", RepoWatchModeDont), &Watch{RepoID: repo.ID}) + ta.EqualValues(repo.NumWatches, actual, "Unexpected number of watches for repo %+v", repo) - actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=?", false), &Issue{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumIssues, actual, + actual = getCount(ta, db.GetEngine(db.DefaultContext).Where("is_pull=?", false), &Issue{RepoID: repo.ID}) + ta.EqualValues(repo.NumIssues, actual, "Unexpected number of issues for repo %+v", repo) - actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=? AND is_closed=?", false, true), &Issue{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumClosedIssues, actual, + actual = getCount(ta, db.GetEngine(db.DefaultContext).Where("is_pull=? AND is_closed=?", false, true), &Issue{RepoID: repo.ID}) + ta.EqualValues(repo.NumClosedIssues, actual, "Unexpected number of closed issues for repo %+v", repo) - actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=?", true), &Issue{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumPulls, actual, + actual = getCount(ta, db.GetEngine(db.DefaultContext).Where("is_pull=?", true), &Issue{RepoID: repo.ID}) + ta.EqualValues(repo.NumPulls, actual, "Unexpected number of pulls for repo %+v", repo) - actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_pull=? AND is_closed=?", true, true), &Issue{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumClosedPulls, actual, + actual = getCount(ta, db.GetEngine(db.DefaultContext).Where("is_pull=? AND is_closed=?", true, true), &Issue{RepoID: repo.ID}) + ta.EqualValues(repo.NumClosedPulls, actual, "Unexpected number of closed pulls for repo %+v", repo) - actual = getCount(t, db.GetEngine(db.DefaultContext).Where("is_closed=?", true), &Milestone{RepoID: repo.ID}) - assert.EqualValues(t, repo.NumClosedMilestones, actual, + actual = getCount(ta, db.GetEngine(db.DefaultContext).Where("is_closed=?", true), &Milestone{RepoID: repo.ID}) + ta.EqualValues(repo.NumClosedMilestones, actual, "Unexpected number of closed milestones for repo %+v", repo) } -func checkForIssueConsistency(issue *Issue, t *testing.T) { - actual := getCount(t, db.GetEngine(db.DefaultContext).Where("type=?", CommentTypeComment), &Comment{IssueID: issue.ID}) - assert.EqualValues(t, issue.NumComments, actual, +func checkForIssueConsistency(issue *Issue, ta unittestbridge.Asserter) { + actual := getCount(ta, db.GetEngine(db.DefaultContext).Where("type=?", CommentTypeComment), &Comment{IssueID: issue.ID}) + ta.EqualValues(issue.NumComments, actual, "Unexpected number of comments for issue %+v", issue) if issue.IsPull { - pr := db.AssertExistsAndLoadBean(t, &PullRequest{IssueID: issue.ID}).(*PullRequest) - assert.EqualValues(t, pr.Index, issue.Index) + pr := db.AssertExistsAndLoadBean(ta, &PullRequest{IssueID: issue.ID}).(*PullRequest) + ta.EqualValues(pr.Index, issue.Index) } } -func checkForPullRequestConsistency(pr *PullRequest, t *testing.T) { - issue := db.AssertExistsAndLoadBean(t, &Issue{ID: pr.IssueID}).(*Issue) - assert.True(t, issue.IsPull) - assert.EqualValues(t, issue.Index, pr.Index) +func checkForPullRequestConsistency(pr *PullRequest, ta unittestbridge.Asserter) { + issue := db.AssertExistsAndLoadBean(ta, &Issue{ID: pr.IssueID}).(*Issue) + ta.True(issue.IsPull) + ta.EqualValues(issue.Index, pr.Index) } -func checkForMilestoneConsistency(milestone *Milestone, t *testing.T) { - assertCount(t, &Issue{MilestoneID: milestone.ID}, milestone.NumIssues) +func checkForMilestoneConsistency(milestone *Milestone, ta unittestbridge.Asserter) { + assertCount(ta, &Issue{MilestoneID: milestone.ID}, milestone.NumIssues) - actual := getCount(t, db.GetEngine(db.DefaultContext).Where("is_closed=?", true), &Issue{MilestoneID: milestone.ID}) - assert.EqualValues(t, milestone.NumClosedIssues, actual, + actual := getCount(ta, db.GetEngine(db.DefaultContext).Where("is_closed=?", true), &Issue{MilestoneID: milestone.ID}) + ta.EqualValues(milestone.NumClosedIssues, actual, "Unexpected number of closed issues for milestone %+v", milestone) completeness := 0 if milestone.NumIssues > 0 { completeness = milestone.NumClosedIssues * 100 / milestone.NumIssues } - assert.Equal(t, completeness, milestone.Completeness) + ta.Equal(completeness, milestone.Completeness) } -func checkForLabelConsistency(label *Label, t *testing.T) { +func checkForLabelConsistency(label *Label, ta unittestbridge.Asserter) { issueLabels := make([]*IssueLabel, 0, 10) - assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&issueLabels, &IssueLabel{LabelID: label.ID})) - assert.EqualValues(t, label.NumIssues, len(issueLabels), + ta.NoError(db.GetEngine(db.DefaultContext).Find(&issueLabels, &IssueLabel{LabelID: label.ID})) + ta.EqualValues(label.NumIssues, len(issueLabels), "Unexpected number of issue for label %+v", label) issueIDs := make([]int64, len(issueLabels)) @@ -173,20 +160,20 @@ func checkForLabelConsistency(label *Label, t *testing.T) { expected := int64(0) if len(issueIDs) > 0 { - expected = getCount(t, db.GetEngine(db.DefaultContext).In("id", issueIDs).Where("is_closed=?", true), &Issue{}) + expected = getCount(ta, db.GetEngine(db.DefaultContext).In("id", issueIDs).Where("is_closed=?", true), &Issue{}) } - assert.EqualValues(t, expected, label.NumClosedIssues, + ta.EqualValues(expected, label.NumClosedIssues, "Unexpected number of closed issues for label %+v", label) } -func checkForTeamConsistency(team *Team, t *testing.T) { - assertCount(t, &TeamUser{TeamID: team.ID}, team.NumMembers) - assertCount(t, &TeamRepo{TeamID: team.ID}, team.NumRepos) +func checkForTeamConsistency(team *Team, ta unittestbridge.Asserter) { + assertCount(ta, &TeamUser{TeamID: team.ID}, team.NumMembers) + assertCount(ta, &TeamRepo{TeamID: team.ID}, team.NumRepos) } -func checkForActionConsistency(action *Action, t *testing.T) { - repo := db.AssertExistsAndLoadBean(t, &Repository{ID: action.RepoID}).(*Repository) - assert.Equal(t, repo.IsPrivate, action.IsPrivate, "action: %+v", action) +func checkForActionConsistency(action *Action, ta unittestbridge.Asserter) { + repo := db.AssertExistsAndLoadBean(ta, &Repository{ID: action.RepoID}).(*Repository) + ta.Equal(repo.IsPrivate, action.IsPrivate, "action: %+v", action) } // CountOrphanedLabels return count of labels witch are broken and not accessible via ui anymore diff --git a/models/consistency_test.go b/models/consistency_test.go index 8332b5d76191..6995f47c87e2 100644 --- a/models/consistency_test.go +++ b/models/consistency_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestDeleteOrphanedObjects(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) countBefore, err := db.GetEngine(db.DefaultContext).Count(&PullRequest{}) assert.NoError(t, err) diff --git a/models/db/engine.go b/models/db/engine.go index d5f2470a7af6..d1b279e01669 100755 --- a/models/db/engine.go +++ b/models/db/engine.go @@ -124,7 +124,8 @@ func NewEngine() (*xorm.Engine, error) { return engine, nil } -func syncTables() error { +//SyncAllTables sync the schemas of all tables, is required by unit test code +func SyncAllTables() error { return x.StoreEngine("InnoDB").Sync2(tables...) } @@ -176,7 +177,7 @@ func InitEngineWithMigration(ctx context.Context, migrateFunc func(*xorm.Engine) return fmt.Errorf("migrate: %v", err) } - if err = syncTables(); err != nil { + if err = SyncAllTables(); err != nil { return fmt.Errorf("sync database struct error: %v", err) } diff --git a/models/db/main_test.go b/models/db/paginator/main_test.go similarity index 67% rename from models/db/main_test.go rename to models/db/paginator/main_test.go index f34ff65813c1..601ed89710a3 100644 --- a/models/db/main_test.go +++ b/models/db/paginator/main_test.go @@ -2,13 +2,15 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package db +package paginator import ( "path/filepath" "testing" + + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } diff --git a/models/db/paginator/paginator.go b/models/db/paginator/paginator.go new file mode 100644 index 000000000000..747539f30ea6 --- /dev/null +++ b/models/db/paginator/paginator.go @@ -0,0 +1,8 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package paginator + +// dummy only. in the future, the models/db/list_options.go should be moved here to decouple from db package +// otherwise the unit test will cause cycle import diff --git a/models/db/list_options_test.go b/models/db/paginator/paginator_test.go similarity index 79% rename from models/db/list_options_test.go rename to models/db/paginator/paginator_test.go index 2c860afdfbdd..fdb8eee4417a 100644 --- a/models/db/list_options_test.go +++ b/models/db/paginator/paginator_test.go @@ -2,11 +2,12 @@ // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package db +package paginator import ( "testing" + "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" @@ -14,35 +15,35 @@ import ( func TestPaginator(t *testing.T) { cases := []struct { - Paginator + db.Paginator Skip int Take int Start int End int }{ { - Paginator: &ListOptions{Page: -1, PageSize: -1}, + Paginator: &db.ListOptions{Page: -1, PageSize: -1}, Skip: 0, Take: setting.API.DefaultPagingNum, Start: 0, End: setting.API.DefaultPagingNum, }, { - Paginator: &ListOptions{Page: 2, PageSize: 10}, + Paginator: &db.ListOptions{Page: 2, PageSize: 10}, Skip: 10, Take: 10, Start: 10, End: 20, }, { - Paginator: NewAbsoluteListOptions(-1, -1), + Paginator: db.NewAbsoluteListOptions(-1, -1), Skip: 0, Take: setting.API.DefaultPagingNum, Start: 0, End: setting.API.DefaultPagingNum, }, { - Paginator: NewAbsoluteListOptions(2, 10), + Paginator: db.NewAbsoluteListOptions(2, 10), Skip: 2, Take: 10, Start: 2, diff --git a/models/db/unit_tests.go b/models/db/unit_tests.go index 6f079c8676ce..2b1691726f19 100644 --- a/models/db/unit_tests.go +++ b/models/db/unit_tests.go @@ -6,157 +6,26 @@ package db import ( "context" - "fmt" "math" - "net/url" - "os" - "path/filepath" - "testing" - "code.gitea.io/gitea/modules/base" - "code.gitea.io/gitea/modules/setting" - "code.gitea.io/gitea/modules/storage" - "code.gitea.io/gitea/modules/util" + "code.gitea.io/gitea/modules/unittestbridge" - "github.com/stretchr/testify/assert" "xorm.io/xorm" - "xorm.io/xorm/names" ) +// Code in this file is mainly used by models.CheckConsistencyFor, which is not in the unit test for various reasons. +// In the future if we can decouple CheckConsistencyFor into separate unit test code, then this file can be moved into unittest package too. + // NonexistentID an ID that will never exist const NonexistentID = int64(math.MaxInt64) -// giteaRoot a path to the gitea root -var ( - giteaRoot string - fixturesDir string -) - -// FixturesDir returns the fixture directory -func FixturesDir() string { - return fixturesDir -} - -func fatalTestError(fmtStr string, args ...interface{}) { - fmt.Fprintf(os.Stderr, fmtStr, args...) - os.Exit(1) -} - -// MainTest a reusable TestMain(..) function for unit tests that need to use a -// test database. Creates the test database, and sets necessary settings. -func MainTest(m *testing.M, pathToGiteaRoot string, fixtureFiles ...string) { - var err error - giteaRoot = pathToGiteaRoot - fixturesDir = filepath.Join(pathToGiteaRoot, "models", "fixtures") - - var opts FixturesOptions - if len(fixtureFiles) == 0 { - opts.Dir = fixturesDir - } else { - for _, f := range fixtureFiles { - if len(f) != 0 { - opts.Files = append(opts.Files, filepath.Join(fixturesDir, f)) - } - } - } - - if err = CreateTestEngine(opts); err != nil { - fatalTestError("Error creating test engine: %v\n", err) - } - - setting.AppURL = "https://try.gitea.io/" - setting.RunUser = "runuser" - setting.SSH.Port = 3000 - setting.SSH.Domain = "try.gitea.io" - setting.Database.UseSQLite3 = true - setting.RepoRootPath, err = os.MkdirTemp(os.TempDir(), "repos") - if err != nil { - fatalTestError("TempDir: %v\n", err) - } - setting.AppDataPath, err = os.MkdirTemp(os.TempDir(), "appdata") - if err != nil { - fatalTestError("TempDir: %v\n", err) - } - setting.AppWorkPath = pathToGiteaRoot - setting.StaticRootPath = pathToGiteaRoot - setting.GravatarSourceURL, err = url.Parse("https://secure.gravatar.com/avatar/") - if err != nil { - fatalTestError("url.Parse: %v\n", err) - } - setting.Attachment.Storage.Path = filepath.Join(setting.AppDataPath, "attachments") - - setting.LFS.Storage.Path = filepath.Join(setting.AppDataPath, "lfs") - - setting.Avatar.Storage.Path = filepath.Join(setting.AppDataPath, "avatars") - - setting.RepoAvatar.Storage.Path = filepath.Join(setting.AppDataPath, "repo-avatars") - - setting.RepoArchive.Storage.Path = filepath.Join(setting.AppDataPath, "repo-archive") - - if err = storage.Init(); err != nil { - fatalTestError("storage.Init: %v\n", err) - } - - if err = util.RemoveAll(setting.RepoRootPath); err != nil { - fatalTestError("util.RemoveAll: %v\n", err) - } - if err = util.CopyDir(filepath.Join(pathToGiteaRoot, "integrations", "gitea-repositories-meta"), setting.RepoRootPath); err != nil { - fatalTestError("util.CopyDir: %v\n", err) - } - - exitStatus := m.Run() - if err = util.RemoveAll(setting.RepoRootPath); err != nil { - fatalTestError("util.RemoveAll: %v\n", err) - } - if err = util.RemoveAll(setting.AppDataPath); err != nil { - fatalTestError("util.RemoveAll: %v\n", err) - } - os.Exit(exitStatus) -} - -// FixturesOptions fixtures needs to be loaded options -type FixturesOptions struct { - Dir string - Files []string -} - -// CreateTestEngine creates a memory database and loads the fixture data from fixturesDir -func CreateTestEngine(opts FixturesOptions) error { - var err error - x, err = xorm.NewEngine("sqlite3", "file::memory:?cache=shared&_txlock=immediate") - if err != nil { - return err - } - x.SetMapper(names.GonicMapper{}) - if err = syncTables(); err != nil { - return err - } - switch os.Getenv("GITEA_UNIT_TESTS_VERBOSE") { - case "true", "1": - x.ShowSQL(true) - } - +//SetUnitTestEngine is used by unit test code +func SetUnitTestEngine(eng *xorm.Engine) { + x = eng DefaultContext = &Context{ Context: context.Background(), e: x, } - - return InitFixtures(opts) -} - -// PrepareTestDatabase load test fixtures into test database -func PrepareTestDatabase() error { - return LoadFixtures() -} - -// PrepareTestEnv prepares the environment for unit tests. Can only be called -// by tests that use the above MainTest(..) function. -func PrepareTestEnv(t testing.TB) { - assert.NoError(t, PrepareTestDatabase()) - assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) - metaPath := filepath.Join(giteaRoot, "integrations", "gitea-repositories-meta") - assert.NoError(t, util.CopyDir(metaPath, setting.RepoRootPath)) - base.SetupGiteaRoot() // Makes sure GITEA_ROOT is set } type testCond struct { @@ -182,10 +51,6 @@ func whereConditions(sess *xorm.Session, conditions []interface{}) { // LoadBeanIfExists loads beans from fixture database if exist func LoadBeanIfExists(bean interface{}, conditions ...interface{}) (bool, error) { - return loadBeanIfExists(bean, conditions...) -} - -func loadBeanIfExists(bean interface{}, conditions ...interface{}) (bool, error) { sess := x.NewSession() defer sess.Close() whereConditions(sess, conditions) @@ -193,61 +58,68 @@ func loadBeanIfExists(bean interface{}, conditions ...interface{}) (bool, error) } // BeanExists for testing, check if a bean exists -func BeanExists(t testing.TB, bean interface{}, conditions ...interface{}) bool { - exists, err := loadBeanIfExists(bean, conditions...) - assert.NoError(t, err) +func BeanExists(t unittestbridge.Tester, bean interface{}, conditions ...interface{}) bool { + ta := unittestbridge.NewAsserter(t) + exists, err := LoadBeanIfExists(bean, conditions...) + ta.NoError(err) return exists } -// AssertExistsAndLoadBean assert that a bean exists and load it from the test -// database -func AssertExistsAndLoadBean(t testing.TB, bean interface{}, conditions ...interface{}) interface{} { - exists, err := loadBeanIfExists(bean, conditions...) - assert.NoError(t, err) - assert.True(t, exists, +// AssertExistsAndLoadBean assert that a bean exists and load it from the test database +func AssertExistsAndLoadBean(t unittestbridge.Tester, bean interface{}, conditions ...interface{}) interface{} { + ta := unittestbridge.NewAsserter(t) + exists, err := LoadBeanIfExists(bean, conditions...) + ta.NoError(err) + ta.True(exists, "Expected to find %+v (of type %T, with conditions %+v), but did not", bean, bean, conditions) return bean } // GetCount get the count of a bean -func GetCount(t testing.TB, bean interface{}, conditions ...interface{}) int { +func GetCount(t unittestbridge.Tester, bean interface{}, conditions ...interface{}) int { + ta := unittestbridge.NewAsserter(t) sess := x.NewSession() defer sess.Close() whereConditions(sess, conditions) count, err := sess.Count(bean) - assert.NoError(t, err) + ta.NoError(err) return int(count) } // AssertNotExistsBean assert that a bean does not exist in the test database -func AssertNotExistsBean(t testing.TB, bean interface{}, conditions ...interface{}) { - exists, err := loadBeanIfExists(bean, conditions...) - assert.NoError(t, err) - assert.False(t, exists) +func AssertNotExistsBean(t unittestbridge.Tester, bean interface{}, conditions ...interface{}) { + ta := unittestbridge.NewAsserter(t) + exists, err := LoadBeanIfExists(bean, conditions...) + ta.NoError(err) + ta.False(exists) } // AssertExistsIf asserts that a bean exists or does not exist, depending on // what is expected. -func AssertExistsIf(t *testing.T, expected bool, bean interface{}, conditions ...interface{}) { - exists, err := loadBeanIfExists(bean, conditions...) - assert.NoError(t, err) - assert.Equal(t, expected, exists) +func AssertExistsIf(t unittestbridge.Tester, expected bool, bean interface{}, conditions ...interface{}) { + ta := unittestbridge.NewAsserter(t) + exists, err := LoadBeanIfExists(bean, conditions...) + ta.NoError(err) + ta.Equal(expected, exists) } // AssertSuccessfulInsert assert that beans is successfully inserted -func AssertSuccessfulInsert(t testing.TB, beans ...interface{}) { +func AssertSuccessfulInsert(t unittestbridge.Tester, beans ...interface{}) { + ta := unittestbridge.NewAsserter(t) _, err := x.Insert(beans...) - assert.NoError(t, err) + ta.NoError(err) } // AssertCount assert the count of a bean -func AssertCount(t testing.TB, bean, expected interface{}) { - assert.EqualValues(t, expected, GetCount(t, bean)) +func AssertCount(t unittestbridge.Tester, bean, expected interface{}) { + ta := unittestbridge.NewAsserter(t) + ta.EqualValues(expected, GetCount(ta, bean)) } // AssertInt64InRange assert value is in range [low, high] -func AssertInt64InRange(t testing.TB, low, high, value int64) { - assert.True(t, value >= low && value <= high, +func AssertInt64InRange(t unittestbridge.Tester, low, high, value int64) { + ta := unittestbridge.NewAsserter(t) + ta.True(value >= low && value <= high, "Expected value in range [%d, %d], found %d", low, high, value) } diff --git a/models/engine_test.go b/models/engine_test.go index d97fc3cc197a..75c854b185f2 100644 --- a/models/engine_test.go +++ b/models/engine_test.go @@ -10,13 +10,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestDumpDatabase(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) dir, err := os.MkdirTemp(os.TempDir(), "dump") assert.NoError(t, err) diff --git a/models/fixture_test.go b/models/fixture_test.go index 3c6ebc06850d..0857341e4447 100644 --- a/models/fixture_test.go +++ b/models/fixture_test.go @@ -9,21 +9,21 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" ) func TestFixtureGeneration(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(gen func() (string, error), name string) { expected, err := gen() if !assert.NoError(t, err) { return } - bytes, err := os.ReadFile(filepath.Join(db.FixturesDir(), name+".yml")) + bytes, err := os.ReadFile(filepath.Join(unittest.FixturesDir(), name+".yml")) if !assert.NoError(t, err) { return } diff --git a/models/gpg_key_test.go b/models/gpg_key_test.go index 7a3cbfd67fea..3df25a10bb90 100644 --- a/models/gpg_key_test.go +++ b/models/gpg_key_test.go @@ -9,6 +9,7 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" @@ -193,7 +194,7 @@ Unknown GPG key with good email } func TestCheckGPGUserEmail(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) _ = db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) diff --git a/models/issue_assignees_test.go b/models/issue_assignees_test.go index 5052df3dfb10..f0bd5fca4b90 100644 --- a/models/issue_assignees_test.go +++ b/models/issue_assignees_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestUpdateAssignee(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Fake issue with assignees issue, err := GetIssueWithAttrsByID(1) @@ -62,7 +63,7 @@ func TestUpdateAssignee(t *testing.T) { } func TestMakeIDsFromAPIAssigneesToAdd(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) _ = db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) _ = db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) diff --git a/models/issue_comment_test.go b/models/issue_comment_test.go index 78199881c602..d855b87bc4bb 100644 --- a/models/issue_comment_test.go +++ b/models/issue_comment_test.go @@ -9,11 +9,12 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestCreateComment(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{}).(*Issue) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: issue.RepoID}).(*Repository) @@ -42,7 +43,7 @@ func TestCreateComment(t *testing.T) { } func TestFetchCodeComments(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) diff --git a/models/issue_dependency_test.go b/models/issue_dependency_test.go index 10872645b081..60fa58738983 100644 --- a/models/issue_dependency_test.go +++ b/models/issue_dependency_test.go @@ -8,12 +8,13 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestCreateIssueDependency(t *testing.T) { // Prepare - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1, err := GetUserByID(1) assert.NoError(t, err) diff --git a/models/issue_label_test.go b/models/issue_label_test.go index 93807a326f80..c77ddfefaf7a 100644 --- a/models/issue_label_test.go +++ b/models/issue_label_test.go @@ -9,20 +9,21 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) // TODO TestGetLabelTemplateFile func TestLabel_CalOpenIssues(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) label.CalOpenIssues() assert.EqualValues(t, 2, label.NumOpenIssues) } func TestLabel_ForegroundColor(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) assert.Equal(t, template.CSS("#000"), label.ForegroundColor()) @@ -31,7 +32,7 @@ func TestLabel_ForegroundColor(t *testing.T) { } func TestNewLabels(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) labels := []*Label{ {RepoID: 2, Name: "labelName2", Color: "#123456"}, {RepoID: 3, Name: "labelName3", Color: "#23456F"}, @@ -50,7 +51,7 @@ func TestNewLabels(t *testing.T) { } func TestGetLabelByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label, err := GetLabelByID(1) assert.NoError(t, err) assert.EqualValues(t, 1, label.ID) @@ -60,7 +61,7 @@ func TestGetLabelByID(t *testing.T) { } func TestGetLabelInRepoByName(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label, err := GetLabelInRepoByName(1, "label1") assert.NoError(t, err) assert.EqualValues(t, 1, label.ID) @@ -74,7 +75,7 @@ func TestGetLabelInRepoByName(t *testing.T) { } func TestGetLabelInRepoByNames(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) labelIDs, err := GetLabelIDsInRepoByNames(1, []string{"label1", "label2"}) assert.NoError(t, err) @@ -85,7 +86,7 @@ func TestGetLabelInRepoByNames(t *testing.T) { } func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // label3 doesn't exists.. See labels.yml labelIDs, err := GetLabelIDsInRepoByNames(1, []string{"label1", "label2", "label3"}) assert.NoError(t, err) @@ -98,7 +99,7 @@ func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) { } func TestGetLabelInRepoByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label, err := GetLabelInRepoByID(1, 1) assert.NoError(t, err) assert.EqualValues(t, 1, label.ID) @@ -111,7 +112,7 @@ func TestGetLabelInRepoByID(t *testing.T) { } func TestGetLabelsInRepoByIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) labels, err := GetLabelsInRepoByIDs(1, []int64{1, 2, db.NonexistentID}) assert.NoError(t, err) if assert.Len(t, labels, 2) { @@ -121,7 +122,7 @@ func TestGetLabelsInRepoByIDs(t *testing.T) { } func TestGetLabelsByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) { labels, err := GetLabelsByRepoID(repoID, sortType, db.ListOptions{}) assert.NoError(t, err) @@ -139,7 +140,7 @@ func TestGetLabelsByRepoID(t *testing.T) { // Org versions func TestGetLabelInOrgByName(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label, err := GetLabelInOrgByName(3, "orglabel3") assert.NoError(t, err) assert.EqualValues(t, 3, label.ID) @@ -159,7 +160,7 @@ func TestGetLabelInOrgByName(t *testing.T) { } func TestGetLabelInOrgByNames(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) labelIDs, err := GetLabelIDsInOrgByNames(3, []string{"orglabel3", "orglabel4"}) assert.NoError(t, err) @@ -170,7 +171,7 @@ func TestGetLabelInOrgByNames(t *testing.T) { } func TestGetLabelInOrgByNamesDiscardsNonExistentLabels(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // orglabel99 doesn't exists.. See labels.yml labelIDs, err := GetLabelIDsInOrgByNames(3, []string{"orglabel3", "orglabel4", "orglabel99"}) assert.NoError(t, err) @@ -183,7 +184,7 @@ func TestGetLabelInOrgByNamesDiscardsNonExistentLabels(t *testing.T) { } func TestGetLabelInOrgByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label, err := GetLabelInOrgByID(3, 3) assert.NoError(t, err) assert.EqualValues(t, 3, label.ID) @@ -202,7 +203,7 @@ func TestGetLabelInOrgByID(t *testing.T) { } func TestGetLabelsInOrgByIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) labels, err := GetLabelsInOrgByIDs(3, []int64{3, 4, db.NonexistentID}) assert.NoError(t, err) if assert.Len(t, labels, 2) { @@ -212,7 +213,7 @@ func TestGetLabelsInOrgByIDs(t *testing.T) { } func TestGetLabelsByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) { labels, err := GetLabelsByOrgID(orgID, sortType, db.ListOptions{}) assert.NoError(t, err) @@ -237,7 +238,7 @@ func TestGetLabelsByOrgID(t *testing.T) { // func TestGetLabelsByIssueID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) labels, err := GetLabelsByIssueID(1) assert.NoError(t, err) if assert.Len(t, labels, 1) { @@ -250,7 +251,7 @@ func TestGetLabelsByIssueID(t *testing.T) { } func TestUpdateLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) // make sure update wont overwrite it update := &Label{ @@ -271,7 +272,7 @@ func TestUpdateLabel(t *testing.T) { } func TestDeleteLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) assert.NoError(t, DeleteLabel(label.RepoID, label.ID)) db.AssertNotExistsBean(t, &Label{ID: label.ID, RepoID: label.RepoID}) @@ -284,14 +285,14 @@ func TestDeleteLabel(t *testing.T) { } func TestHasIssueLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, HasIssueLabel(1, 1)) assert.False(t, HasIssueLabel(1, 2)) assert.False(t, HasIssueLabel(db.NonexistentID, db.NonexistentID)) } func TestNewIssueLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label := db.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) doer := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) @@ -316,7 +317,7 @@ func TestNewIssueLabel(t *testing.T) { } func TestNewIssueLabels(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label1 := db.AssertExistsAndLoadBean(t, &Label{ID: 1}).(*Label) label2 := db.AssertExistsAndLoadBean(t, &Label{ID: 2}).(*Label) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 5}).(*Issue) @@ -346,7 +347,7 @@ func TestNewIssueLabels(t *testing.T) { } func TestDeleteIssueLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(labelID, issueID, doerID int64) { label := db.AssertExistsAndLoadBean(t, &Label{ID: labelID}).(*Label) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: issueID}).(*Issue) diff --git a/models/issue_list_test.go b/models/issue_list_test.go index dadca3844c88..ea2f42e77b38 100644 --- a/models/issue_list_test.go +++ b/models/issue_list_test.go @@ -8,13 +8,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestIssueList_LoadRepositories(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issueList := IssueList{ db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue), @@ -31,7 +32,7 @@ func TestIssueList_LoadRepositories(t *testing.T) { } func TestIssueList_LoadAttributes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) setting.Service.EnableTimetracking = true issueList := IssueList{ db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue), diff --git a/models/issue_milestone_test.go b/models/issue_milestone_test.go index 099fe47c7c1c..8dee46406618 100644 --- a/models/issue_milestone_test.go +++ b/models/issue_milestone_test.go @@ -9,6 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/timeutil" @@ -23,7 +24,7 @@ func TestMilestone_State(t *testing.T) { } func TestNewMilestone(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) milestone := &Milestone{ RepoID: 1, Name: "milestoneName", @@ -36,7 +37,7 @@ func TestNewMilestone(t *testing.T) { } func TestGetMilestoneByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) milestone, err := GetMilestoneByRepoID(1, 1) assert.NoError(t, err) @@ -48,7 +49,7 @@ func TestGetMilestoneByRepoID(t *testing.T) { } func TestGetMilestonesByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64, state api.StateType) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) milestones, _, err := GetMilestones(GetMilestonesOption{ @@ -97,7 +98,7 @@ func TestGetMilestonesByRepoID(t *testing.T) { } func TestGetMilestones(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) test := func(sortType string, sortCond func(*Milestone) int) { for _, page := range []int{0, 1} { @@ -158,7 +159,7 @@ func TestGetMilestones(t *testing.T) { } func TestUpdateMilestone(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) milestone := db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) milestone.Name = " newMilestoneName " @@ -170,7 +171,7 @@ func TestUpdateMilestone(t *testing.T) { } func TestCountRepoMilestones(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) count, err := countRepoMilestones(db.GetEngine(db.DefaultContext), repoID) @@ -187,7 +188,7 @@ func TestCountRepoMilestones(t *testing.T) { } func TestCountRepoClosedMilestones(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) count, err := CountRepoClosedMilestones(repoID) @@ -204,7 +205,7 @@ func TestCountRepoClosedMilestones(t *testing.T) { } func TestChangeMilestoneStatus(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) milestone := db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) assert.NoError(t, ChangeMilestoneStatus(milestone, true)) @@ -217,7 +218,7 @@ func TestChangeMilestoneStatus(t *testing.T) { } func TestUpdateMilestoneCounters(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{MilestoneID: 1}, "is_closed=0").(*Issue) @@ -237,7 +238,7 @@ func TestUpdateMilestoneCounters(t *testing.T) { } func TestChangeMilestoneAssign(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{RepoID: 1}).(*Issue) doer := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) assert.NotNil(t, issue) @@ -256,7 +257,7 @@ func TestChangeMilestoneAssign(t *testing.T) { } func TestDeleteMilestoneByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, DeleteMilestoneByRepoID(1, 1)) db.AssertNotExistsBean(t, &Milestone{ID: 1}) CheckConsistencyFor(t, &Repository{ID: 1}) @@ -265,7 +266,7 @@ func TestDeleteMilestoneByRepoID(t *testing.T) { } func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) miles := MilestoneList{ db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone), } @@ -276,7 +277,7 @@ func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) { } func TestCountMilestonesByRepoIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) milestonesCount := func(repoID int64) (int, int) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) return repo.NumOpenMilestones, repo.NumClosedMilestones @@ -296,7 +297,7 @@ func TestCountMilestonesByRepoIDs(t *testing.T) { } func TestGetMilestonesByRepoIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) test := func(sortType string, sortCond func(*Milestone) int) { @@ -341,7 +342,7 @@ func TestGetMilestonesByRepoIDs(t *testing.T) { } func TestLoadTotalTrackedTime(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) milestone := db.AssertExistsAndLoadBean(t, &Milestone{ID: 1}).(*Milestone) assert.NoError(t, milestone.LoadTotalTrackedTime()) @@ -350,7 +351,7 @@ func TestLoadTotalTrackedTime(t *testing.T) { } func TestGetMilestonesStats(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) diff --git a/models/issue_reaction_test.go b/models/issue_reaction_test.go index dd15b816c73f..5c0441623b34 100644 --- a/models/issue_reaction_test.go +++ b/models/issue_reaction_test.go @@ -7,6 +7,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" @@ -25,7 +26,7 @@ func addReaction(t *testing.T, doer *User, issue *Issue, comment *Comment, conte } func TestIssueAddReaction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) @@ -37,7 +38,7 @@ func TestIssueAddReaction(t *testing.T) { } func TestIssueAddDuplicateReaction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) @@ -58,7 +59,7 @@ func TestIssueAddDuplicateReaction(t *testing.T) { } func TestIssueDeleteReaction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) @@ -73,7 +74,7 @@ func TestIssueDeleteReaction(t *testing.T) { } func TestIssueReactionCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) setting.UI.ReactionMaxUserNum = 2 @@ -111,7 +112,7 @@ func TestIssueReactionCount(t *testing.T) { } func TestIssueCommentAddReaction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) @@ -125,7 +126,7 @@ func TestIssueCommentAddReaction(t *testing.T) { } func TestIssueCommentDeleteReaction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) @@ -152,7 +153,7 @@ func TestIssueCommentDeleteReaction(t *testing.T) { } func TestIssueCommentReactionCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1 := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) diff --git a/models/issue_stopwatch_test.go b/models/issue_stopwatch_test.go index 11306efcf53f..0de4dd03476f 100644 --- a/models/issue_stopwatch_test.go +++ b/models/issue_stopwatch_test.go @@ -8,13 +8,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" ) func TestCancelStopwatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1, err := GetUserByID(1) assert.NoError(t, err) @@ -34,14 +35,14 @@ func TestCancelStopwatch(t *testing.T) { } func TestStopwatchExists(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, StopwatchExists(1, 1)) assert.False(t, StopwatchExists(1, 2)) } func TestHasUserStopwatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) exists, sw, err := HasUserStopwatch(1) assert.NoError(t, err) @@ -54,7 +55,7 @@ func TestHasUserStopwatch(t *testing.T) { } func TestCreateOrStopIssueStopwatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user2, err := GetUserByID(2) assert.NoError(t, err) diff --git a/models/issue_test.go b/models/issue_test.go index 9df91aeb9944..296e12a5d407 100644 --- a/models/issue_test.go +++ b/models/issue_test.go @@ -12,11 +12,12 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestIssue_ReplaceLabels(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(issueID int64, labelIDs []int64) { issue := db.AssertExistsAndLoadBean(t, &Issue{ID: issueID}).(*Issue) @@ -40,7 +41,7 @@ func TestIssue_ReplaceLabels(t *testing.T) { } func Test_GetIssueIDsByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) ids, err := GetIssueIDsByRepoID(1) assert.NoError(t, err) @@ -48,7 +49,7 @@ func Test_GetIssueIDsByRepoID(t *testing.T) { } func TestIssueAPIURL(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) err := issue.LoadAttributes() @@ -57,7 +58,7 @@ func TestIssueAPIURL(t *testing.T) { } func TestGetIssuesByIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(expectedIssueIDs, nonExistentIssueIDs []int64) { issues, err := GetIssuesByIDs(append(expectedIssueIDs, nonExistentIssueIDs...)) assert.NoError(t, err) @@ -72,7 +73,7 @@ func TestGetIssuesByIDs(t *testing.T) { } func TestGetParticipantIDsByIssue(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) checkParticipants := func(issueID int64, userIDs []int) { issue, err := GetIssueByID(issueID) @@ -106,7 +107,7 @@ func TestIssue_ClearLabels(t *testing.T) { {3, 2}, // pull-request, has no labels } for _, test := range tests { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: test.issueID}).(*Issue) doer := db.AssertExistsAndLoadBean(t, &User{ID: test.doerID}).(*User) assert.NoError(t, issue.ClearLabels(doer)) @@ -115,7 +116,7 @@ func TestIssue_ClearLabels(t *testing.T) { } func TestUpdateIssueCols(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{}).(*Issue) const newTitle = "New Title for unit test" @@ -135,7 +136,7 @@ func TestUpdateIssueCols(t *testing.T) { } func TestIssues(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) for _, test := range []struct { Opts IssuesOptions ExpectedIssueIDs []int64 @@ -190,7 +191,7 @@ func TestIssues(t *testing.T) { } func TestGetUserIssueStats(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) for _, test := range []struct { Opts UserIssueStatsOptions ExpectedIssueStats IssueStats @@ -287,7 +288,7 @@ func TestGetUserIssueStats(t *testing.T) { } func TestIssue_loadTotalTimes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) ms, err := GetIssueByID(2) assert.NoError(t, err) assert.NoError(t, ms.loadTotalTimes(db.GetEngine(db.DefaultContext))) @@ -295,7 +296,7 @@ func TestIssue_loadTotalTimes(t *testing.T) { } func TestIssue_SearchIssueIDsByKeyword(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) total, ids, err := SearchIssueIDsByKeyword("issue2", []int64{1}, 10, 0) assert.NoError(t, err) assert.EqualValues(t, 1, total) @@ -319,7 +320,7 @@ func TestIssue_SearchIssueIDsByKeyword(t *testing.T) { } func TestGetRepoIDsForIssuesOptions(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) for _, test := range []struct { Opts IssuesOptions @@ -377,7 +378,7 @@ func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *Is } func TestIssue_InsertIssue(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // there are 5 issues and max index is 5 on repository 1, so this one should 6 issue := testInsertIssue(t, "my issue1", "special issue's comments?", 6) @@ -391,7 +392,7 @@ func TestIssue_InsertIssue(t *testing.T) { } func TestIssue_ResolveMentions(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(owner, repo, doer string, mentions []string, expected []int64) { o := db.AssertExistsAndLoadBean(t, &User{LowerName: owner}).(*User) @@ -423,7 +424,7 @@ func TestIssue_ResolveMentions(t *testing.T) { } func TestResourceIndex(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) var wg sync.WaitGroup for i := 0; i < 100; i++ { @@ -437,7 +438,7 @@ func TestResourceIndex(t *testing.T) { } func TestCorrectIssueStats(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Because the condition is to have chunked database look-ups, // We have to more issues than `maxQueryParameters`, we will insert. diff --git a/models/issue_tracked_time_test.go b/models/issue_tracked_time_test.go index 7643360727fc..27700653631a 100644 --- a/models/issue_tracked_time_test.go +++ b/models/issue_tracked_time_test.go @@ -9,11 +9,12 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestAddTime(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user3, err := GetUserByID(3) assert.NoError(t, err) @@ -36,7 +37,7 @@ func TestAddTime(t *testing.T) { } func TestGetTrackedTimes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // by Issue times, err := GetTrackedTimes(&FindTrackedTimesOptions{IssueID: 1}) @@ -77,7 +78,7 @@ func TestGetTrackedTimes(t *testing.T) { } func TestTotalTimes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) total, err := TotalTimes(&FindTrackedTimesOptions{IssueID: 1}) assert.NoError(t, err) diff --git a/models/issue_user_test.go b/models/issue_user_test.go index d4e504719fc6..1a9ae6395b29 100644 --- a/models/issue_user_test.go +++ b/models/issue_user_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func Test_newIssueUsers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) newIssue := &Issue{ @@ -34,7 +35,7 @@ func Test_newIssueUsers(t *testing.T) { } func TestUpdateIssueUserByRead(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) assert.NoError(t, UpdateIssueUserByRead(4, issue.ID)) @@ -47,7 +48,7 @@ func TestUpdateIssueUserByRead(t *testing.T) { } func TestUpdateIssueUsersByMentions(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) uids := []int64{2, 5} diff --git a/models/issue_watch_test.go b/models/issue_watch_test.go index 139ed41cb608..9aaa184a349a 100644 --- a/models/issue_watch_test.go +++ b/models/issue_watch_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestCreateOrUpdateIssueWatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, CreateOrUpdateIssueWatch(3, 1, true)) iw := db.AssertExistsAndLoadBean(t, &IssueWatch{UserID: 3, IssueID: 1}).(*IssueWatch) @@ -24,7 +25,7 @@ func TestCreateOrUpdateIssueWatch(t *testing.T) { } func TestGetIssueWatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) _, exists, err := GetIssueWatch(9, 1) assert.True(t, exists) @@ -41,7 +42,7 @@ func TestGetIssueWatch(t *testing.T) { } func TestGetIssueWatchers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) iws, err := GetIssueWatchers(1, db.ListOptions{}) assert.NoError(t, err) diff --git a/models/issue_xref_test.go b/models/issue_xref_test.go index bf498e471073..a1f4515b60f2 100644 --- a/models/issue_xref_test.go +++ b/models/issue_xref_test.go @@ -9,13 +9,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/references" "github.com/stretchr/testify/assert" ) func TestXRef_AddCrossReferences(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Issue #1 to test against itarget := testCreateIssue(t, 1, 2, "title1", "content1", false) @@ -66,7 +67,7 @@ func TestXRef_AddCrossReferences(t *testing.T) { } func TestXRef_NeuterCrossReferences(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Issue #1 to test against itarget := testCreateIssue(t, 1, 2, "title1", "content1", false) @@ -88,7 +89,7 @@ func TestXRef_NeuterCrossReferences(t *testing.T) { } func TestXRef_ResolveCrossReferences(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) d := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) diff --git a/models/issues/content_history_test.go b/models/issues/content_history_test.go index dadeb484b13f..f040a7dc57f1 100644 --- a/models/issues/content_history_test.go +++ b/models/issues/content_history_test.go @@ -8,13 +8,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" ) func TestContentHistory(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) dbCtx := db.DefaultContext dbEngine := db.GetEngine(dbCtx) diff --git a/models/issues/main_test.go b/models/issues/main_test.go index 61a15c53b787..af71f038d63e 100644 --- a/models/issues/main_test.go +++ b/models/issues/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", ".."), "") + unittest.MainTest(m, filepath.Join("..", ".."), "") } diff --git a/models/login/main_test.go b/models/login/main_test.go index 141952a5941d..0666eeaad018 100644 --- a/models/login/main_test.go +++ b/models/login/main_test.go @@ -8,11 +8,11 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", ".."), + unittest.MainTest(m, filepath.Join("..", ".."), "login_source.yml", "oauth2_application.yml", "oauth2_authorization_code.yml", diff --git a/models/login/oauth2_application_test.go b/models/login/oauth2_application_test.go index cb064cef1b4d..876de5b52abd 100644 --- a/models/login/oauth2_application_test.go +++ b/models/login/oauth2_application_test.go @@ -8,6 +8,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) @@ -15,7 +16,7 @@ import ( //////////////////// Application func TestOAuth2Application_GenerateClientSecret(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) app := db.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) secret, err := app.GenerateClientSecret() assert.NoError(t, err) @@ -24,7 +25,7 @@ func TestOAuth2Application_GenerateClientSecret(t *testing.T) { } func BenchmarkOAuth2Application_GenerateClientSecret(b *testing.B) { - assert.NoError(b, db.PrepareTestDatabase()) + assert.NoError(b, unittest.PrepareTestDatabase()) app := db.AssertExistsAndLoadBean(b, &OAuth2Application{ID: 1}).(*OAuth2Application) for i := 0; i < b.N; i++ { _, _ = app.GenerateClientSecret() @@ -42,7 +43,7 @@ func TestOAuth2Application_ContainsRedirectURI(t *testing.T) { } func TestOAuth2Application_ValidateClientSecret(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) app := db.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) secret, err := app.GenerateClientSecret() assert.NoError(t, err) @@ -51,7 +52,7 @@ func TestOAuth2Application_ValidateClientSecret(t *testing.T) { } func TestGetOAuth2ApplicationByClientID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) app, err := GetOAuth2ApplicationByClientID("da7da3ba-9a13-4167-856f-3899de0b0138") assert.NoError(t, err) assert.Equal(t, "da7da3ba-9a13-4167-856f-3899de0b0138", app.ClientID) @@ -62,7 +63,7 @@ func TestGetOAuth2ApplicationByClientID(t *testing.T) { } func TestCreateOAuth2Application(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) app, err := CreateOAuth2Application(CreateOAuth2ApplicationOptions{Name: "newapp", UserID: 1}) assert.NoError(t, err) assert.Equal(t, "newapp", app.Name) @@ -75,7 +76,7 @@ func TestOAuth2Application_TableName(t *testing.T) { } func TestOAuth2Application_GetGrantByUserID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) app := db.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) grant, err := app.GetGrantByUserID(1) assert.NoError(t, err) @@ -87,7 +88,7 @@ func TestOAuth2Application_GetGrantByUserID(t *testing.T) { } func TestOAuth2Application_CreateGrant(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) app := db.AssertExistsAndLoadBean(t, &OAuth2Application{ID: 1}).(*OAuth2Application) grant, err := app.CreateGrant(2, "") assert.NoError(t, err) @@ -100,7 +101,7 @@ func TestOAuth2Application_CreateGrant(t *testing.T) { //////////////////// Grant func TestGetOAuth2GrantByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) grant, err := GetOAuth2GrantByID(1) assert.NoError(t, err) assert.Equal(t, int64(1), grant.ID) @@ -111,7 +112,7 @@ func TestGetOAuth2GrantByID(t *testing.T) { } func TestOAuth2Grant_IncreaseCounter(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) grant := db.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Counter: 1}).(*OAuth2Grant) assert.NoError(t, grant.IncreaseCounter()) assert.Equal(t, int64(2), grant.Counter) @@ -119,7 +120,7 @@ func TestOAuth2Grant_IncreaseCounter(t *testing.T) { } func TestOAuth2Grant_ScopeContains(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) grant := db.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1, Scope: "openid profile"}).(*OAuth2Grant) assert.True(t, grant.ScopeContains("openid")) assert.True(t, grant.ScopeContains("profile")) @@ -128,7 +129,7 @@ func TestOAuth2Grant_ScopeContains(t *testing.T) { } func TestOAuth2Grant_GenerateNewAuthorizationCode(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) grant := db.AssertExistsAndLoadBean(t, &OAuth2Grant{ID: 1}).(*OAuth2Grant) code, err := grant.GenerateNewAuthorizationCode("https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256") assert.NoError(t, err) @@ -141,7 +142,7 @@ func TestOAuth2Grant_TableName(t *testing.T) { } func TestGetOAuth2GrantsByUserID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) result, err := GetOAuth2GrantsByUserID(1) assert.NoError(t, err) assert.Len(t, result, 1) @@ -154,7 +155,7 @@ func TestGetOAuth2GrantsByUserID(t *testing.T) { } func TestRevokeOAuth2Grant(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, RevokeOAuth2Grant(1, 1)) db.AssertNotExistsBean(t, &OAuth2Grant{ID: 1, UserID: 1}) } @@ -162,7 +163,7 @@ func TestRevokeOAuth2Grant(t *testing.T) { //////////////////// Authorization Code func TestGetOAuth2AuthorizationByCode(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) code, err := GetOAuth2AuthorizationByCode("authcode") assert.NoError(t, err) assert.NotNil(t, code) @@ -222,7 +223,7 @@ func TestOAuth2AuthorizationCode_GenerateRedirectURI(t *testing.T) { } func TestOAuth2AuthorizationCode_Invalidate(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) code := db.AssertExistsAndLoadBean(t, &OAuth2AuthorizationCode{Code: "authcode"}).(*OAuth2AuthorizationCode) assert.NoError(t, code.Invalidate()) db.AssertNotExistsBean(t, &OAuth2AuthorizationCode{Code: "authcode"}) diff --git a/models/login/source_test.go b/models/login/source_test.go index d98609037cd5..e7ef7c70488c 100644 --- a/models/login/source_test.go +++ b/models/login/source_test.go @@ -9,6 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" @@ -34,7 +35,7 @@ func (source *TestSource) ToDB() ([]byte, error) { } func TestDumpLoginSource(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) loginSourceSchema, err := db.TableInfo(new(Source)) assert.NoError(t, err) diff --git a/models/login/u2f_test.go b/models/login/u2f_test.go index 8f5cea61508a..11f20bc79071 100644 --- a/models/login/u2f_test.go +++ b/models/login/u2f_test.go @@ -9,13 +9,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" "github.com/tstranex/u2f" ) func TestGetU2FRegistrationByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) res, err := GetU2FRegistrationByID(1) assert.NoError(t, err) @@ -27,7 +28,7 @@ func TestGetU2FRegistrationByID(t *testing.T) { } func TestGetU2FRegistrationsByUID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) res, err := GetU2FRegistrationsByUID(32) @@ -41,7 +42,7 @@ func TestU2FRegistration_TableName(t *testing.T) { } func TestU2FRegistration_UpdateCounter(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) reg := db.AssertExistsAndLoadBean(t, &U2FRegistration{ID: 1}).(*U2FRegistration) reg.Counter = 1 assert.NoError(t, reg.UpdateCounter()) @@ -49,7 +50,7 @@ func TestU2FRegistration_UpdateCounter(t *testing.T) { } func TestU2FRegistration_UpdateLargeCounter(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) reg := db.AssertExistsAndLoadBean(t, &U2FRegistration{ID: 1}).(*U2FRegistration) reg.Counter = 0xffffffff assert.NoError(t, reg.UpdateCounter()) @@ -57,7 +58,7 @@ func TestU2FRegistration_UpdateLargeCounter(t *testing.T) { } func TestCreateRegistration(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) res, err := CreateRegistration(1, "U2F Created Key", &u2f.Registration{Raw: []byte("Test")}) assert.NoError(t, err) @@ -68,7 +69,7 @@ func TestCreateRegistration(t *testing.T) { } func TestDeleteRegistration(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) reg := db.AssertExistsAndLoadBean(t, &U2FRegistration{ID: 1}).(*U2FRegistration) assert.NoError(t, DeleteRegistration(reg)) diff --git a/models/main_test.go b/models/main_test.go index ad9276330f1a..15bece7bf497 100644 --- a/models/main_test.go +++ b/models/main_test.go @@ -7,17 +7,25 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) // TestFixturesAreConsistent assert that test fixtures are consistent func TestFixturesAreConsistent(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) - CheckConsistencyForAll(t) + assert.NoError(t, unittest.PrepareTestDatabase()) + CheckConsistencyFor(t, + &User{}, + &Repository{}, + &Issue{}, + &PullRequest{}, + &Milestone{}, + &Label{}, + &Team{}, + &Action{}) } func TestMain(m *testing.M) { - db.MainTest(m, "..") + unittest.MainTest(m, "..") } diff --git a/models/migrations/migrations_test.go b/models/migrations/migrations_test.go index 46c8c66a24fa..f46070cf8e58 100644 --- a/models/migrations/migrations_test.go +++ b/models/migrations/migrations_test.go @@ -15,6 +15,7 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/base" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/setting" @@ -241,14 +242,14 @@ func prepareTestEnv(t *testing.T, skip int, syncModels ...interface{}) (*xorm.En if _, err := os.Stat(fixturesDir); err == nil { t.Logf("initializing fixtures from: %s", fixturesDir) - if err := db.InitFixtures( - db.FixturesOptions{ + if err := unittest.InitFixtures( + unittest.FixturesOptions{ Dir: fixturesDir, }, x); err != nil { t.Errorf("error whilst initializing fixtures from %s: %v", fixturesDir, err) return x, deferFn } - if err := db.LoadFixtures(x); err != nil { + if err := unittest.LoadFixtures(x); err != nil { t.Errorf("error whilst loading fixtures from %s: %v", fixturesDir, err) return x, deferFn } diff --git a/models/notification_test.go b/models/notification_test.go index 588882bed3ff..cdba409f3d7f 100644 --- a/models/notification_test.go +++ b/models/notification_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestCreateOrUpdateIssueNotifications(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 1}).(*Issue) assert.NoError(t, CreateOrUpdateIssueNotifications(issue.ID, 0, 2, 0)) @@ -27,7 +28,7 @@ func TestCreateOrUpdateIssueNotifications(t *testing.T) { } func TestNotificationsForUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) statuses := []NotificationStatus{NotificationStatusRead, NotificationStatusUnread} notfs, err := NotificationsForUser(user, statuses, 1, 10) @@ -43,7 +44,7 @@ func TestNotificationsForUser(t *testing.T) { } func TestNotification_GetRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) notf := db.AssertExistsAndLoadBean(t, &Notification{RepoID: 1}).(*Notification) repo, err := notf.GetRepo() assert.NoError(t, err) @@ -52,7 +53,7 @@ func TestNotification_GetRepo(t *testing.T) { } func TestNotification_GetIssue(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) notf := db.AssertExistsAndLoadBean(t, &Notification{RepoID: 1}).(*Notification) issue, err := notf.GetIssue() assert.NoError(t, err) @@ -61,7 +62,7 @@ func TestNotification_GetIssue(t *testing.T) { } func TestGetNotificationCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) cnt, err := GetNotificationCount(user, NotificationStatusRead) assert.NoError(t, err) @@ -73,7 +74,7 @@ func TestGetNotificationCount(t *testing.T) { } func TestSetNotificationStatus(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) notf := db.AssertExistsAndLoadBean(t, &Notification{UserID: user.ID, Status: NotificationStatusRead}).(*Notification) @@ -89,7 +90,7 @@ func TestSetNotificationStatus(t *testing.T) { } func TestUpdateNotificationStatuses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) notfUnread := db.AssertExistsAndLoadBean(t, &Notification{UserID: user.ID, Status: NotificationStatusUnread}).(*Notification) diff --git a/models/org_team_test.go b/models/org_team_test.go index f1c8f8887932..114c8016e8da 100644 --- a/models/org_team_test.go +++ b/models/org_team_test.go @@ -9,11 +9,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestTeam_IsOwnerTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) team := db.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) assert.True(t, team.IsOwnerTeam()) @@ -23,7 +24,7 @@ func TestTeam_IsOwnerTeam(t *testing.T) { } func TestTeam_IsMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) team := db.AssertExistsAndLoadBean(t, &Team{ID: 1}).(*Team) assert.True(t, team.IsMember(2)) @@ -37,7 +38,7 @@ func TestTeam_IsMember(t *testing.T) { } func TestTeam_GetRepositories(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID int64) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -52,7 +53,7 @@ func TestTeam_GetRepositories(t *testing.T) { } func TestTeam_GetMembers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID int64) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -67,7 +68,7 @@ func TestTeam_GetMembers(t *testing.T) { } func TestTeam_AddMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, userID int64) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -81,7 +82,7 @@ func TestTeam_AddMember(t *testing.T) { } func TestTeam_RemoveMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, userID int64) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -100,7 +101,7 @@ func TestTeam_RemoveMember(t *testing.T) { } func TestTeam_HasRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, repoID int64, expected bool) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -116,7 +117,7 @@ func TestTeam_HasRepository(t *testing.T) { } func TestTeam_AddRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, repoID int64) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -135,7 +136,7 @@ func TestTeam_AddRepository(t *testing.T) { } func TestTeam_RemoveRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, repoID int64) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -154,7 +155,7 @@ func TestIsUsableTeamName(t *testing.T) { } func TestNewTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) const teamName = "newTeamName" team := &Team{Name: teamName, OrgID: 3} @@ -164,7 +165,7 @@ func TestNewTeam(t *testing.T) { } func TestGetTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID int64, name string) { team, err := GetTeam(orgID, name) @@ -182,7 +183,7 @@ func TestGetTeam(t *testing.T) { } func TestGetTeamByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID int64) { team, err := GetTeamByID(teamID) @@ -200,7 +201,7 @@ func TestGetTeamByID(t *testing.T) { func TestUpdateTeam(t *testing.T) { // successful update - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) team := db.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) team.LowerName = "newname" @@ -220,7 +221,7 @@ func TestUpdateTeam(t *testing.T) { func TestUpdateTeam2(t *testing.T) { // update to already-existing team - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) team := db.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) team.LowerName = "owners" @@ -233,7 +234,7 @@ func TestUpdateTeam2(t *testing.T) { } func TestDeleteTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) team := db.AssertExistsAndLoadBean(t, &Team{ID: 2}).(*Team) assert.NoError(t, DeleteTeam(team)) @@ -250,7 +251,7 @@ func TestDeleteTeam(t *testing.T) { } func TestIsTeamMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, teamID, userID int64, expected bool) { isMember, err := IsTeamMember(orgID, teamID, userID) assert.NoError(t, err) @@ -269,7 +270,7 @@ func TestIsTeamMember(t *testing.T) { } func TestGetTeamMembers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID int64) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -285,7 +286,7 @@ func TestGetTeamMembers(t *testing.T) { } func TestGetUserTeams(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(userID int64) { teams, _, err := SearchTeam(&SearchTeamOptions{UserID: userID}) assert.NoError(t, err) @@ -299,7 +300,7 @@ func TestGetUserTeams(t *testing.T) { } func TestGetUserOrgTeams(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64) { teams, err := GetUserOrgTeams(orgID, userID) assert.NoError(t, err) @@ -314,7 +315,7 @@ func TestGetUserOrgTeams(t *testing.T) { } func TestAddTeamMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, userID int64) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -328,7 +329,7 @@ func TestAddTeamMember(t *testing.T) { } func TestRemoveTeamMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, userID int64) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -347,7 +348,7 @@ func TestRemoveTeamMember(t *testing.T) { } func TestHasTeamRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, repoID int64, expected bool) { team := db.AssertExistsAndLoadBean(t, &Team{ID: teamID}).(*Team) @@ -363,7 +364,7 @@ func TestHasTeamRepo(t *testing.T) { } func TestUsersInTeamsCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(teamIDs, userIDs []int64, expected int64) { count, err := UsersInTeamsCount(teamIDs, userIDs) diff --git a/models/org_test.go b/models/org_test.go index 2df89b2afcac..9557e14edcc3 100644 --- a/models/org_test.go +++ b/models/org_test.go @@ -8,6 +8,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" @@ -15,7 +16,7 @@ import ( ) func TestUser_IsOwnedBy(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) for _, testCase := range []struct { OrgID int64 UserID int64 @@ -36,7 +37,7 @@ func TestUser_IsOwnedBy(t *testing.T) { } func TestUser_IsOrgMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) for _, testCase := range []struct { OrgID int64 UserID int64 @@ -57,7 +58,7 @@ func TestUser_IsOrgMember(t *testing.T) { } func TestUser_GetTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) team, err := org.GetTeam("team1") assert.NoError(t, err) @@ -73,7 +74,7 @@ func TestUser_GetTeam(t *testing.T) { } func TestUser_GetOwnerTeam(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) team, err := org.GetOwnerTeam() assert.NoError(t, err) @@ -85,7 +86,7 @@ func TestUser_GetOwnerTeam(t *testing.T) { } func TestUser_GetTeams(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) assert.NoError(t, org.LoadTeams()) if assert.Len(t, org.Teams, 4) { @@ -97,7 +98,7 @@ func TestUser_GetTeams(t *testing.T) { } func TestUser_GetMembers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) assert.NoError(t, org.GetMembers()) if assert.Len(t, org.Members, 3) { @@ -108,7 +109,7 @@ func TestUser_GetMembers(t *testing.T) { } func TestUser_AddMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) // add a user that is not a member @@ -131,7 +132,7 @@ func TestUser_AddMember(t *testing.T) { } func TestUser_RemoveMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) // remove a user that is a member @@ -154,7 +155,7 @@ func TestUser_RemoveMember(t *testing.T) { } func TestUser_RemoveOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) repo := db.AssertExistsAndLoadBean(t, &Repository{OwnerID: org.ID}).(*Repository) @@ -178,7 +179,7 @@ func TestUser_RemoveOrgRepo(t *testing.T) { func TestCreateOrganization(t *testing.T) { // successful creation of org - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) const newOrgName = "neworg" @@ -198,7 +199,7 @@ func TestCreateOrganization(t *testing.T) { func TestCreateOrganization2(t *testing.T) { // unauthorized creation of org - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) owner := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) const newOrgName = "neworg" @@ -216,7 +217,7 @@ func TestCreateOrganization2(t *testing.T) { func TestCreateOrganization3(t *testing.T) { // create org with same name as existent org - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) org := &User{Name: "user3"} // should already exist @@ -229,7 +230,7 @@ func TestCreateOrganization3(t *testing.T) { func TestCreateOrganization4(t *testing.T) { // create org with unusable name - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) err := CreateOrganization(&User{Name: "assets"}, owner) @@ -239,7 +240,7 @@ func TestCreateOrganization4(t *testing.T) { } func TestGetOrgByName(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org, err := GetOrgByName("user3") assert.NoError(t, err) @@ -254,14 +255,14 @@ func TestGetOrgByName(t *testing.T) { } func TestCountOrganizations(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) expected, err := db.GetEngine(db.DefaultContext).Where("type=?", UserTypeOrganization).Count(&User{}) assert.NoError(t, err) assert.Equal(t, expected, CountOrganizations()) } func TestDeleteOrganization(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 6}).(*User) assert.NoError(t, DeleteOrganization(org)) db.AssertNotExistsBean(t, &User{ID: 6}) @@ -279,7 +280,7 @@ func TestDeleteOrganization(t *testing.T) { } func TestIsOrganizationOwner(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64, expected bool) { isOwner, err := IsOrganizationOwner(orgID, userID) assert.NoError(t, err) @@ -293,7 +294,7 @@ func TestIsOrganizationOwner(t *testing.T) { } func TestIsOrganizationMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64, expected bool) { isMember, err := IsOrganizationMember(orgID, userID) assert.NoError(t, err) @@ -308,7 +309,7 @@ func TestIsOrganizationMember(t *testing.T) { } func TestIsPublicMembership(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64, expected bool) { isMember, err := IsPublicMembership(orgID, userID) assert.NoError(t, err) @@ -323,7 +324,7 @@ func TestIsPublicMembership(t *testing.T) { } func TestGetOrgsByUserID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) orgs, err := GetOrgsByUserID(4, true) assert.NoError(t, err) @@ -337,7 +338,7 @@ func TestGetOrgsByUserID(t *testing.T) { } func TestGetOwnedOrgsByUserID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) orgs, err := GetOwnedOrgsByUserID(2) assert.NoError(t, err) @@ -351,7 +352,7 @@ func TestGetOwnedOrgsByUserID(t *testing.T) { } func TestGetOwnedOrgsByUserIDDesc(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) orgs, err := GetOwnedOrgsByUserIDDesc(5, "id") assert.NoError(t, err) @@ -366,7 +367,7 @@ func TestGetOwnedOrgsByUserIDDesc(t *testing.T) { } func TestGetOrgUsersByUserID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) orgUsers, err := GetOrgUsersByUserID(5, &SearchOrganizationsOptions{All: true}) assert.NoError(t, err) @@ -396,7 +397,7 @@ func TestGetOrgUsersByUserID(t *testing.T) { } func TestGetOrgUsersByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) orgUsers, err := GetOrgUsersByOrgID(&FindOrgMembersOpts{ ListOptions: db.ListOptions{}, @@ -429,7 +430,7 @@ func TestGetOrgUsersByOrgID(t *testing.T) { } func TestChangeOrgUserStatus(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID, userID int64, public bool) { assert.NoError(t, ChangeOrgUserStatus(orgID, userID, public)) @@ -444,7 +445,7 @@ func TestChangeOrgUserStatus(t *testing.T) { } func TestAddOrgUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID, userID int64, isPublic bool) { org := db.AssertExistsAndLoadBean(t, &User{ID: orgID}).(*User) expectedNumMembers := org.NumMembers @@ -471,7 +472,7 @@ func TestAddOrgUser(t *testing.T) { } func TestRemoveOrgUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID, userID int64) { org := db.AssertExistsAndLoadBean(t, &User{ID: orgID}).(*User) expectedNumMembers := org.NumMembers @@ -494,7 +495,7 @@ func TestRemoveOrgUser(t *testing.T) { } func TestUser_GetUserTeamIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) testSuccess := func(userID int64, expected []int64) { teamIDs, err := org.GetUserTeamIDs(userID) @@ -507,7 +508,7 @@ func TestUser_GetUserTeamIDs(t *testing.T) { } func TestAccessibleReposEnv_CountRepos(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) testSuccess := func(userID, expectedCount int64) { env, err := org.AccessibleReposEnv(userID) @@ -521,7 +522,7 @@ func TestAccessibleReposEnv_CountRepos(t *testing.T) { } func TestAccessibleReposEnv_RepoIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) testSuccess := func(userID, _, pageSize int64, expectedRepoIDs []int64) { env, err := org.AccessibleReposEnv(userID) @@ -535,7 +536,7 @@ func TestAccessibleReposEnv_RepoIDs(t *testing.T) { } func TestAccessibleReposEnv_Repos(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) testSuccess := func(userID int64, expectedRepoIDs []int64) { env, err := org.AccessibleReposEnv(userID) @@ -554,7 +555,7 @@ func TestAccessibleReposEnv_Repos(t *testing.T) { } func TestAccessibleReposEnv_MirrorRepos(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) org := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) testSuccess := func(userID int64, expectedRepoIDs []int64) { env, err := org.AccessibleReposEnv(userID) @@ -573,7 +574,7 @@ func TestAccessibleReposEnv_MirrorRepos(t *testing.T) { } func TestHasOrgVisibleTypePublic(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user3 := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) @@ -596,7 +597,7 @@ func TestHasOrgVisibleTypePublic(t *testing.T) { } func TestHasOrgVisibleTypeLimited(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user3 := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) @@ -619,7 +620,7 @@ func TestHasOrgVisibleTypeLimited(t *testing.T) { } func TestHasOrgVisibleTypePrivate(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) owner := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user3 := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) @@ -642,7 +643,7 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) { } func TestGetUsersWhoCanCreateOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) users, err := GetUsersWhoCanCreateOrgRepo(3) assert.NoError(t, err) diff --git a/models/project_test.go b/models/project_test.go index 8c630d8bedd5..70dabb7674fe 100644 --- a/models/project_test.go +++ b/models/project_test.go @@ -7,7 +7,7 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" @@ -32,7 +32,7 @@ func TestIsProjectTypeValid(t *testing.T) { } func TestGetProjects(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) projects, _, err := GetProjects(ProjectSearchOptions{RepoID: 1}) assert.NoError(t, err) @@ -48,7 +48,7 @@ func TestGetProjects(t *testing.T) { } func TestProject(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) project := &Project{ Type: ProjectTypeRepository, diff --git a/models/protected_tag_test.go b/models/protected_tag_test.go index fd29f7e64b2c..ed838483d2e5 100644 --- a/models/protected_tag_test.go +++ b/models/protected_tag_test.go @@ -7,12 +7,13 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestIsUserAllowed(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pt := &ProtectedTag{} allowed, err := pt.IsUserAllowed(1) diff --git a/models/pull_test.go b/models/pull_test.go index e6855240db06..54083355ab56 100644 --- a/models/pull_test.go +++ b/models/pull_test.go @@ -9,11 +9,12 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestPullRequest_LoadAttributes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) assert.NoError(t, pr.LoadAttributes()) assert.NotNil(t, pr.Merger) @@ -21,7 +22,7 @@ func TestPullRequest_LoadAttributes(t *testing.T) { } func TestPullRequest_LoadIssue(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) assert.NoError(t, pr.LoadIssue()) assert.NotNil(t, pr.Issue) @@ -32,7 +33,7 @@ func TestPullRequest_LoadIssue(t *testing.T) { } func TestPullRequest_LoadBaseRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) assert.NoError(t, pr.LoadBaseRepo()) assert.NotNil(t, pr.BaseRepo) @@ -43,7 +44,7 @@ func TestPullRequest_LoadBaseRepo(t *testing.T) { } func TestPullRequest_LoadHeadRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) assert.NoError(t, pr.LoadHeadRepo()) assert.NotNil(t, pr.HeadRepo) @@ -55,7 +56,7 @@ func TestPullRequest_LoadHeadRepo(t *testing.T) { // TODO TestNewPullRequest func TestPullRequestsNewest(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) prs, count, err := PullRequests(1, &PullRequestsOptions{ ListOptions: db.ListOptions{ Page: 1, @@ -74,7 +75,7 @@ func TestPullRequestsNewest(t *testing.T) { } func TestPullRequestsOldest(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) prs, count, err := PullRequests(1, &PullRequestsOptions{ ListOptions: db.ListOptions{ Page: 1, @@ -93,7 +94,7 @@ func TestPullRequestsOldest(t *testing.T) { } func TestGetUnmergedPullRequest(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr, err := GetUnmergedPullRequest(1, 1, "branch2", "master", PullRequestFlowGithub) assert.NoError(t, err) assert.Equal(t, int64(2), pr.ID) @@ -104,7 +105,7 @@ func TestGetUnmergedPullRequest(t *testing.T) { } func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) prs, err := GetUnmergedPullRequestsByHeadInfo(1, "branch2") assert.NoError(t, err) assert.Len(t, prs, 1) @@ -115,7 +116,7 @@ func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) { } func TestGetUnmergedPullRequestsByBaseInfo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) prs, err := GetUnmergedPullRequestsByBaseInfo(1, "master") assert.NoError(t, err) assert.Len(t, prs, 1) @@ -126,7 +127,7 @@ func TestGetUnmergedPullRequestsByBaseInfo(t *testing.T) { } func TestGetPullRequestByIndex(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr, err := GetPullRequestByIndex(1, 2) assert.NoError(t, err) assert.Equal(t, int64(1), pr.BaseRepoID) @@ -142,7 +143,7 @@ func TestGetPullRequestByIndex(t *testing.T) { } func TestGetPullRequestByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr, err := GetPullRequestByID(1) assert.NoError(t, err) assert.Equal(t, int64(1), pr.ID) @@ -154,7 +155,7 @@ func TestGetPullRequestByID(t *testing.T) { } func TestGetPullRequestByIssueID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr, err := GetPullRequestByIssueID(2) assert.NoError(t, err) assert.Equal(t, int64(2), pr.IssueID) @@ -165,7 +166,7 @@ func TestGetPullRequestByIssueID(t *testing.T) { } func TestPullRequest_Update(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest) pr.BaseBranch = "baseBranch" pr.HeadBranch = "headBranch" @@ -178,7 +179,7 @@ func TestPullRequest_Update(t *testing.T) { } func TestPullRequest_UpdateCols(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr := &PullRequest{ ID: 1, BaseBranch: "baseBranch", @@ -193,7 +194,7 @@ func TestPullRequest_UpdateCols(t *testing.T) { } func TestPullRequestList_LoadAttributes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) prs := []*PullRequest{ db.AssertExistsAndLoadBean(t, &PullRequest{ID: 1}).(*PullRequest), @@ -211,7 +212,7 @@ func TestPullRequestList_LoadAttributes(t *testing.T) { // TODO TestAddTestPullRequestTask func TestPullRequest_IsWorkInProgress(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) pr.LoadIssue() @@ -226,7 +227,7 @@ func TestPullRequest_IsWorkInProgress(t *testing.T) { } func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) pr.LoadIssue() @@ -242,7 +243,7 @@ func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) { } func TestPullRequest_GetDefaultMergeMessage_InternalTracker(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pr := db.AssertExistsAndLoadBean(t, &PullRequest{ID: 2}).(*PullRequest) assert.Equal(t, "Merge pull request 'issue3' (#3) from branch2 into master", pr.GetDefaultMergeMessage()) @@ -253,7 +254,7 @@ func TestPullRequest_GetDefaultMergeMessage_InternalTracker(t *testing.T) { } func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) externalTracker := RepoUnit{ Type: unit.TypeExternalTracker, diff --git a/models/repo_collaboration_test.go b/models/repo_collaboration_test.go index 326fb4dbf7a8..5e6a0a5d94aa 100644 --- a/models/repo_collaboration_test.go +++ b/models/repo_collaboration_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestRepository_AddCollaborator(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(repoID, userID int64) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) @@ -27,7 +28,7 @@ func TestRepository_AddCollaborator(t *testing.T) { } func TestRepository_GetCollaborators(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) collaborators, err := repo.GetCollaborators(db.ListOptions{}) @@ -47,7 +48,7 @@ func TestRepository_GetCollaborators(t *testing.T) { } func TestRepository_IsCollaborator(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID, userID int64, expected bool) { repo := db.AssertExistsAndLoadBean(t, &Repository{ID: repoID}).(*Repository) @@ -62,7 +63,7 @@ func TestRepository_IsCollaborator(t *testing.T) { } func TestRepository_ChangeCollaborationAccessMode(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) assert.NoError(t, repo.ChangeCollaborationAccessMode(4, AccessModeAdmin)) @@ -81,7 +82,7 @@ func TestRepository_ChangeCollaborationAccessMode(t *testing.T) { } func TestRepository_DeleteCollaboration(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) assert.NoError(t, repo.GetOwner()) diff --git a/models/repo_list_test.go b/models/repo_list_test.go index 3c30cad564d6..eaf5e8a7ceee 100644 --- a/models/repo_list_test.go +++ b/models/repo_list_test.go @@ -8,13 +8,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" ) func TestSearchRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // test search public repository on explore page repos, count, err := SearchRepositoryByName(&SearchRepoOptions{ @@ -324,7 +325,7 @@ func TestSearchRepository(t *testing.T) { } func TestSearchRepositoryByTopicName(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testCases := []struct { name string diff --git a/models/repo_permission_test.go b/models/repo_permission_test.go index 5e43937776f7..1f04a45315f3 100644 --- a/models/repo_permission_test.go +++ b/models/repo_permission_test.go @@ -9,11 +9,12 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // public non-organization repo repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) @@ -66,7 +67,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { } func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // private non-organization repo repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) @@ -118,7 +119,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { } func TestRepoPermissionPublicOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // public organization repo repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 32}).(*Repository) @@ -180,7 +181,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { } func TestRepoPermissionPrivateOrgRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // private organization repo repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 24}).(*Repository) diff --git a/models/repo_pushmirror_test.go b/models/repo_pushmirror_test.go index 65ef91814163..aa4465082f7c 100644 --- a/models/repo_pushmirror_test.go +++ b/models/repo_pushmirror_test.go @@ -8,14 +8,14 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" ) func TestPushMirrorsIterate(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) now := timeutil.TimeStampNow() diff --git a/models/repo_redirect_test.go b/models/repo_redirect_test.go index 9400422752cb..bf42d4854c2b 100644 --- a/models/repo_redirect_test.go +++ b/models/repo_redirect_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestLookupRepoRedirect(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repoID, err := LookupRepoRedirect(2, "oldrepo1") assert.NoError(t, err) @@ -24,7 +25,7 @@ func TestLookupRepoRedirect(t *testing.T) { func TestNewRepoRedirect(t *testing.T) { // redirect to a completely new name - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "newreponame")) @@ -43,7 +44,7 @@ func TestNewRepoRedirect(t *testing.T) { func TestNewRepoRedirect2(t *testing.T) { // redirect to previously used name - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "oldrepo1")) @@ -62,7 +63,7 @@ func TestNewRepoRedirect2(t *testing.T) { func TestNewRepoRedirect3(t *testing.T) { // redirect for a previously-unredirected repo - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) assert.NoError(t, newRepoRedirect(db.GetEngine(db.DefaultContext), repo.OwnerID, repo.ID, repo.Name, "newreponame")) diff --git a/models/repo_test.go b/models/repo_test.go index 425e8c01913e..2eb6e817ec5e 100644 --- a/models/repo_test.go +++ b/models/repo_test.go @@ -14,13 +14,14 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unit" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/markup" "github.com/stretchr/testify/assert" ) func TestMetas(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := &Repository{Name: "testRepo"} repo.Owner = &User{Name: "testOwner"} @@ -68,7 +69,7 @@ func TestMetas(t *testing.T) { } func TestGetRepositoryCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) count, err1 := GetRepositoryCount(&User{ID: int64(10)}) privateCount, err2 := GetPrivateRepositoryCount(&User{ID: int64(10)}) @@ -81,7 +82,7 @@ func TestGetRepositoryCount(t *testing.T) { } func TestGetPublicRepositoryCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) count, err := GetPublicRepositoryCount(&User{ID: int64(10)}) assert.NoError(t, err) @@ -89,7 +90,7 @@ func TestGetPublicRepositoryCount(t *testing.T) { } func TestGetPrivateRepositoryCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) count, err := GetPrivateRepositoryCount(&User{ID: int64(10)}) assert.NoError(t, err) @@ -97,7 +98,7 @@ func TestGetPrivateRepositoryCount(t *testing.T) { } func TestUpdateRepositoryVisibilityChanged(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Get sample repo and change visibility repo, err := GetRepositoryByID(9) @@ -117,7 +118,7 @@ func TestUpdateRepositoryVisibilityChanged(t *testing.T) { } func TestGetUserFork(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // User13 has repo 11 forked from repo10 repo, err := GetRepositoryByID(10) @@ -136,7 +137,7 @@ func TestGetUserFork(t *testing.T) { } func TestRepoAPIURL(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) assert.Equal(t, "https://try.gitea.io/api/v1/repos/user12/repo10", repo.APIURL()) @@ -148,7 +149,7 @@ func TestUploadAvatar(t *testing.T) { var buff bytes.Buffer png.Encode(&buff, myImage) - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) err := repo.UploadAvatar(buff.Bytes()) @@ -162,7 +163,7 @@ func TestUploadBigAvatar(t *testing.T) { var buff bytes.Buffer png.Encode(&buff, myImage) - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) err := repo.UploadAvatar(buff.Bytes()) @@ -175,7 +176,7 @@ func TestDeleteAvatar(t *testing.T) { var buff bytes.Buffer png.Encode(&buff, myImage) - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 10}).(*Repository) err := repo.UploadAvatar(buff.Bytes()) @@ -188,13 +189,13 @@ func TestDeleteAvatar(t *testing.T) { } func TestDoctorUserStarNum(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, DoctorUserStarNum()) } func TestRepoGetReviewers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // test public repo repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) @@ -211,7 +212,7 @@ func TestRepoGetReviewers(t *testing.T) { } func TestRepoGetReviewerTeams(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) teams, err := repo2.GetReviewerTeams() diff --git a/models/repo_transfer_test.go b/models/repo_transfer_test.go index 4c6b7254c21a..71976def961b 100644 --- a/models/repo_transfer_test.go +++ b/models/repo_transfer_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestRepositoryTransfer(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) doer := db.AssertExistsAndLoadBean(t, &User{ID: 3}).(*User) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) diff --git a/models/repo_watch_test.go b/models/repo_watch_test.go index 52222af2ca14..9f20a088f5a6 100644 --- a/models/repo_watch_test.go +++ b/models/repo_watch_test.go @@ -8,13 +8,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestIsWatching(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, IsWatching(1, 1)) assert.True(t, IsWatching(4, 1)) @@ -26,7 +27,7 @@ func TestIsWatching(t *testing.T) { } func TestWatchRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) const repoID = 3 const userID = 2 @@ -40,7 +41,7 @@ func TestWatchRepo(t *testing.T) { } func TestGetWatchers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) watches, err := GetWatchers(repo.ID) @@ -57,7 +58,7 @@ func TestGetWatchers(t *testing.T) { } func TestRepository_GetWatchers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) watchers, err := repo.GetWatchers(db.ListOptions{Page: 1}) @@ -74,7 +75,7 @@ func TestRepository_GetWatchers(t *testing.T) { } func TestNotifyWatchers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) action := &Action{ ActUserID: 8, @@ -111,7 +112,7 @@ func TestNotifyWatchers(t *testing.T) { } func TestWatchIfAuto(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) watchers, err := repo.GetWatchers(db.ListOptions{Page: 1}) @@ -168,7 +169,7 @@ func TestWatchIfAuto(t *testing.T) { } func TestWatchRepoMode(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) db.AssertCount(t, &Watch{UserID: 12, RepoID: 1}, 0) diff --git a/models/review_test.go b/models/review_test.go index c809a3d66222..31d6c4553551 100644 --- a/models/review_test.go +++ b/models/review_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestGetReviewByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) review, err := GetReviewByID(1) assert.NoError(t, err) assert.Equal(t, "Demo Review", review.Content) @@ -24,7 +25,7 @@ func TestGetReviewByID(t *testing.T) { } func TestReview_LoadAttributes(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) review := db.AssertExistsAndLoadBean(t, &Review{ID: 1}).(*Review) assert.NoError(t, review.LoadAttributes()) assert.NotNil(t, review.Issue) @@ -38,7 +39,7 @@ func TestReview_LoadAttributes(t *testing.T) { } func TestReview_LoadCodeComments(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) review := db.AssertExistsAndLoadBean(t, &Review{ID: 4}).(*Review) assert.NoError(t, review.LoadAttributes()) @@ -57,7 +58,7 @@ func TestReviewType_Icon(t *testing.T) { } func TestFindReviews(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) reviews, err := FindReviews(FindReviewOptions{ Type: ReviewTypeApprove, IssueID: 2, @@ -69,7 +70,7 @@ func TestFindReviews(t *testing.T) { } func TestGetCurrentReview(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) @@ -87,7 +88,7 @@ func TestGetCurrentReview(t *testing.T) { } func TestCreateReview(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 2}).(*Issue) user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) @@ -104,7 +105,7 @@ func TestCreateReview(t *testing.T) { } func TestGetReviewersByIssueID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &Issue{ID: 3}).(*Issue) user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) @@ -144,7 +145,7 @@ func TestGetReviewersByIssueID(t *testing.T) { } func TestDismissReview(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) rejectReviewExample := db.AssertExistsAndLoadBean(t, &Review{ID: 9}).(*Review) requestReviewExample := db.AssertExistsAndLoadBean(t, &Review{ID: 11}).(*Review) diff --git a/models/star_test.go b/models/star_test.go index 326da8a861d9..8e448ae7cf7d 100644 --- a/models/star_test.go +++ b/models/star_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestStarRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) const userID = 2 const repoID = 1 db.AssertNotExistsBean(t, &Star{UID: userID, RepoID: repoID}) @@ -25,14 +26,14 @@ func TestStarRepo(t *testing.T) { } func TestIsStaring(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, IsStaring(2, 4)) assert.False(t, IsStaring(3, 4)) } func TestRepository_GetStargazers(t *testing.T) { // repo with stargazers - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 4}).(*Repository) gazers, err := repo.GetStargazers(db.ListOptions{Page: 0}) assert.NoError(t, err) @@ -43,7 +44,7 @@ func TestRepository_GetStargazers(t *testing.T) { func TestRepository_GetStargazers2(t *testing.T) { // repo with stargazers - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 3}).(*Repository) gazers, err := repo.GetStargazers(db.ListOptions{Page: 0}) assert.NoError(t, err) @@ -52,7 +53,7 @@ func TestRepository_GetStargazers2(t *testing.T) { func TestUser_GetStarredRepos(t *testing.T) { // user who has starred repos - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) starred, err := user.GetStarredRepos(false, 1, 10, "") @@ -71,7 +72,7 @@ func TestUser_GetStarredRepos(t *testing.T) { func TestUser_GetStarredRepos2(t *testing.T) { // user who has no starred repos - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) starred, err := user.GetStarredRepos(false, 1, 10, "") @@ -84,7 +85,7 @@ func TestUser_GetStarredRepos2(t *testing.T) { } func TestUserGetStarredRepoCount(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) counts, err := user.GetStarredRepoCount(false) diff --git a/models/token_test.go b/models/token_test.go index 21d827ea6158..0161764596ec 100644 --- a/models/token_test.go +++ b/models/token_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestNewAccessToken(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) token := &AccessToken{ UID: 3, Name: "Token C", @@ -31,7 +32,7 @@ func TestNewAccessToken(t *testing.T) { func TestAccessTokenByNameExists(t *testing.T) { name := "Token Gitea" - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) token := &AccessToken{ UID: 3, Name: name, @@ -64,7 +65,7 @@ func TestAccessTokenByNameExists(t *testing.T) { } func TestGetAccessTokenBySHA(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) token, err := GetAccessTokenBySHA("d2c6c1ba3890b309189a8e618c72a162e4efbf36") assert.NoError(t, err) assert.Equal(t, int64(1), token.UID) @@ -82,7 +83,7 @@ func TestGetAccessTokenBySHA(t *testing.T) { } func TestListAccessTokens(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tokens, err := ListAccessTokens(ListAccessTokensOptions{UserID: 1}) assert.NoError(t, err) if assert.Len(t, tokens, 2) { @@ -105,7 +106,7 @@ func TestListAccessTokens(t *testing.T) { } func TestUpdateAccessToken(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) token, err := GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") assert.NoError(t, err) token.Name = "Token Z" @@ -115,7 +116,7 @@ func TestUpdateAccessToken(t *testing.T) { } func TestDeleteAccessTokenByID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) token, err := GetAccessTokenBySHA("4c6f36e6cf498e2a448662f915d932c09c5a146c") assert.NoError(t, err) diff --git a/models/topic_test.go b/models/topic_test.go index b069deaba3c2..def946b66688 100644 --- a/models/topic_test.go +++ b/models/topic_test.go @@ -8,6 +8,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) @@ -16,7 +17,7 @@ func TestAddTopic(t *testing.T) { repo1NrOfTopics := 3 repo2NrOfTopics := 2 - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) topics, _, err := FindTopics(&FindTopicOptions{}) assert.NoError(t, err) diff --git a/models/unittest/bridge.go b/models/unittest/bridge.go new file mode 100644 index 000000000000..776dd6951977 --- /dev/null +++ b/models/unittest/bridge.go @@ -0,0 +1,54 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package unittest + +import ( + "code.gitea.io/gitea/modules/unittestbridge" + "github.com/stretchr/testify/assert" +) + +// For legacy code only, please refer to the `unittestbridge` package. + +// TestifyAsserter uses "stretchr/testify/assert" to do assert +type TestifyAsserter struct { + t unittestbridge.Tester +} + +// Errorf assert Errorf +func (ta TestifyAsserter) Errorf(format string, args ...interface{}) { + ta.t.Errorf(format, args) +} + +// NoError assert NoError +func (ta TestifyAsserter) NoError(err error, msgAndArgs ...interface{}) bool { + return assert.NoError(ta, err, msgAndArgs...) +} + +// EqualValues assert EqualValues +func (ta TestifyAsserter) EqualValues(expected, actual interface{}, msgAndArgs ...interface{}) bool { + return assert.EqualValues(ta, expected, actual, msgAndArgs...) +} + +// Equal assert Equal +func (ta TestifyAsserter) Equal(expected, actual interface{}, msgAndArgs ...interface{}) bool { + return assert.Equal(ta, expected, actual, msgAndArgs...) +} + +// True assert True +func (ta TestifyAsserter) True(value bool, msgAndArgs ...interface{}) bool { + return assert.True(ta, value, msgAndArgs...) +} + +// False assert False +func (ta TestifyAsserter) False(value bool, msgAndArgs ...interface{}) bool { + return assert.False(ta, value, msgAndArgs...) +} + +// InitUnitTestBridge init the unit test bridge. eg: models.CheckConsistencyFor can use testing and assert frameworks +func InitUnitTestBridge() { + unittestbridge.SetNewAsserterFunc(func(t unittestbridge.Tester) unittestbridge.Asserter { + return &TestifyAsserter{t: t} + }) +} diff --git a/models/db/test_fixtures.go b/models/unittest/fixtures.go similarity index 89% rename from models/db/test_fixtures.go rename to models/unittest/fixtures.go index 2715b688ea35..af60df7b68e8 100644 --- a/models/db/test_fixtures.go +++ b/models/unittest/fixtures.go @@ -1,28 +1,34 @@ -// Copyright 2017 The Gitea Authors. All rights reserved. +// Copyright 2021 The Gitea Authors. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. -package db +package unittest import ( "fmt" "os" "time" + "code.gitea.io/gitea/models/db" + "github.com/go-testfixtures/testfixtures/v3" + "xorm.io/xorm" "xorm.io/xorm/schemas" ) var fixtures *testfixtures.Loader -// InitFixtures initialize test fixtures for a test database -func InitFixtures(opts FixturesOptions, engine ...*xorm.Engine) (err error) { - e := x +func getXORMEngine(engine ...*xorm.Engine) (x *xorm.Engine) { if len(engine) == 1 { - e = engine[0] + return engine[0] } + return db.DefaultContext.(*db.Context).Engine().(*xorm.Engine) +} +// InitFixtures initialize test fixtures for a test database +func InitFixtures(opts FixturesOptions, engine ...*xorm.Engine) (err error) { + e := getXORMEngine(engine...) var testfiles func(*testfixtures.Loader) error if opts.Dir != "" { testfiles = testfixtures.Directory(opts.Dir) @@ -64,10 +70,7 @@ func InitFixtures(opts FixturesOptions, engine ...*xorm.Engine) (err error) { // LoadFixtures load fixtures for a test database func LoadFixtures(engine ...*xorm.Engine) error { - e := x - if len(engine) == 1 { - e = engine[0] - } + e := getXORMEngine(engine...) var err error // Database transaction conflicts could occur and result in ROLLBACK // As a simple workaround, we just retry 20 times. diff --git a/models/unittest/testdb.go b/models/unittest/testdb.go new file mode 100644 index 000000000000..b4f8c813af54 --- /dev/null +++ b/models/unittest/testdb.go @@ -0,0 +1,154 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package unittest + +import ( + "fmt" + "net/url" + "os" + "path/filepath" + "testing" + + "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/modules/base" + "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/storage" + "code.gitea.io/gitea/modules/util" + + "github.com/stretchr/testify/assert" + + "xorm.io/xorm" + "xorm.io/xorm/names" +) + +// giteaRoot a path to the gitea root +var ( + giteaRoot string + fixturesDir string +) + +// FixturesDir returns the fixture directory +func FixturesDir() string { + return fixturesDir +} + +func fatalTestError(fmtStr string, args ...interface{}) { + _, _ = fmt.Fprintf(os.Stderr, fmtStr, args...) + os.Exit(1) +} + +// MainTest a reusable TestMain(..) function for unit tests that need to use a +// test database. Creates the test database, and sets necessary settings. +func MainTest(m *testing.M, pathToGiteaRoot string, fixtureFiles ...string) { + var err error + InitUnitTestBridge() + giteaRoot = pathToGiteaRoot + fixturesDir = filepath.Join(pathToGiteaRoot, "models", "fixtures") + + var opts FixturesOptions + if len(fixtureFiles) == 0 { + opts.Dir = fixturesDir + } else { + for _, f := range fixtureFiles { + if len(f) != 0 { + opts.Files = append(opts.Files, filepath.Join(fixturesDir, f)) + } + } + } + + if err = CreateTestEngine(opts); err != nil { + fatalTestError("Error creating test engine: %v\n", err) + } + + setting.AppURL = "https://try.gitea.io/" + setting.RunUser = "runuser" + setting.SSH.Port = 3000 + setting.SSH.Domain = "try.gitea.io" + setting.Database.UseSQLite3 = true + setting.RepoRootPath, err = os.MkdirTemp(os.TempDir(), "repos") + if err != nil { + fatalTestError("TempDir: %v\n", err) + } + setting.AppDataPath, err = os.MkdirTemp(os.TempDir(), "appdata") + if err != nil { + fatalTestError("TempDir: %v\n", err) + } + setting.AppWorkPath = pathToGiteaRoot + setting.StaticRootPath = pathToGiteaRoot + setting.GravatarSourceURL, err = url.Parse("https://secure.gravatar.com/avatar/") + if err != nil { + fatalTestError("url.Parse: %v\n", err) + } + setting.Attachment.Storage.Path = filepath.Join(setting.AppDataPath, "attachments") + + setting.LFS.Storage.Path = filepath.Join(setting.AppDataPath, "lfs") + + setting.Avatar.Storage.Path = filepath.Join(setting.AppDataPath, "avatars") + + setting.RepoAvatar.Storage.Path = filepath.Join(setting.AppDataPath, "repo-avatars") + + setting.RepoArchive.Storage.Path = filepath.Join(setting.AppDataPath, "repo-archive") + + if err = storage.Init(); err != nil { + fatalTestError("storage.Init: %v\n", err) + } + + if err = util.RemoveAll(setting.RepoRootPath); err != nil { + fatalTestError("util.RemoveAll: %v\n", err) + } + if err = util.CopyDir(filepath.Join(pathToGiteaRoot, "integrations", "gitea-repositories-meta"), setting.RepoRootPath); err != nil { + fatalTestError("util.CopyDir: %v\n", err) + } + + exitStatus := m.Run() + if err = util.RemoveAll(setting.RepoRootPath); err != nil { + fatalTestError("util.RemoveAll: %v\n", err) + } + if err = util.RemoveAll(setting.AppDataPath); err != nil { + fatalTestError("util.RemoveAll: %v\n", err) + } + os.Exit(exitStatus) +} + +// FixturesOptions fixtures needs to be loaded options +type FixturesOptions struct { + Dir string + Files []string +} + +// CreateTestEngine creates a memory database and loads the fixture data from fixturesDir +func CreateTestEngine(opts FixturesOptions) error { + x, err := xorm.NewEngine("sqlite3", "file::memory:?cache=shared&_txlock=immediate") + if err != nil { + return err + } + x.SetMapper(names.GonicMapper{}) + db.SetUnitTestEngine(x) + + if err = db.SyncAllTables(); err != nil { + return err + } + switch os.Getenv("GITEA_UNIT_TESTS_VERBOSE") { + case "true", "1": + x.ShowSQL(true) + } + + return InitFixtures(opts) +} + +// PrepareTestDatabase load test fixtures into test database +func PrepareTestDatabase() error { + return LoadFixtures() +} + +// PrepareTestEnv prepares the environment for unit tests. Can only be called +// by tests that use the above MainTest(..) function. +func PrepareTestEnv(t testing.TB) { + assert.NoError(t, PrepareTestDatabase()) + assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) + metaPath := filepath.Join(giteaRoot, "integrations", "gitea-repositories-meta") + assert.NoError(t, util.CopyDir(metaPath, setting.RepoRootPath)) + base.SetupGiteaRoot() // Makes sure GITEA_ROOT is set +} diff --git a/models/user/email_address_test.go b/models/user/email_address_test.go index 5ed0bf88841a..642c2b387697 100644 --- a/models/user/email_address_test.go +++ b/models/user/email_address_test.go @@ -8,12 +8,13 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestGetEmailAddresses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) emails, _ := GetEmailAddresses(int64(1)) if assert.Len(t, emails, 3) { @@ -30,7 +31,7 @@ func TestGetEmailAddresses(t *testing.T) { } func TestIsEmailUsed(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) isExist, _ := IsEmailUsed(db.DefaultContext, "") assert.True(t, isExist) @@ -41,7 +42,7 @@ func TestIsEmailUsed(t *testing.T) { } func TestAddEmailAddress(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, AddEmailAddress(&EmailAddress{ Email: "user1234567890@example.com", @@ -60,7 +61,7 @@ func TestAddEmailAddress(t *testing.T) { } func TestAddEmailAddresses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // insert multiple email address emails := make([]*EmailAddress, 2) @@ -83,7 +84,7 @@ func TestAddEmailAddresses(t *testing.T) { } func TestDeleteEmailAddress(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.NoError(t, DeleteEmailAddress(&EmailAddress{ UID: int64(1), @@ -108,7 +109,7 @@ func TestDeleteEmailAddress(t *testing.T) { } func TestDeleteEmailAddresses(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // delete multiple email address emails := make([]*EmailAddress, 2) diff --git a/models/user/main_test.go b/models/user/main_test.go index 2999c4c81db5..1dd9fb278131 100644 --- a/models/user/main_test.go +++ b/models/user/main_test.go @@ -8,11 +8,11 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", ".."), + unittest.MainTest(m, filepath.Join("..", ".."), "email_address.yml", "user_redirect.yml", ) diff --git a/models/user/redirect_test.go b/models/user/redirect_test.go index b33c42cf3d7c..82a0a0a2e21e 100644 --- a/models/user/redirect_test.go +++ b/models/user/redirect_test.go @@ -7,12 +7,13 @@ package user import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestLookupUserRedirect(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) userID, err := LookupUserRedirect("olduser1") assert.NoError(t, err) diff --git a/models/user_email_test.go b/models/user_email_test.go index 8c2bb48b9452..bde0778b6442 100644 --- a/models/user_email_test.go +++ b/models/user_email_test.go @@ -8,6 +8,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/util" @@ -15,7 +16,7 @@ import ( ) func TestMakeEmailPrimary(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) email := &user_model.EmailAddress{ Email: "user567890@example.com", @@ -49,7 +50,7 @@ func TestMakeEmailPrimary(t *testing.T) { } func TestActivate(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) email := &user_model.EmailAddress{ ID: int64(1), @@ -68,7 +69,7 @@ func TestActivate(t *testing.T) { } func TestListEmails(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Must find all users and their emails opts := &SearchEmailOptions{ diff --git a/models/user_follow_test.go b/models/user_follow_test.go index ae8faad6fa97..c7e56410f074 100644 --- a/models/user_follow_test.go +++ b/models/user_follow_test.go @@ -8,11 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestIsFollowing(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, IsFollowing(4, 2)) assert.False(t, IsFollowing(2, 4)) assert.False(t, IsFollowing(5, db.NonexistentID)) @@ -21,7 +22,7 @@ func TestIsFollowing(t *testing.T) { } func TestFollowUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(followerID, followedID int64) { assert.NoError(t, FollowUser(followerID, followedID)) @@ -36,7 +37,7 @@ func TestFollowUser(t *testing.T) { } func TestUnfollowUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(followerID, followedID int64) { assert.NoError(t, UnfollowUser(followerID, followedID)) diff --git a/models/user_heatmap_test.go b/models/user_heatmap_test.go index 8d2002b1a0f3..85e678e9331a 100644 --- a/models/user_heatmap_test.go +++ b/models/user_heatmap_test.go @@ -10,6 +10,7 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/timeutil" @@ -39,7 +40,7 @@ func TestGetUserHeatmapDataByUser(t *testing.T) { {10, 10, 3, `[{"timestamp":1603009800,"contributions":1},{"timestamp":1603010700,"contributions":2}]`}, } // Prepare - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Mock time timeutil.Set(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)) diff --git a/models/user_openid_test.go b/models/user_openid_test.go index 3c17b0742c87..d0d801ad187c 100644 --- a/models/user_openid_test.go +++ b/models/user_openid_test.go @@ -7,12 +7,13 @@ package models import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestGetUserOpenIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) oids, err := GetUserOpenIDs(int64(1)) if assert.NoError(t, err) && assert.Len(t, oids, 2) { @@ -30,7 +31,7 @@ func TestGetUserOpenIDs(t *testing.T) { } func TestGetUserByOpenID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) _, err := GetUserByOpenID("https://unknown") if assert.Error(t, err) { @@ -49,7 +50,7 @@ func TestGetUserByOpenID(t *testing.T) { } func TestToggleUserOpenIDVisibility(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) oids, err := GetUserOpenIDs(int64(2)) if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { return diff --git a/models/user_test.go b/models/user_test.go index 58044d1e99f9..9a91a9b2575f 100644 --- a/models/user_test.go +++ b/models/user_test.go @@ -12,6 +12,7 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/structs" @@ -21,7 +22,7 @@ import ( ) func TestOAuth2Application_LoadUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) app := db.AssertExistsAndLoadBean(t, &login.OAuth2Application{ID: 1}).(*login.OAuth2Application) user, err := GetUserByID(app.UID) assert.NoError(t, err) @@ -29,7 +30,7 @@ func TestOAuth2Application_LoadUser(t *testing.T) { } func TestUserIsPublicMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { uid int64 @@ -55,7 +56,7 @@ func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) { } func TestIsUserOrgOwner(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { uid int64 @@ -81,7 +82,7 @@ func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) { } func TestGetUserEmailsByNames(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // ignore none active user email assert.Equal(t, []string{"user8@example.com"}, GetUserEmailsByNames([]string{"user8", "user9"})) @@ -91,7 +92,7 @@ func TestGetUserEmailsByNames(t *testing.T) { } func TestCanCreateOrganization(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) admin := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) assert.True(t, admin.CanCreateOrganization()) @@ -109,7 +110,7 @@ func TestCanCreateOrganization(t *testing.T) { } func TestSearchUsers(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(opts *SearchUserOptions, expectedUserOrOrgIDs []int64) { users, _, err := SearchUsers(opts) assert.NoError(t, err) @@ -178,7 +179,7 @@ func TestSearchUsers(t *testing.T) { func TestDeleteUser(t *testing.T) { test := func(userID int64) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: userID}).(*User) ownedRepos := make([]*Repository, 0, 10) @@ -212,7 +213,7 @@ func TestDeleteUser(t *testing.T) { } func TestEmailNotificationPreferences(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) for _, test := range []struct { expected string @@ -280,7 +281,7 @@ func BenchmarkHashPassword(b *testing.B) { } func TestGetOrgRepositoryIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user2 := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user4 := db.AssertExistsAndLoadBean(t, &User{ID: 4}).(*User) user5 := db.AssertExistsAndLoadBean(t, &User{ID: 5}).(*User) @@ -393,7 +394,7 @@ func TestCreateUser_Issue5882(t *testing.T) { } func TestGetUserIDsByNames(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // ignore non existing IDs, err := GetUserIDsByNames([]string{"user1", "user2", "none_existing_user"}, true) @@ -407,7 +408,7 @@ func TestGetUserIDsByNames(t *testing.T) { } func TestGetMaileableUsersByIDs(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) results, err := GetMaileableUsersByIDs([]int64{1, 4}, false) assert.NoError(t, err) @@ -426,7 +427,7 @@ func TestGetMaileableUsersByIDs(t *testing.T) { } func TestAddLdapSSHPublicKeys(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) s := &login.Source{ID: 1} @@ -494,7 +495,7 @@ ssh-dss AAAAB3NzaC1kc3MAAACBAOChCC7lf6Uo9n7BmZ6M8St19PZf4Tn59NriyboW2x/DZuYAz3ib } func TestUpdateUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) user.KeepActivityPrivate = true @@ -515,7 +516,7 @@ func TestUpdateUser(t *testing.T) { func TestNewUserRedirect(t *testing.T) { // redirect to a completely new name - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "newusername")) @@ -532,7 +533,7 @@ func TestNewUserRedirect(t *testing.T) { func TestNewUserRedirect2(t *testing.T) { // redirect to previously used name - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 1}).(*User) assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "olduser1")) @@ -549,7 +550,7 @@ func TestNewUserRedirect2(t *testing.T) { func TestNewUserRedirect3(t *testing.T) { // redirect for a previously-unredirected user - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &User{ID: 2}).(*User) assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "newusername")) diff --git a/models/userlist_test.go b/models/userlist_test.go index 9e75f783f192..2b8518c92f2e 100644 --- a/models/userlist_test.go +++ b/models/userlist_test.go @@ -8,12 +8,13 @@ import ( "fmt" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestUserListIsPublicMember(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { orgid int64 expected map[int64]bool @@ -39,7 +40,7 @@ func testUserListIsPublicMember(t *testing.T, orgID int64, expected map[int64]bo } func TestUserListIsUserOrgOwner(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { orgid int64 expected map[int64]bool @@ -65,7 +66,7 @@ func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bo } func TestUserListIsTwoFaEnrolled(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { orgid int64 expected map[int64]bool diff --git a/models/webhook/main_test.go b/models/webhook/main_test.go index f94612a755b0..89c947b061fd 100644 --- a/models/webhook/main_test.go +++ b/models/webhook/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", ".."), "webhook.yml", "hook_task.yml") + unittest.MainTest(m, filepath.Join("..", ".."), "webhook.yml", "hook_task.yml") } diff --git a/models/webhook/webhook_test.go b/models/webhook/webhook_test.go index df2c37b355f8..6d7957ba6441 100644 --- a/models/webhook/webhook_test.go +++ b/models/webhook/webhook_test.go @@ -10,6 +10,7 @@ import ( "time" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/json" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" @@ -29,7 +30,7 @@ func TestIsValidHookContentType(t *testing.T) { } func TestWebhook_History(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) webhook := db.AssertExistsAndLoadBean(t, &Webhook{ID: 1}).(*Webhook) tasks, err := webhook.History(0) assert.NoError(t, err) @@ -44,7 +45,7 @@ func TestWebhook_History(t *testing.T) { } func TestWebhook_UpdateEvent(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) webhook := db.AssertExistsAndLoadBean(t, &Webhook{ID: 1}).(*Webhook) hookEvent := &HookEvent{ PushOnly: true, @@ -97,7 +98,7 @@ func TestCreateWebhook(t *testing.T) { } func TestGetWebhookByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hook, err := GetWebhookByRepoID(1, 1) assert.NoError(t, err) assert.Equal(t, int64(1), hook.ID) @@ -108,7 +109,7 @@ func TestGetWebhookByRepoID(t *testing.T) { } func TestGetWebhookByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hook, err := GetWebhookByOrgID(3, 3) assert.NoError(t, err) assert.Equal(t, int64(3), hook.ID) @@ -119,7 +120,7 @@ func TestGetWebhookByOrgID(t *testing.T) { } func TestGetActiveWebhooksByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hooks, err := ListWebhooksByOpts(&ListWebhookOptions{RepoID: 1, IsActive: util.OptionalBoolTrue}) assert.NoError(t, err) if assert.Len(t, hooks, 1) { @@ -129,7 +130,7 @@ func TestGetActiveWebhooksByRepoID(t *testing.T) { } func TestGetWebhooksByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hooks, err := ListWebhooksByOpts(&ListWebhookOptions{RepoID: 1}) assert.NoError(t, err) if assert.Len(t, hooks, 2) { @@ -139,7 +140,7 @@ func TestGetWebhooksByRepoID(t *testing.T) { } func TestGetActiveWebhooksByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hooks, err := ListWebhooksByOpts(&ListWebhookOptions{OrgID: 3, IsActive: util.OptionalBoolTrue}) assert.NoError(t, err) if assert.Len(t, hooks, 1) { @@ -149,7 +150,7 @@ func TestGetActiveWebhooksByOrgID(t *testing.T) { } func TestGetWebhooksByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hooks, err := ListWebhooksByOpts(&ListWebhookOptions{OrgID: 3}) assert.NoError(t, err) if assert.Len(t, hooks, 1) { @@ -159,7 +160,7 @@ func TestGetWebhooksByOrgID(t *testing.T) { } func TestUpdateWebhook(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hook := db.AssertExistsAndLoadBean(t, &Webhook{ID: 2}).(*Webhook) hook.IsActive = true hook.ContentType = ContentTypeForm @@ -169,7 +170,7 @@ func TestUpdateWebhook(t *testing.T) { } func TestDeleteWebhookByRepoID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) db.AssertExistsAndLoadBean(t, &Webhook{ID: 2, RepoID: 1}) assert.NoError(t, DeleteWebhookByRepoID(1, 2)) db.AssertNotExistsBean(t, &Webhook{ID: 2, RepoID: 1}) @@ -180,7 +181,7 @@ func TestDeleteWebhookByRepoID(t *testing.T) { } func TestDeleteWebhookByOrgID(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) db.AssertExistsAndLoadBean(t, &Webhook{ID: 3, OrgID: 3}) assert.NoError(t, DeleteWebhookByOrgID(3, 3)) db.AssertNotExistsBean(t, &Webhook{ID: 3, OrgID: 3}) @@ -191,7 +192,7 @@ func TestDeleteWebhookByOrgID(t *testing.T) { } func TestHookTasks(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTasks, err := HookTasks(1, 1) assert.NoError(t, err) if assert.Len(t, hookTasks, 1) { @@ -204,7 +205,7 @@ func TestHookTasks(t *testing.T) { } func TestCreateHookTask(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 3, HookID: 3, @@ -216,7 +217,7 @@ func TestCreateHookTask(t *testing.T) { } func TestUpdateHookTask(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hook := db.AssertExistsAndLoadBean(t, &HookTask{ID: 1}).(*HookTask) hook.PayloadContent = "new payload content" @@ -228,7 +229,7 @@ func TestUpdateHookTask(t *testing.T) { } func TestCleanupHookTaskTable_PerWebhook_DeletesDelivered(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 3, HookID: 3, @@ -245,7 +246,7 @@ func TestCleanupHookTaskTable_PerWebhook_DeletesDelivered(t *testing.T) { } func TestCleanupHookTaskTable_PerWebhook_LeavesUndelivered(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 2, HookID: 4, @@ -261,7 +262,7 @@ func TestCleanupHookTaskTable_PerWebhook_LeavesUndelivered(t *testing.T) { } func TestCleanupHookTaskTable_PerWebhook_LeavesMostRecentTask(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 2, HookID: 4, @@ -278,7 +279,7 @@ func TestCleanupHookTaskTable_PerWebhook_LeavesMostRecentTask(t *testing.T) { } func TestCleanupHookTaskTable_OlderThan_DeletesDelivered(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 3, HookID: 3, @@ -295,7 +296,7 @@ func TestCleanupHookTaskTable_OlderThan_DeletesDelivered(t *testing.T) { } func TestCleanupHookTaskTable_OlderThan_LeavesUndelivered(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 2, HookID: 4, @@ -311,7 +312,7 @@ func TestCleanupHookTaskTable_OlderThan_LeavesUndelivered(t *testing.T) { } func TestCleanupHookTaskTable_OlderThan_LeavesTaskEarlierThanAgeToDelete(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ RepoID: 2, HookID: 4, diff --git a/models/wiki_test.go b/models/wiki_test.go index f1435e8178a6..2114425872ee 100644 --- a/models/wiki_test.go +++ b/models/wiki_test.go @@ -9,13 +9,14 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestRepository_WikiCloneLink(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) cloneLink := repo.WikiCloneLink() @@ -24,20 +25,20 @@ func TestRepository_WikiCloneLink(t *testing.T) { } func TestWikiPath(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) expected := filepath.Join(setting.RepoRootPath, "user2/repo1.wiki.git") assert.Equal(t, expected, WikiPath("user2", "repo1")) } func TestRepository_WikiPath(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) expected := filepath.Join(setting.RepoRootPath, "user2/repo1.wiki.git") assert.Equal(t, expected, repo.WikiPath()) } func TestRepository_HasWiki(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) repo1 := db.AssertExistsAndLoadBean(t, &Repository{ID: 1}).(*Repository) assert.True(t, repo1.HasWiki()) repo2 := db.AssertExistsAndLoadBean(t, &Repository{ID: 2}).(*Repository) diff --git a/modules/appstate/appstate_test.go b/modules/appstate/appstate_test.go index d8ab0a45fd80..15fbc829bae4 100644 --- a/modules/appstate/appstate_test.go +++ b/modules/appstate/appstate_test.go @@ -8,13 +8,13 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", ".."), "") + unittest.MainTest(m, filepath.Join("..", ".."), "") } type testItem1 struct { @@ -35,7 +35,7 @@ func (*testItem2) Name() string { } func TestAppStateDB(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) as := &DBStore{} diff --git a/modules/convert/git_commit_test.go b/modules/convert/git_commit_test.go index 298a006cb19e..3cb55c6a6f23 100644 --- a/modules/convert/git_commit_test.go +++ b/modules/convert/git_commit_test.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/util" @@ -18,7 +19,7 @@ import ( ) func TestToCommitMeta(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) headRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) sha1, _ := git.NewIDFromString("0000000000000000000000000000000000000000") signature := &git.Signature{Name: "Test Signature", Email: "test@email.com", When: time.Unix(0, 0)} diff --git a/modules/convert/issue_test.go b/modules/convert/issue_test.go index 7c6b05e816a5..e44733c46d84 100644 --- a/modules/convert/issue_test.go +++ b/modules/convert/issue_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/timeutil" @@ -19,7 +20,7 @@ import ( ) func TestLabel_ToLabel(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) label := db.AssertExistsAndLoadBean(t, &models.Label{ID: 1}).(*models.Label) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: label.RepoID}).(*models.Repository) assert.Equal(t, &api.Label{ diff --git a/modules/convert/main_test.go b/modules/convert/main_test.go index acb9802f97a0..307fd06197ce 100644 --- a/modules/convert/main_test.go +++ b/modules/convert/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } diff --git a/modules/convert/pull_test.go b/modules/convert/pull_test.go index a2b1e12a3718..f5310eb82581 100644 --- a/modules/convert/pull_test.go +++ b/modules/convert/pull_test.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -16,7 +17,7 @@ import ( func TestPullRequest_APIFormat(t *testing.T) { //with HeadRepo - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) headRepo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) pr := db.AssertExistsAndLoadBean(t, &models.PullRequest{ID: 1}).(*models.PullRequest) assert.NoError(t, pr.LoadAttributes()) diff --git a/modules/convert/user_test.go b/modules/convert/user_test.go index acf918dd99cf..fe26456f5d9f 100644 --- a/modules/convert/user_test.go +++ b/modules/convert/user_test.go @@ -9,13 +9,14 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" ) func TestUser_ToUser(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user1 := db.AssertExistsAndLoadBean(t, &models.User{ID: 1, IsAdmin: true}).(*models.User) diff --git a/modules/indexer/code/bleve_test.go b/modules/indexer/code/bleve_test.go index 3d97e312f9aa..37ed2eb9f021 100644 --- a/modules/indexer/code/bleve_test.go +++ b/modules/indexer/code/bleve_test.go @@ -8,14 +8,14 @@ import ( "os" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" ) func TestBleveIndexAndSearch(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) dir, err := os.MkdirTemp("", "bleve.index") assert.NoError(t, err) diff --git a/modules/indexer/code/elastic_search_test.go b/modules/indexer/code/elastic_search_test.go index c9d2c297bba4..fc58633f16e8 100644 --- a/modules/indexer/code/elastic_search_test.go +++ b/modules/indexer/code/elastic_search_test.go @@ -8,12 +8,13 @@ import ( "os" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestESIndexAndSearch(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) u := os.Getenv("TEST_INDEXER_CODE_ES_URL") if u == "" { diff --git a/modules/indexer/code/indexer_test.go b/modules/indexer/code/indexer_test.go index 34930a84caff..b8fedcb3239e 100644 --- a/modules/indexer/code/indexer_test.go +++ b/modules/indexer/code/indexer_test.go @@ -8,12 +8,13 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + "github.com/stretchr/testify/assert" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } func testIndexer(name string, t *testing.T, indexer Indexer) { diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index 561f357f4da7..edfaddb648fe 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -11,7 +11,7 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/util" @@ -21,11 +21,11 @@ import ( ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } func TestBleveSearchIssues(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) setting.Cfg = ini.Empty() tmpIndexerDir, err := os.MkdirTemp("", "issues-indexer") @@ -74,7 +74,7 @@ func TestBleveSearchIssues(t *testing.T) { } func TestDBSearchIssues(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) setting.Indexer.IssueType = "db" InitIssueIndexer(true) diff --git a/modules/indexer/stats/indexer_test.go b/modules/indexer/stats/indexer_test.go index a4645b2083d9..c451e8023838 100644 --- a/modules/indexer/stats/indexer_test.go +++ b/modules/indexer/stats/indexer_test.go @@ -10,7 +10,7 @@ import ( "time" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "gopkg.in/ini.v1" @@ -19,11 +19,11 @@ import ( ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } func TestRepoStatsIndex(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) setting.Cfg = ini.Empty() setting.NewQueueService() diff --git a/modules/migrations/gitea_uploader_test.go b/modules/migrations/gitea_uploader_test.go index b8b947961f4b..b5763f30d957 100644 --- a/modules/migrations/gitea_uploader_test.go +++ b/modules/migrations/gitea_uploader_test.go @@ -12,6 +12,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/graceful" "code.gitea.io/gitea/modules/migrations/base" "code.gitea.io/gitea/modules/structs" @@ -24,7 +25,7 @@ func TestGiteaUploadRepo(t *testing.T) { // FIXME: Since no accesskey or user/password will trigger rate limit of github, just skip t.Skip() - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) diff --git a/modules/migrations/main_test.go b/modules/migrations/main_test.go index 5b29230659aa..e9108c3c9303 100644 --- a/modules/migrations/main_test.go +++ b/modules/migrations/main_test.go @@ -10,14 +10,14 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/migrations/base" "github.com/stretchr/testify/assert" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } func timePtr(t time.Time) *time.Time { diff --git a/modules/migrations/migrate_test.go b/modules/migrations/migrate_test.go index c050a9abc086..aecc263cc66b 100644 --- a/modules/migrations/migrate_test.go +++ b/modules/migrations/migrate_test.go @@ -10,13 +10,14 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" ) func TestMigrateWhiteBlocklist(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) adminUser := db.AssertExistsAndLoadBean(t, &models.User{Name: "user1"}).(*models.User) nonAdminUser := db.AssertExistsAndLoadBean(t, &models.User{Name: "user2"}).(*models.User) diff --git a/modules/notification/action/action_test.go b/modules/notification/action/action_test.go index 705a4fb2f49a..e57069ed9a52 100644 --- a/modules/notification/action/action_test.go +++ b/modules/notification/action/action_test.go @@ -11,15 +11,16 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } func TestRenameRepoAction(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) repo := db.AssertExistsAndLoadBean(t, &models.Repository{OwnerID: user.ID}).(*models.Repository) diff --git a/modules/repofiles/action_test.go b/modules/repofiles/action_test.go index c29cfd686d42..59cb4df16096 100644 --- a/modules/repofiles/action_test.go +++ b/modules/repofiles/action_test.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" @@ -16,7 +17,7 @@ import ( ) func TestUpdateIssuesCommit(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pushCommits := []*repository.PushCommit{ { Sha1: "abcdef1", @@ -118,7 +119,7 @@ func TestUpdateIssuesCommit(t *testing.T) { } func TestUpdateIssuesCommit_Colon(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pushCommits := []*repository.PushCommit{ { Sha1: "abcdef2", @@ -143,7 +144,7 @@ func TestUpdateIssuesCommit_Colon(t *testing.T) { } func TestUpdateIssuesCommit_Issue5957(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Test that push to a non-default branch closes an issue. @@ -177,7 +178,7 @@ func TestUpdateIssuesCommit_Issue5957(t *testing.T) { } func TestUpdateIssuesCommit_AnotherRepo(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Test that a push to default branch closes issue in another repo @@ -212,7 +213,7 @@ func TestUpdateIssuesCommit_AnotherRepo(t *testing.T) { } func TestUpdateIssuesCommit_AnotherRepo_FullAddress(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) // Test that a push to default branch closes issue in another repo @@ -247,7 +248,7 @@ func TestUpdateIssuesCommit_AnotherRepo_FullAddress(t *testing.T) { } func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 10}).(*models.User) // Test that a push with close reference *can not* close issue diff --git a/modules/repofiles/blob_test.go b/modules/repofiles/blob_test.go index 5238dd6e74f4..c219892aec8e 100644 --- a/modules/repofiles/blob_test.go +++ b/modules/repofiles/blob_test.go @@ -7,7 +7,8 @@ package repofiles import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/test" @@ -15,7 +16,7 @@ import ( ) func TestGetBlobBySHA(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") test.LoadRepo(t, ctx, 1) test.LoadRepoCommit(t, ctx) diff --git a/modules/repofiles/content_test.go b/modules/repofiles/content_test.go index f68460d7ec3f..e3230698bcec 100644 --- a/modules/repofiles/content_test.go +++ b/modules/repofiles/content_test.go @@ -8,7 +8,8 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/test" @@ -16,7 +17,7 @@ import ( ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } func getExpectedReadmeContentsResponse() *api.ContentsResponse { @@ -49,7 +50,7 @@ func getExpectedReadmeContentsResponse() *api.ContentsResponse { } func TestGetContents(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -77,7 +78,7 @@ func TestGetContents(t *testing.T) { } func TestGetContentsOrListForDir(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -112,7 +113,7 @@ func TestGetContentsOrListForDir(t *testing.T) { } func TestGetContentsOrListForFile(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -140,7 +141,7 @@ func TestGetContentsOrListForFile(t *testing.T) { } func TestGetContentsErrors(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -171,7 +172,7 @@ func TestGetContentsErrors(t *testing.T) { } func TestGetContentsOrListErrors(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -202,7 +203,7 @@ func TestGetContentsOrListErrors(t *testing.T) { } func TestGetContentsOrListOfEmptyRepos(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo15") ctx.SetParams(":id", "15") test.LoadRepo(t, ctx, 15) diff --git a/modules/repofiles/diff_test.go b/modules/repofiles/diff_test.go index aeb4f76a4576..463ce4ec6744 100644 --- a/modules/repofiles/diff_test.go +++ b/modules/repofiles/diff_test.go @@ -8,7 +8,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/services/gitdiff" @@ -16,7 +16,7 @@ import ( ) func TestGetDiffPreview(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -129,7 +129,7 @@ func TestGetDiffPreview(t *testing.T) { } func TestGetDiffPreviewErrors(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) diff --git a/modules/repofiles/file_test.go b/modules/repofiles/file_test.go index 2974056549e3..54205a89c7e6 100644 --- a/modules/repofiles/file_test.go +++ b/modules/repofiles/file_test.go @@ -7,7 +7,7 @@ package repofiles import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" @@ -81,7 +81,7 @@ func getExpectedFileResponse() *api.FileResponse { } func TestGetFileResponseFromCommit(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) diff --git a/modules/repofiles/tree_test.go b/modules/repofiles/tree_test.go index 9e2efa4216fa..512313c43b36 100644 --- a/modules/repofiles/tree_test.go +++ b/modules/repofiles/tree_test.go @@ -7,7 +7,8 @@ package repofiles import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" + api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/test" @@ -15,7 +16,7 @@ import ( ) func TestGetTreeBySHA(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") test.LoadRepo(t, ctx, 1) test.LoadRepoCommit(t, ctx) diff --git a/modules/repository/commits_test.go b/modules/repository/commits_test.go index c62ad584496d..c47d9cf48ca9 100644 --- a/modules/repository/commits_test.go +++ b/modules/repository/commits_test.go @@ -12,12 +12,13 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" "github.com/stretchr/testify/assert" ) func TestPushCommits_ToAPIPayloadCommits(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pushCommits := NewPushCommits() pushCommits.Commits = []*PushCommit{ @@ -100,7 +101,7 @@ func TestPushCommits_ToAPIPayloadCommits(t *testing.T) { } func TestPushCommits_AvatarLink(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) pushCommits := NewPushCommits() pushCommits.Commits = []*PushCommit{ diff --git a/modules/repository/create_test.go b/modules/repository/create_test.go index 040c061d9209..d8330171604d 100644 --- a/modules/repository/create_test.go +++ b/modules/repository/create_test.go @@ -10,13 +10,14 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" ) func TestIncludesAllRepositoriesTeams(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) testTeamRepositories := func(teamID int64, repoIds []int64) { team := db.AssertExistsAndLoadBean(t, &models.Team{ID: teamID}).(*models.Team) diff --git a/modules/repository/fork_test.go b/modules/repository/fork_test.go index 7a05f9dd97e3..bfb813adbcf8 100644 --- a/modules/repository/fork_test.go +++ b/modules/repository/fork_test.go @@ -9,11 +9,12 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestForkRepository(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // user 13 has already forked repo10 user := db.AssertExistsAndLoadBean(t, &models.User{ID: 13}).(*models.User) diff --git a/modules/repository/main_test.go b/modules/repository/main_test.go index 91d0d36ca026..262d3394818b 100644 --- a/modules/repository/main_test.go +++ b/modules/repository/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } diff --git a/modules/unittestbridge/unittestbridge.go b/modules/unittestbridge/unittestbridge.go new file mode 100644 index 000000000000..273cf5e70f92 --- /dev/null +++ b/modules/unittestbridge/unittestbridge.go @@ -0,0 +1,46 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package unittestbridge + +// Usage: generally, non-unit-test code shouldn't depend on unit test code. +// However, we have some code like models.CheckConsistencyFor, which need to do some unit test works. +// Now we can not decouple models.CheckConsistencyFor from unit test code easily (cycle-import reasons). +// So we introduce this `unit test bridge`: +// * When a release binary is built, no testing/assert framework would be compiled into the binary, and CheckConsistencyFor won't run unit test related code +// * When a unit test binary is built, the unit test code will init this bridge, then CheckConsistencyFor can run unit test related code +// +// Tester/Assert are intermediate interfaces, they should NOT be used in new code. +// One day, if CheckConsistencyFor is clean enough, we can remove these intermediate interfaces. + +// Tester is the same as TestingT in "stretchr/testify/assert" +// Tester can be used in non-unit-test code (ex: models.CheckConsistencyFor), it is used to isolate dependencies +type Tester interface { + Errorf(format string, args ...interface{}) +} + +// Asserter can be used in non-unit-test code (ex: models.CheckConsistencyFor), it is used to isolate dependencies +type Asserter interface { + Tester + NoError(err error, msgAndArgs ...interface{}) bool + EqualValues(expected, actual interface{}, msgAndArgs ...interface{}) bool + Equal(expected, actual interface{}, msgAndArgs ...interface{}) bool + True(value bool, msgAndArgs ...interface{}) bool + False(value bool, msgAndArgs ...interface{}) bool +} + +var newAsserterFunc func(t Tester) Asserter + +// NewAsserter returns a new asserter, only works in unit test +func NewAsserter(t Tester) Asserter { + if newAsserterFunc == nil { + panic("the newAsserterFunc is not set. you can only use assert in unit test.") + } + return newAsserterFunc(t) +} + +// SetNewAsserterFunc in unit test, the asserter must be set first +func SetNewAsserterFunc(f func(t Tester) Asserter) { + newAsserterFunc = f +} diff --git a/routers/api/v1/repo/hook_test.go b/routers/api/v1/repo/hook_test.go index 60fa6cead31c..ff0aaf29382e 100644 --- a/routers/api/v1/repo/hook_test.go +++ b/routers/api/v1/repo/hook_test.go @@ -9,6 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/webhook" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/test" @@ -17,7 +18,7 @@ import ( ) func TestTestHook(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/wiki/_pages") ctx.SetParams(":id", "1") diff --git a/routers/api/v1/repo/main_test.go b/routers/api/v1/repo/main_test.go index 7a66370e05b2..f9ed886999c9 100644 --- a/routers/api/v1/repo/main_test.go +++ b/routers/api/v1/repo/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..", "..")) } diff --git a/routers/api/v1/repo/repo_test.go b/routers/api/v1/repo/repo_test.go index e4fd4f94240e..b992b93fd4a9 100644 --- a/routers/api/v1/repo/repo_test.go +++ b/routers/api/v1/repo/repo_test.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/context" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/test" @@ -19,7 +20,7 @@ import ( ) func TestRepoEdit(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") test.LoadRepo(t, ctx, 1) @@ -66,7 +67,7 @@ func TestRepoEdit(t *testing.T) { } func TestRepoEditNameChange(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") test.LoadRepo(t, ctx, 1) diff --git a/routers/web/admin/main_test.go b/routers/web/admin/main_test.go index cfdefdb1b4af..e41d8fea75c3 100644 --- a/routers/web/admin/main_test.go +++ b/routers/web/admin/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } diff --git a/routers/web/admin/users_test.go b/routers/web/admin/users_test.go index 022d8f662c8f..62b35ea28660 100644 --- a/routers/web/admin/users_test.go +++ b/routers/web/admin/users_test.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/test" @@ -20,7 +21,7 @@ import ( func TestNewUserPost_MustChangePassword(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "admin/users/new") u := db.AssertExistsAndLoadBean(t, &models.User{ @@ -57,7 +58,7 @@ func TestNewUserPost_MustChangePassword(t *testing.T) { } func TestNewUserPost_MustChangePasswordFalse(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "admin/users/new") u := db.AssertExistsAndLoadBean(t, &models.User{ @@ -94,7 +95,7 @@ func TestNewUserPost_MustChangePasswordFalse(t *testing.T) { } func TestNewUserPost_InvalidEmail(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "admin/users/new") u := db.AssertExistsAndLoadBean(t, &models.User{ @@ -124,7 +125,7 @@ func TestNewUserPost_InvalidEmail(t *testing.T) { } func TestNewUserPost_VisibilityDefaultPublic(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "admin/users/new") u := db.AssertExistsAndLoadBean(t, &models.User{ @@ -162,7 +163,7 @@ func TestNewUserPost_VisibilityDefaultPublic(t *testing.T) { } func TestNewUserPost_VisibilityPrivate(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "admin/users/new") u := db.AssertExistsAndLoadBean(t, &models.User{ diff --git a/routers/web/repo/editor_test.go b/routers/web/repo/editor_test.go index 8ab1fe1ee892..77f94ff5501e 100644 --- a/routers/web/repo/editor_test.go +++ b/routers/web/repo/editor_test.go @@ -7,7 +7,7 @@ package repo import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/test" @@ -15,7 +15,7 @@ import ( ) func TestCleanUploadName(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) var kases = map[string]string{ ".git/refs/master": "", @@ -41,7 +41,7 @@ func TestCleanUploadName(t *testing.T) { } func TestGetUniquePatchBranchName(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) @@ -56,7 +56,7 @@ func TestGetUniquePatchBranchName(t *testing.T) { } func TestGetClosestParentWithFiles(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1") ctx.SetParams(":id", "1") test.LoadRepo(t, ctx, 1) diff --git a/routers/web/repo/issue_label_test.go b/routers/web/repo/issue_label_test.go index 8c3caabe17cf..98fa9eb96867 100644 --- a/routers/web/repo/issue_label_test.go +++ b/routers/web/repo/issue_label_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/services/forms" @@ -30,7 +31,7 @@ func int64SliceToCommaSeparated(a []int64) string { } func TestInitializeLabels(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/labels/initialize") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 2) @@ -46,7 +47,7 @@ func TestInitializeLabels(t *testing.T) { } func TestRetrieveLabels(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) for _, testCase := range []struct { RepoID int64 Sort string @@ -73,7 +74,7 @@ func TestRetrieveLabels(t *testing.T) { } func TestNewLabel(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/labels/edit") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 1) @@ -91,7 +92,7 @@ func TestNewLabel(t *testing.T) { } func TestUpdateLabel(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/labels/edit") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 1) @@ -111,7 +112,7 @@ func TestUpdateLabel(t *testing.T) { } func TestDeleteLabel(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/labels/delete") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 1) @@ -124,7 +125,7 @@ func TestDeleteLabel(t *testing.T) { } func TestUpdateIssueLabel_Clear(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 1) @@ -149,7 +150,7 @@ func TestUpdateIssueLabel_Toggle(t *testing.T) { {"toggle", []int64{1, 3}, 1, false}, {"toggle", []int64{1, 2}, 2, true}, } { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 1) diff --git a/routers/web/repo/main_test.go b/routers/web/repo/main_test.go index 832256724987..81e3a8e28135 100644 --- a/routers/web/repo/main_test.go +++ b/routers/web/repo/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } diff --git a/routers/web/repo/projects_test.go b/routers/web/repo/projects_test.go index d3b78cc77587..62fb0457400b 100644 --- a/routers/web/repo/projects_test.go +++ b/routers/web/repo/projects_test.go @@ -7,14 +7,14 @@ package repo import ( "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" ) func TestCheckProjectBoardChangePermissions(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/projects/1/2") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 1) diff --git a/routers/web/repo/release_test.go b/routers/web/repo/release_test.go index 7ac49c012fef..ff54232da755 100644 --- a/routers/web/repo/release_test.go +++ b/routers/web/repo/release_test.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/web" "code.gitea.io/gitea/services/forms" @@ -44,7 +45,7 @@ func TestNewReleasePost(t *testing.T) { }, }, } { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/releases/new") test.LoadUser(t, ctx, 2) diff --git a/routers/web/repo/settings_test.go b/routers/web/repo/settings_test.go index a3ed271cce6c..78426f5b79a1 100644 --- a/routers/web/repo/settings_test.go +++ b/routers/web/repo/settings_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/context" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/test" @@ -43,7 +44,7 @@ func TestAddReadOnlyDeployKey(t *testing.T) { } else { return } - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/settings/keys") @@ -72,7 +73,7 @@ func TestAddReadWriteOnlyDeployKey(t *testing.T) { return } - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/settings/keys") @@ -97,7 +98,7 @@ func TestAddReadWriteOnlyDeployKey(t *testing.T) { func TestCollaborationPost(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2) test.LoadUser(t, ctx, 4) @@ -133,7 +134,7 @@ func TestCollaborationPost(t *testing.T) { func TestCollaborationPost_InactiveUser(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2) test.LoadUser(t, ctx, 9) @@ -157,7 +158,7 @@ func TestCollaborationPost_InactiveUser(t *testing.T) { func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2) test.LoadUser(t, ctx, 4) @@ -199,7 +200,7 @@ func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) { func TestCollaborationPost_NonExistentUser(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/issues/labels") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 1) @@ -221,7 +222,7 @@ func TestCollaborationPost_NonExistentUser(t *testing.T) { } func TestAddTeamPost(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "org26/repo43") ctx.Req.Form.Set("team", "team11") @@ -261,7 +262,7 @@ func TestAddTeamPost(t *testing.T) { } func TestAddTeamPost_NotAllowed(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "org26/repo43") ctx.Req.Form.Set("team", "team11") @@ -302,7 +303,7 @@ func TestAddTeamPost_NotAllowed(t *testing.T) { } func TestAddTeamPost_AddTeamTwice(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "org26/repo43") ctx.Req.Form.Set("team", "team11") @@ -343,7 +344,7 @@ func TestAddTeamPost_AddTeamTwice(t *testing.T) { } func TestAddTeamPost_NonExistentTeam(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "org26/repo43") ctx.Req.Form.Set("team", "team-non-existent") @@ -376,7 +377,7 @@ func TestAddTeamPost_NonExistentTeam(t *testing.T) { } func TestDeleteTeam(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "org3/team1/repo3") ctx.Req.Form.Set("id", "2") diff --git a/routers/web/repo/wiki_test.go b/routers/web/repo/wiki_test.go index 14cb893d46d7..cf49f19afe44 100644 --- a/routers/web/repo/wiki_test.go +++ b/routers/web/repo/wiki_test.go @@ -10,7 +10,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/web" @@ -74,7 +74,7 @@ func assertPagesMetas(t *testing.T, expectedNames []string, metas interface{}) { } func TestWiki(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/wiki/_pages") ctx.SetParams(":page", "Home") @@ -86,7 +86,7 @@ func TestWiki(t *testing.T) { } func TestWikiPages(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/wiki/_pages") test.LoadRepo(t, ctx, 1) @@ -96,7 +96,7 @@ func TestWikiPages(t *testing.T) { } func TestNewWiki(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/wiki/_new") test.LoadUser(t, ctx, 2) @@ -111,7 +111,7 @@ func TestNewWikiPost(t *testing.T) { "New page", "&&&&", } { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/wiki/_new") test.LoadUser(t, ctx, 2) @@ -129,7 +129,7 @@ func TestNewWikiPost(t *testing.T) { } func TestNewWikiPost_ReservedName(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/wiki/_new") test.LoadUser(t, ctx, 2) @@ -146,7 +146,7 @@ func TestNewWikiPost_ReservedName(t *testing.T) { } func TestEditWiki(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/wiki/_edit/Home") ctx.SetParams(":page", "Home") @@ -163,7 +163,7 @@ func TestEditWikiPost(t *testing.T) { "Home", "New/", } { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/wiki/_new/Home") ctx.SetParams(":page", "Home") test.LoadUser(t, ctx, 2) @@ -184,7 +184,7 @@ func TestEditWikiPost(t *testing.T) { } func TestDeleteWikiPagePost(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/wiki/Home/delete") test.LoadUser(t, ctx, 2) @@ -203,7 +203,7 @@ func TestWikiRaw(t *testing.T) { "Page With Spaced Name.md": "text/plain; charset=utf-8", "Page-With-Spaced-Name.md": "text/plain; charset=utf-8", } { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user2/repo1/wiki/raw/"+filepath) ctx.SetParams("*", filepath) diff --git a/routers/web/user/home_test.go b/routers/web/user/home_test.go index daf473b270c0..cd599abd047e 100644 --- a/routers/web/user/home_test.go +++ b/routers/web/user/home_test.go @@ -9,7 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/test" @@ -19,7 +19,7 @@ import ( func TestArchivedIssues(t *testing.T) { // Arrange setting.UI.IssuePagingNum = 1 - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) ctx := test.MockContext(t, "issues") test.LoadUser(t, ctx, 30) @@ -52,7 +52,7 @@ func TestArchivedIssues(t *testing.T) { func TestIssues(t *testing.T) { setting.UI.IssuePagingNum = 1 - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) ctx := test.MockContext(t, "issues") test.LoadUser(t, ctx, 2) @@ -68,7 +68,7 @@ func TestIssues(t *testing.T) { func TestPulls(t *testing.T) { setting.UI.IssuePagingNum = 20 - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) ctx := test.MockContext(t, "pulls") test.LoadUser(t, ctx, 2) @@ -81,7 +81,7 @@ func TestPulls(t *testing.T) { func TestMilestones(t *testing.T) { setting.UI.IssuePagingNum = 1 - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) ctx := test.MockContext(t, "milestones") test.LoadUser(t, ctx, 2) @@ -100,7 +100,7 @@ func TestMilestones(t *testing.T) { func TestMilestonesForSpecificRepo(t *testing.T) { setting.UI.IssuePagingNum = 1 - assert.NoError(t, db.LoadFixtures()) + assert.NoError(t, unittest.LoadFixtures()) ctx := test.MockContext(t, "milestones") test.LoadUser(t, ctx, 2) diff --git a/routers/web/user/main_test.go b/routers/web/user/main_test.go index 272e4b8b2111..77b48d89fb86 100644 --- a/routers/web/user/main_test.go +++ b/routers/web/user/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..")) } diff --git a/routers/web/user/oauth_test.go b/routers/web/user/oauth_test.go index 27d339b778ea..e0c1bf4e7742 100644 --- a/routers/web/user/oauth_test.go +++ b/routers/web/user/oauth_test.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/login" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/services/auth/source/oauth2" "github.com/golang-jwt/jwt" @@ -41,7 +42,7 @@ func createAndParseToken(t *testing.T, grant *login.OAuth2Grant) *oauth2.OIDCTok } func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) grants, err := login.GetOAuth2GrantsByUserID(3) assert.NoError(t, err) diff --git a/routers/web/user/setting/account_test.go b/routers/web/user/setting/account_test.go index bfb7ac48726f..cd5c77795ea9 100644 --- a/routers/web/user/setting/account_test.go +++ b/routers/web/user/setting/account_test.go @@ -8,7 +8,7 @@ import ( "net/http" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/web" @@ -81,7 +81,7 @@ func TestChangePassword(t *testing.T) { PasswordComplexity: pcLU, }, } { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) ctx := test.MockContext(t, "user/settings/security") test.LoadUser(t, ctx, 2) test.LoadRepo(t, ctx, 1) diff --git a/routers/web/user/setting/main_test.go b/routers/web/user/setting/main_test.go index a0fbe55ee17e..b6ed7f5b1803 100644 --- a/routers/web/user/setting/main_test.go +++ b/routers/web/user/setting/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..", "..", "..")) + unittest.MainTest(m, filepath.Join("..", "..", "..", "..")) } diff --git a/services/archiver/archiver_test.go b/services/archiver/archiver_test.go index 94b0423d9bae..67484fdc786a 100644 --- a/services/archiver/archiver_test.go +++ b/services/archiver/archiver_test.go @@ -9,14 +9,14 @@ import ( "testing" "time" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } func waitForCount(t *testing.T, num int) { @@ -24,7 +24,7 @@ func waitForCount(t *testing.T, num int) { } func TestArchive_Basic(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) ctx := test.MockContext(t, "user27/repo49") firstCommit, secondCommit := "51f84af23134", "aacbdfe9e1c4" diff --git a/services/attachment/attachment_test.go b/services/attachment/attachment_test.go index 3e9e55a8f2fe..f44c4f9b5e81 100644 --- a/services/attachment/attachment_test.go +++ b/services/attachment/attachment_test.go @@ -11,16 +11,17 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } func TestUploadAttachment(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) diff --git a/services/gitdiff/gitdiff_test.go b/services/gitdiff/gitdiff_test.go index 6decb59b64b5..359e2e8c666b 100644 --- a/services/gitdiff/gitdiff_test.go +++ b/services/gitdiff/gitdiff_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/highlight" "code.gitea.io/gitea/modules/json" @@ -493,7 +494,7 @@ func setupDefaultDiff() *Diff { } } func TestDiff_LoadComments(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: 2}).(*models.Issue) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 1}).(*models.User) diff --git a/services/gitdiff/main_test.go b/services/gitdiff/main_test.go index 1b83cbd684a0..8c76e7e1530f 100644 --- a/services/gitdiff/main_test.go +++ b/services/gitdiff/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } diff --git a/services/issue/assignee_test.go b/services/issue/assignee_test.go index 5684ed6d8997..b0bbe42273d1 100644 --- a/services/issue/assignee_test.go +++ b/services/issue/assignee_test.go @@ -8,12 +8,12 @@ import ( "testing" "code.gitea.io/gitea/models" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) func TestDeleteNotPassedAssignee(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) // Fake issue with assignees issue, err := models.GetIssueWithAttrsByID(1) diff --git a/services/issue/label_test.go b/services/issue/label_test.go index 8a3a77ecb0a6..758ef98b27ab 100644 --- a/services/issue/label_test.go +++ b/services/issue/label_test.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" ) @@ -24,7 +25,7 @@ func TestIssue_AddLabels(t *testing.T) { {2, []int64{}, 1}, // pull-request, empty } for _, test := range tests { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: test.issueID}).(*models.Issue) labels := make([]*models.Label, len(test.labelIDs)) for i, labelID := range test.labelIDs { @@ -50,7 +51,7 @@ func TestIssue_AddLabel(t *testing.T) { {2, 1, 2}, // pull-request, already-added label } for _, test := range tests { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) issue := db.AssertExistsAndLoadBean(t, &models.Issue{ID: test.issueID}).(*models.Issue) label := db.AssertExistsAndLoadBean(t, &models.Label{ID: test.labelID}).(*models.Label) doer := db.AssertExistsAndLoadBean(t, &models.User{ID: test.doerID}).(*models.User) diff --git a/services/issue/main_test.go b/services/issue/main_test.go index 1349837949d0..cbcfd08a4979 100644 --- a/services/issue/main_test.go +++ b/services/issue/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } diff --git a/services/mailer/mail_test.go b/services/mailer/mail_test.go index cd730a13a445..aaa18681b8b1 100644 --- a/services/mailer/mail_test.go +++ b/services/mailer/mail_test.go @@ -12,6 +12,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" @@ -41,7 +42,7 @@ const bodyTpl = ` ` func prepareMailerTest(t *testing.T) (doer *models.User, repo *models.Repository, issue *models.Issue, comment *models.Comment) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) var mailService = setting.Mailer{ From: "test@gitea.com", } diff --git a/services/mailer/main_test.go b/services/mailer/main_test.go index 2fbe9c54a93c..ae3b2c12b4ca 100644 --- a/services/mailer/main_test.go +++ b/services/mailer/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } diff --git a/services/pull/check_test.go b/services/pull/check_test.go index 8beea3d56d90..bc3df0a4bb89 100644 --- a/services/pull/check_test.go +++ b/services/pull/check_test.go @@ -12,13 +12,14 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/queue" "github.com/stretchr/testify/assert" ) func TestPullRequest_AddToTaskQueue(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) idChan := make(chan int64, 10) diff --git a/services/pull/main_test.go b/services/pull/main_test.go index c8d3394e8e6a..6059a291addd 100644 --- a/services/pull/main_test.go +++ b/services/pull/main_test.go @@ -9,9 +9,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } diff --git a/services/release/release_test.go b/services/release/release_test.go index e53e4c935b7c..b855ec6647a2 100644 --- a/services/release/release_test.go +++ b/services/release/release_test.go @@ -12,6 +12,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/services/attachment" @@ -19,11 +20,11 @@ import ( ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } func TestRelease_Create(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) @@ -127,7 +128,7 @@ func TestRelease_Create(t *testing.T) { } func TestRelease_Update(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) @@ -269,7 +270,7 @@ func TestRelease_Update(t *testing.T) { } func TestRelease_createTag(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) @@ -352,7 +353,7 @@ func TestRelease_createTag(t *testing.T) { } func TestCreateNewTag(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) user := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) diff --git a/services/repository/main_test.go b/services/repository/main_test.go index 91d0d36ca026..262d3394818b 100644 --- a/services/repository/main_test.go +++ b/services/repository/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } diff --git a/services/repository/transfer_test.go b/services/repository/transfer_test.go index 40ccfdfb52fa..9ce60f30eeb8 100644 --- a/services/repository/transfer_test.go +++ b/services/repository/transfer_test.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/notification" "code.gitea.io/gitea/modules/notification/action" "code.gitea.io/gitea/modules/util" @@ -28,7 +29,7 @@ func registerNotifier() { func TestTransferOwnership(t *testing.T) { registerNotifier() - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) doer := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 3}).(*models.Repository) @@ -55,7 +56,7 @@ func TestTransferOwnership(t *testing.T) { } func TestStartRepositoryTransferSetPermission(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) doer := db.AssertExistsAndLoadBean(t, &models.User{ID: 3}).(*models.User) recipient := db.AssertExistsAndLoadBean(t, &models.User{ID: 5}).(*models.User) diff --git a/services/webhook/main_test.go b/services/webhook/main_test.go index 7aef4b3a51ef..fc58f72565f9 100644 --- a/services/webhook/main_test.go +++ b/services/webhook/main_test.go @@ -8,9 +8,9 @@ import ( "path/filepath" "testing" - "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } diff --git a/services/webhook/webhook_test.go b/services/webhook/webhook_test.go index 75f19e50ce98..276d1e78cd61 100644 --- a/services/webhook/webhook_test.go +++ b/services/webhook/webhook_test.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" webhook_model "code.gitea.io/gitea/models/webhook" api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" @@ -27,7 +28,7 @@ func TestWebhook_GetSlackHook(t *testing.T) { } func TestPrepareWebhooks(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) hookTasks := []*webhook_model.HookTask{ @@ -43,7 +44,7 @@ func TestPrepareWebhooks(t *testing.T) { } func TestPrepareWebhooksBranchFilterMatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) hookTasks := []*webhook_model.HookTask{ @@ -60,7 +61,7 @@ func TestPrepareWebhooksBranchFilterMatch(t *testing.T) { } func TestPrepareWebhooksBranchFilterNoMatch(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 2}).(*models.Repository) hookTasks := []*webhook_model.HookTask{ diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go index d6a65cc23a82..7ecd3bb04ea9 100644 --- a/services/wiki/wiki_test.go +++ b/services/wiki/wiki_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/models/db" + "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/util" @@ -18,7 +19,7 @@ import ( ) func TestMain(m *testing.M) { - db.MainTest(m, filepath.Join("..", "..")) + unittest.MainTest(m, filepath.Join("..", "..")) } func TestWikiNameToSubURL(t *testing.T) { @@ -110,7 +111,7 @@ func TestWikiNameToFilenameToName(t *testing.T) { } func TestRepository_InitWiki(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) // repo1 already has a wiki repo1 := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) assert.NoError(t, InitWiki(repo1)) @@ -122,7 +123,7 @@ func TestRepository_InitWiki(t *testing.T) { } func TestRepository_AddWikiPage(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) const wikiContent = "This is the wiki content" const commitMsg = "Commit message" repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) @@ -166,7 +167,7 @@ func TestRepository_AddWikiPage(t *testing.T) { } func TestRepository_EditWikiPage(t *testing.T) { - assert.NoError(t, db.PrepareTestDatabase()) + assert.NoError(t, unittest.PrepareTestDatabase()) const newWikiContent = "This is the new content" const commitMsg = "Commit message" @@ -177,7 +178,7 @@ func TestRepository_EditWikiPage(t *testing.T) { "New home", "New/name/with/slashes", } { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) assert.NoError(t, EditWikiPage(doer, repo, "Home", newWikiName, newWikiContent, commitMsg)) // Now need to show that the page has been added: @@ -199,7 +200,7 @@ func TestRepository_EditWikiPage(t *testing.T) { } func TestRepository_DeleteWikiPage(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) doer := db.AssertExistsAndLoadBean(t, &models.User{ID: 2}).(*models.User) assert.NoError(t, DeleteWikiPage(doer, repo, "Home")) @@ -216,7 +217,7 @@ func TestRepository_DeleteWikiPage(t *testing.T) { } func TestPrepareWikiFileName(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) repo := db.AssertExistsAndLoadBean(t, &models.Repository{ID: 1}).(*models.Repository) gitRepo, err := git.OpenRepository(repo.WikiPath()) defer gitRepo.Close() @@ -267,7 +268,7 @@ func TestPrepareWikiFileName(t *testing.T) { } func TestPrepareWikiFileName_FirstPage(t *testing.T) { - db.PrepareTestEnv(t) + unittest.PrepareTestEnv(t) // Now create a temporaryDirectory tmpDir, err := os.MkdirTemp("", "empty-wiki") From 47448083a1b88201dcfa00ec06fb748f5ac18040 Mon Sep 17 00:00:00 2001 From: Michael Grigoryan <56165400+michaelgrigoryan25@users.noreply.github.com> Date: Sat, 13 Nov 2021 03:27:18 +0400 Subject: [PATCH 03/24] Minor readability patch. (#17627) --- services/auth/basic.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/auth/basic.go b/services/auth/basic.go index 0c400b6b5329..d7f889cbdc8e 100644 --- a/services/auth/basic.go +++ b/services/auth/basic.go @@ -50,7 +50,7 @@ func (b *Basic) Verify(req *http.Request, w http.ResponseWriter, store DataStore } auths := strings.SplitN(baHead, " ", 2) - if len(auths) != 2 || (auths[0] != "Basic" && auths[0] != "basic") { + if len(auths) != 2 || (strings.ToLower(auths[0]) != "basic") { return nil } From bab95c3a86f63f521311a77e516be5b6c521e0a4 Mon Sep 17 00:00:00 2001 From: zeripath Date: Sat, 13 Nov 2021 11:28:50 +0000 Subject: [PATCH 04/24] Correctly handle failed migrations (#17575) * Correctly handle failed migrations There is a bug in handling failed migrations whereby the migration task gets decoupled from the migration repository. This leads to a failure of the task to get deleted with the repository and also leads to the migration failed page resulting in a ISE. This PR removes the zeroing out of the task id from the migration but also makes the migration handler tolerate missing tasks much nicer. Fix #17571 Signed-off-by: Andrew Thornton --- modules/task/migrate.go | 3 +++ modules/task/task.go | 6 +++--- options/locale/locale_en-US.ini | 1 + routers/web/repo/view.go | 7 +++++++ routers/web/user/task.go | 7 +++++++ templates/repo/migrate/migrating.tmpl | 6 +++++- 6 files changed, 26 insertions(+), 4 deletions(-) diff --git a/modules/task/migrate.go b/modules/task/migrate.go index 52f4bb91cf72..715e76b4ade0 100644 --- a/modules/task/migrate.go +++ b/modules/task/migrate.go @@ -58,6 +58,9 @@ func runMigrateTask(t *models.Task) (err error) { t.EndTime = timeutil.TimeStampNow() t.Status = structs.TaskStatusFailed t.Message = err.Error() + // Ensure that the repo loaded before we zero out the repo ID from the task - thus ensuring that we can delete it + _ = t.LoadRepo() + t.RepoID = 0 if err := t.UpdateCols("status", "errors", "repo_id", "end_time"); err != nil { log.Error("Task UpdateCols failed: %v", err) diff --git a/modules/task/task.go b/modules/task/task.go index 4e782869f93f..51377df78c93 100644 --- a/modules/task/task.go +++ b/modules/task/task.go @@ -90,7 +90,7 @@ func CreateMigrateTask(doer, u *models.User, opts base.MigrateOptions) (*models. return nil, err } - var task = models.Task{ + var task = &models.Task{ DoerID: doer.ID, OwnerID: u.ID, Type: structs.TaskTypeMigrateRepo, @@ -98,7 +98,7 @@ func CreateMigrateTask(doer, u *models.User, opts base.MigrateOptions) (*models. PayloadContent: string(bs), } - if err := models.CreateTask(&task); err != nil { + if err := models.CreateTask(task); err != nil { return nil, err } @@ -126,5 +126,5 @@ func CreateMigrateTask(doer, u *models.User, opts base.MigrateOptions) (*models. return nil, err } - return &task, nil + return task, nil } diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 2632531e2fb5..6fad20c87ed0 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -904,6 +904,7 @@ migrate.migrate = Migrate From %s migrate.migrating = Migrating from %s ... migrate.migrating_failed = Migrating from %s failed. migrate.migrating_failed.error = Error: %s +migrate.migrating_failed_no_addr = Migration failed. migrate.github.description = Migrate data from github.com or other Github instances. migrate.git.description = Migrate a repository only from any Git service. migrate.gitlab.description = Migrate data from gitlab.com or other GitLab instances. diff --git a/routers/web/repo/view.go b/routers/web/repo/view.go index 72f12e9bf2a5..cecd8437b696 100644 --- a/routers/web/repo/view.go +++ b/routers/web/repo/view.go @@ -583,6 +583,13 @@ func checkHomeCodeViewable(ctx *context.Context) { if ctx.Repo.Repository.IsBeingCreated() { task, err := models.GetMigratingTask(ctx.Repo.Repository.ID) if err != nil { + if models.IsErrTaskDoesNotExist(err) { + ctx.Data["Repo"] = ctx.Repo + ctx.Data["CloneAddr"] = "" + ctx.Data["Failed"] = true + ctx.HTML(http.StatusOK, tplMigrating) + return + } ctx.ServerError("models.GetMigratingTask", err) return } diff --git a/routers/web/user/task.go b/routers/web/user/task.go index c71d43523393..4dbd1b8537bf 100644 --- a/routers/web/user/task.go +++ b/routers/web/user/task.go @@ -6,6 +6,7 @@ package user import ( "net/http" + "strconv" "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/context" @@ -16,6 +17,12 @@ import ( func TaskStatus(ctx *context.Context) { task, opts, err := models.GetMigratingTaskByID(ctx.ParamsInt64("task"), ctx.User.ID) if err != nil { + if models.IsErrTaskDoesNotExist(err) { + ctx.JSON(http.StatusNotFound, map[string]interface{}{ + "error": "task `" + strconv.FormatInt(ctx.ParamsInt64("task"), 10) + "` does not exist", + }) + return + } ctx.JSON(http.StatusInternalServerError, map[string]interface{}{ "err": err, }) diff --git a/templates/repo/migrate/migrating.tmpl b/templates/repo/migrate/migrating.tmpl index cc12243205c1..6df7f0a65d68 100644 --- a/templates/repo/migrate/migrating.tmpl +++ b/templates/repo/migrate/migrating.tmpl @@ -25,7 +25,11 @@

{{if and .Failed .Permission.IsAdmin}} From 424959e07cf197e03297b0277f48785d0864e9a1 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Sun, 14 Nov 2021 00:26:06 +0000 Subject: [PATCH 05/24] [skip ci] Updated licenses and gitignores --- options/license/BSD-1-Clause | 23 +- options/license/COIL-1.0 | 30 +++ options/license/Community-Spec-1.0 | 293 +++++++++++++++++++++++ options/license/FDK-AAC | 79 ++++++ options/license/Linux-man-pages-copyleft | 2 +- 5 files changed, 408 insertions(+), 19 deletions(-) create mode 100644 options/license/COIL-1.0 create mode 100644 options/license/Community-Spec-1.0 create mode 100644 options/license/FDK-AAC diff --git a/options/license/BSD-1-Clause b/options/license/BSD-1-Clause index 8f8d606c656f..4005b63def76 100644 --- a/options/license/BSD-1-Clause +++ b/options/license/BSD-1-Clause @@ -1,20 +1,7 @@ -Copyright (c) [Year] -[Name of Organization]. All rights reserved. +Copyright (c) . All rights reserved. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions -are met: -1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -THIS SOFTWARE IS PROVIDED BY [Name of Organization] ``AS IS'' AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL [Name of Organization] BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS -OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF -SUCH DAMAGE. +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/options/license/COIL-1.0 b/options/license/COIL-1.0 new file mode 100644 index 000000000000..c24c539e3184 --- /dev/null +++ b/options/license/COIL-1.0 @@ -0,0 +1,30 @@ +# Copyfree Open Innovation License + +This is version 1.0 of the Copyfree Open Innovation License. + +## Terms and Conditions + +Redistributions, modified or unmodified, in whole or in part, must retain +applicable notices of copyright or other legal privilege, these conditions, and +the following license terms and disclaimer. Subject to these conditions, each +holder of copyright or other legal privileges, author or assembler, and +contributor of this work, henceforth "licensor", hereby grants to any person +who obtains a copy of this work in any form: + +1. Permission to reproduce, modify, distribute, publish, sell, sublicense, use, +and/or otherwise deal in the licensed material without restriction. + +2. A perpetual, worldwide, non-exclusive, royalty-free, gratis, irrevocable +patent license to make, have made, provide, transfer, import, use, and/or +otherwise deal in the licensed material without restriction, for any and all +patents held by such licensor and necessarily infringed by the form of the work +upon distribution of that licensor's contribution to the work under the terms +of this license. + +NO WARRANTY OF ANY KIND IS IMPLIED BY, OR SHOULD BE INFERRED FROM, THIS LICENSE +OR THE ACT OF DISTRIBUTION UNDER THE TERMS OF THIS LICENSE, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, +AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS, ASSEMBLERS, OR HOLDERS OF +COPYRIGHT OR OTHER LEGAL PRIVILEGE BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER +LIABILITY, WHETHER IN ACTION OF CONTRACT, TORT, OR OTHERWISE ARISING FROM, OUT +OF, OR IN CONNECTION WITH THE WORK OR THE USE OF OR OTHER DEALINGS IN THE WORK. diff --git a/options/license/Community-Spec-1.0 b/options/license/Community-Spec-1.0 new file mode 100644 index 000000000000..cdf7c64c07cd --- /dev/null +++ b/options/license/Community-Spec-1.0 @@ -0,0 +1,293 @@ +Community Specification License 1.0 + +The Purpose of this License. This License sets forth the terms under which +1) Contributor will participate in and contribute to the development +of specifications, standards, best practices, guidelines, and other +similar materials under this Working Group, and 2) how the materials +developed under this License may be used. It is not intended for source +code. Capitalized terms are defined in the License’s last section. + +1. Copyright. + +1.1. Copyright License. Contributor grants everyone a non-sublicensable, +perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable +(except as expressly stated in this License) copyright license, without +any obligation for accounting, to reproduce, prepare derivative works +of, publicly display, publicly perform, and distribute any materials +it submits to the full extent of its copyright interest in those +materials. Contributor also acknowledges that the Working Group may +exercise copyright rights in the Specification, including the rights to +submit the Specification to another standards organization. + +1.2. Copyright Attribution. As a condition, anyone exercising this +copyright license must include attribution to the Working Group in any +derivative work based on materials developed by the Working Group. +That attribution must include, at minimum, the material’s name, +version number, and source from where the materials were retrieved. +Attribution is not required for implementations of the Specification. + +2. Patents. + +2.1. Patent License. + +2.1.1. As a Result of Contributions. + +2.1.1.1. As a Result of Contributions to Draft Specifications. +Contributor grants Licensee a non-sublicensable, perpetual, worldwide, +non-exclusive, no-charge, royalty-free, irrevocable (except as +expressly stated in this License) license to its Necessary Claims in 1) +Contributor’s Contributions and 2) to the Draft Specification that +is within Scope as of the date of that Contribution, in both cases for +Licensee’s Implementation of the Draft Specification, except for those +patent claims excluded by Contributor under Section 3. + +2.1.1.2. For Approved Specifications. Contributor grants Licensee a +non-sublicensable, perpetual, worldwide, non-exclusive, no-charge, +royalty-free, irrevocable (except as expressly stated in this License) +license to its Necessary Claims included the Approved Specification +that are within Scope for Licensee’s Implementation of the Approved +Specification, except for those patent claims excluded by Contributor +under Section 3. + +2.1.2. Patent Grant from Licensee. Licensee grants each other Licensee +a non-sublicensable, perpetual, worldwide, non-exclusive, no-charge, +royalty-free, irrevocable (except as expressly stated in this License) +license to its Necessary Claims for its Implementation, except for those +patent claims excluded under Section 3. + +2.1.3. Licensee Acceptance. The patent grants set forth in Section 2.1 +extend only to Licensees that have indicated their agreement to this +License as follows: + +2.1.3.1. Source Code Distributions. For distribution in source code, +by including this License in the root directory of the source code with +the Implementation; + +2.1.3.2. Non-Source Code Distributions. For distribution in any form +other than source code, by including this License in the documentation, +legal notices, via notice in the software, and/or other written materials +provided with the Implementation; or + +2.1.3.3. Via Notices.md. By issuing pull request or commit to the +Specification’s repository’s Notices.md file by the Implementer’s +authorized representative, including the Implementer’s name, authorized +individual and system identifier, and Specification version. + +2.1.4. Defensive Termination. If any Licensee files or maintains a +claim in a court asserting that a Necessary Claim is infringed by an +Implementation, any licenses granted under this License to the Licensee +are immediately terminated unless 1) that claim is directly in response +to a claim against Licensee regarding an Implementation, or 2) that claim +was brought to enforce the terms of this License, including intervention +in a third-party action by a Licensee. + +2.1.5. Additional Conditions. This License is not an assurance (i) +that any of Contributor’s copyrights or issued patent claims cover +an Implementation of the Specification or are enforceable or (ii) that +an Implementation of the Specification would not infringe intellectual +property rights of any third party. + +2.2. Patent Licensing Commitment. In addition to the rights granted +in Section 2.1, Contributor agrees to grant everyone a no charge, +royalty-free license on reasonable and non-discriminatory terms +to Contributor’s Necessary Claims that are within Scope for: +1) Implementations of a Draft Specification, where such license +applies only to those Necessary Claims infringed by implementing +Contributor's Contribution(s) included in that Draft Specification, +and 2) Implementations of the Approved Specification. + +This patent licensing commitment does not apply to those claims subject +to Contributor’s Exclusion Notice under Section 3. + +2.3. Effect of Withdrawal. Contributor may withdraw from the Working Group +by issuing a pull request or commit providing notice of withdrawal to +the Working Group repository’s Notices.md file. All of Contributor’s +existing commitments and obligations with respect to the Working Group +up to the date of that withdrawal notice will remain in effect, but no +new obligations will be incurred. + +2.4. Binding Encumbrance. This License is binding on any future owner, +assignee, or party who has been given the right to enforce any Necessary +Claims against third parties. + +3. Patent Exclusion. + +3.1. As a Result of Contributions. Contributor may exclude Necessary +Claims from its licensing commitments incurred under Section 2.1.1 +by issuing an Exclusion Notice within 45 days of the date of that +Contribution. Contributor may not issue an Exclusion Notice for any +material that has been included in a Draft Deliverable for more than 45 +days prior to the date of that Contribution. + +3.2. As a Result of a Draft Specification Becoming an Approved +Specification. Prior to the adoption of a Draft Specification as an +Approved Specification, Contributor may exclude Necessary Claims from +its licensing commitments under this Agreement by issuing an Exclusion +Notice. Contributor may not issue an Exclusion Notice for patents that +were eligible to have been excluded pursuant to Section 3.1. + +4. Source Code License. Any source code developed by the Working Group is +solely subject the source code license included in the Working Group’s +repository for that code. If no source code license is included, the +source code will be subject to the MIT License. + +5. No Other Rights. Except as specifically set forth in this License, no +other express or implied patent, trademark, copyright, or other rights are +granted under this License, including by implication, waiver, or estoppel. + +6. Antitrust Compliance. Contributor acknowledge that it may compete +with other participants in various lines of business and that it is +therefore imperative that they and their respective representatives +act in a manner that does not violate any applicable antitrust laws and +regulations. This License does not restrict any Contributor from engaging +in similar specification development projects. Each Contributor may +design, develop, manufacture, acquire or market competitive deliverables, +products, and services, and conduct its business, in whatever way it +chooses. No Contributor is obligated to announce or market any products +or services. Without limiting the generality of the foregoing, the +Contributors agree not to have any discussion relating to any product +pricing, methods or channels of product distribution, division of markets, +allocation of customers or any other topic that should not be discussed +among competitors under the auspices of the Working Group. + +7. Non-Circumvention. Contributor agrees that it will not intentionally +take or willfully assist any third party to take any action for the +purpose of circumventing any obligations under this License. + +8. Representations, Warranties and Disclaimers. + +8.1. Representations, Warranties and Disclaimers. Contributor and Licensee +represents and warrants that 1) it is legally entitled to grant the +rights set forth in this License and 2) it will not intentionally include +any third party materials in any Contribution unless those materials are +available under terms that do not conflict with this License. IN ALL OTHER +RESPECTS ITS CONTRIBUTIONS ARE PROVIDED "AS IS." The entire risk as to +implementing or otherwise using the Contribution or the Specification +is assumed by the implementer and user. Except as stated herein, +CONTRIBUTOR AND LICENSEE EXPRESSLY DISCLAIM ANY WARRANTIES (EXPRESS, +IMPLIED, OR OTHERWISE), INCLUDING IMPLIED WARRANTIES OF MERCHANTABILITY, +NON-INFRINGEMENT, FITNESS FOR A PARTICULAR PURPOSE, CONDITIONS OF QUALITY, +OR TITLE, RELATED TO THE CONTRIBUTION OR THE SPECIFICATION. IN NO EVENT +WILL ANY PARTY BE LIABLE TO ANY OTHER PARTY FOR LOST PROFITS OR ANY +FORM OF INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF +ANY CHARACTER FROM ANY CAUSES OF ACTION OF ANY KIND WITH RESPECT TO +THIS AGREEMENT, WHETHER BASED ON BREACH OF CONTRACT, TORT (INCLUDING +NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT THE OTHER PARTY HAS BEEN +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Any obligations regarding +the transfer, successors in interest, or assignment of Necessary Claims +will be satisfied if Contributor or Licensee notifies the transferee +or assignee of any patent that it knows contains Necessary Claims or +necessary claims under this License. Nothing in this License requires +Contributor to undertake a patent search. If Contributor is 1) employed by +or acting on behalf of an employer, 2) is making a Contribution under the +direction or control of a third party, or 3) is making the Contribution +as a consultant, contractor, or under another similar relationship with +a third party, Contributor represents that they have been authorized by +that party to enter into this License on its behalf. + +8.2. Distribution Disclaimer. Any distributions of technical +information to third parties must include a notice materially similar +to the following: “THESE MATERIALS ARE PROVIDED “AS IS.” The +Contributors and Licensees expressly disclaim any warranties (express, +implied, or otherwise), including implied warranties of merchantability, +non-infringement, fitness for a particular purpose, or title, related to +the materials. The entire risk as to implementing or otherwise using the +materials is assumed by the implementer and user. IN NO EVENT WILL THE +CONTRIBUTORS OR LICENSEES BE LIABLE TO ANY OTHER PARTY FOR LOST PROFITS +OR ANY FORM OF INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES +OF ANY CHARACTER FROM ANY CAUSES OF ACTION OF ANY KIND WITH RESPECT TO +THIS DELIVERABLE OR ITS GOVERNING AGREEMENT, WHETHER BASED ON BREACH OF +CONTRACT, TORT (INCLUDING NEGLIGENCE), OR OTHERWISE, AND WHETHER OR NOT +THE OTHER MEMBER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.” + +9. Definitions. + +9.1. Affiliate. “Affiliate” means an entity that directly or +indirectly Controls, is Controlled by, or is under common Control of +that party. + +9.2. Approved Specification. “Approved Specification” means the final +version and contents of any Draft Specification designated as an Approved +Specification as set forth in the accompanying Governance.md file. + +9.3. Contribution. “Contribution” means any original work of +authorship, including any modifications or additions to an existing +work, that Contributor submits for inclusion in a Draft Specification, +which is included in a Draft Specification or Approved Specification. + +9.4. Contributor. “Contributor” means any person or entity that has +indicated its acceptance of the License 1) by making a Contribution to +the Specification, or 2) by entering into the Community Specification +Contributor License Agreement for the Specification. Contributor includes +its Affiliates, assigns, agents, and successors in interest. + +9.5. Control. “Control” means direct or indirect control of more +than 50% of the voting power to elect directors of that corporation, +or for any other entity, the power to direct management of such entity. + +9.6. Draft Specification. “Draft Specification” means all versions +of the material (except an Approved Specification) developed by this +Working Group for the purpose of creating, commenting on, revising, +updating, modifying, or adding to any document that is to be considered +for inclusion in the Approved Specification. + +9.7. Exclusion Notice. “Exclusion Notice” means a written notice +made by making a pull request or commit to the repository’s Notices.md +file that identifies patents that Contributor is excluding from its +patent licensing commitments under this License. The Exclusion Notice +for issued patents and published applications must include the Draft +Specification’s name, patent number(s) or title and application +number(s), as the case may be, for each of the issued patent(s) or +pending patent application(s) that the Contributor is excluding from the +royalty-free licensing commitment set forth in this License. If an issued +patent or pending patent application that may contain Necessary Claims +is not set forth in the Exclusion Notice, those Necessary Claims shall +continue to be subject to the licensing commitments under this License. +The Exclusion Notice for unpublished patent applications must provide +either: (i) the text of the filed application; or (ii) identification +of the specific part(s) of the Draft Specification whose implementation +makes the excluded claim a Necessary Claim. If (ii) is chosen, the +effect of the exclusion will be limited to the identified part(s) of +the Draft Specification. + +9.8. Implementation. “Implementation” means making, using, selling, +offering for sale, importing or distributing any implementation of the +Specification 1) only to the extent it implements the Specification and 2) +so long as all required portions of the Specification are implemented. + +9.9. License. “License” means this Community Specification License. + +9.10. Licensee. “Licensee” means any person or entity that has +indicated its acceptance of the License as set forth in Section 2.1.3. +Licensee includes its Affiliates, assigns, agents, and successors in +interest. + +9.11. Necessary Claims. “Necessary Claims” are those patent claims, if +any, that a party owns or controls, including those claims later acquired, +that are necessary to implement the required portions (including the +required elements of optional portions) of the Specification that are +described in detail and not merely referenced in the Specification. + +9.12. Specification. “Specification” means a Draft Specification +or Approved Specification included in the Working Group’s repository +subject to this License, and the version of the Specification implemented +by the Licensee. + +9.13. Scope. “Scope” has the meaning as set forth in the accompanying +Scope.md file included in this Specification’s repository. Changes +to Scope do not apply retroactively. If no Scope is provided, each +Contributor’s Necessary Claims are limited to that Contributor’s +Contributions. + +9.14. Working Group. “Working Group” means this project to develop +specifications, standards, best practices, guidelines, and other similar +materials under this License. + + + +The text of this Community Specification License is Copyright 2020 +Joint Development Foundation and is licensed under the Creative +Commons Attribution 4.0 International License available at +https://creativecommons.org/licenses/by/4.0/. + +SPDX-License-Identifier: CC-BY-4.0 diff --git a/options/license/FDK-AAC b/options/license/FDK-AAC new file mode 100644 index 000000000000..e506d69d5eea --- /dev/null +++ b/options/license/FDK-AAC @@ -0,0 +1,79 @@ +Software License for The Fraunhofer FDK AAC Codec Library for Android + +© Copyright 1995 - 2012 Fraunhofer-Gesellschaft zur Förderung der angewandten Forschung e.V. + All rights reserved. + +1. INTRODUCTION +The Fraunhofer FDK AAC Codec Library for Android ("FDK AAC Codec") is software that implements +the MPEG Advanced Audio Coding ("AAC") encoding and decoding scheme for digital audio. +This FDK AAC Codec software is intended to be used on a wide variety of Android devices. + +AAC's HE-AAC and HE-AAC v2 versions are regarded as today's most efficient general perceptual +audio codecs. AAC-ELD is considered the best-performing full-bandwidth communications codec by +independent studies and is widely deployed. AAC has been standardized by ISO and IEC as part +of the MPEG specifications. + +Patent licenses for necessary patent claims for the FDK AAC Codec (including those of Fraunhofer) +may be obtained through Via Licensing (www.vialicensing.com) or through the respective patent owners +individually for the purpose of encoding or decoding bit streams in products that are compliant with +the ISO/IEC MPEG audio standards. Please note that most manufacturers of Android devices already license +these patent claims through Via Licensing or directly from the patent owners, and therefore FDK AAC Codec +software may already be covered under those patent licenses when it is used for those licensed purposes only. + +Commercially-licensed AAC software libraries, including floating-point versions with enhanced sound quality, +are also available from Fraunhofer. Users are encouraged to check the Fraunhofer website for additional +applications information and documentation. + +2. COPYRIGHT LICENSE + +Redistribution and use in source and binary forms, with or without modification, are permitted without +payment of copyright license fees provided that you satisfy the following conditions: + +You must retain the complete text of this software license in redistributions of the FDK AAC Codec or +your modifications thereto in source code form. + +You must retain the complete text of this software license in the documentation and/or other materials +provided with redistributions of the FDK AAC Codec or your modifications thereto in binary form. +You must make available free of charge copies of the complete source code of the FDK AAC Codec and your +modifications thereto to recipients of copies in binary form. + +The name of Fraunhofer may not be used to endorse or promote products derived from this library without +prior written permission. + +You may not charge copyright license fees for anyone to use, copy or distribute the FDK AAC Codec +software or your modifications thereto. + +Your modified versions of the FDK AAC Codec must carry prominent notices stating that you changed the software +and the date of any change. For modified versions of the FDK AAC Codec, the term +"Fraunhofer FDK AAC Codec Library for Android" must be replaced by the term +"Third-Party Modified Version of the Fraunhofer FDK AAC Codec Library for Android." + +3. NO PATENT LICENSE + +NO EXPRESS OR IMPLIED LICENSES TO ANY PATENT CLAIMS, including without limitation the patents of Fraunhofer, +ARE GRANTED BY THIS SOFTWARE LICENSE. Fraunhofer provides no warranty of patent non-infringement with +respect to this software. + +You may use this FDK AAC Codec software or modifications thereto only for purposes that are authorized +by appropriate patent licenses. + +4. DISCLAIMER + +This FDK AAC Codec software is provided by Fraunhofer on behalf of the copyright holders and contributors +"AS IS" and WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, including but not limited to the implied warranties +of merchantability and fitness for a particular purpose. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +CONTRIBUTORS BE LIABLE for any direct, indirect, incidental, special, exemplary, or consequential damages, +including but not limited to procurement of substitute goods or services; loss of use, data, or profits, +or business interruption, however caused and on any theory of liability, whether in contract, strict +liability, or tort (including negligence), arising in any way out of the use of this software, even if +advised of the possibility of such damage. + +5. CONTACT INFORMATION + +Fraunhofer Institute for Integrated Circuits IIS +Attention: Audio and Multimedia Departments - FDK AAC LL +Am Wolfsmantel 33 +91058 Erlangen, Germany + +www.iis.fraunhofer.de/amm +amm-info@iis.fraunhofer.de diff --git a/options/license/Linux-man-pages-copyleft b/options/license/Linux-man-pages-copyleft index 8a10d8e6840d..764635ae5c8d 100644 --- a/options/license/Linux-man-pages-copyleft +++ b/options/license/Linux-man-pages-copyleft @@ -1,4 +1,4 @@ -Copyright (c) 0000, Obelix the Gaul . +Copyright (c) All rights reserved. Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are From 8eddb755086f84c8c1168447391ac04a3a6b7702 Mon Sep 17 00:00:00 2001 From: Gusted Date: Sun, 14 Nov 2021 05:28:57 +0000 Subject: [PATCH 06/24] perf: only generate data-comment-url once (#17618) --- templates/repo/diff/box.tmpl | 2 +- templates/repo/diff/section_split.tmpl | 8 ++++---- templates/repo/diff/section_unified.tmpl | 2 +- web_src/js/features/repo-issue.js | 2 +- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/templates/repo/diff/box.tmpl b/templates/repo/diff/box.tmpl index 30039f0d1ab7..8aa324206332 100644 --- a/templates/repo/diff/box.tmpl +++ b/templates/repo/diff/box.tmpl @@ -118,7 +118,7 @@ {{end}} {{else}} - +
{{if $.IsSplitStyle}} {{template "repo/diff/section_split" dict "file" . "root" $}} {{else}} diff --git a/templates/repo/diff/section_split.tmpl b/templates/repo/diff/section_split.tmpl index aed6d784b307..ca070858716c 100644 --- a/templates/repo/diff/section_split.tmpl +++ b/templates/repo/diff/section_split.tmpl @@ -27,17 +27,17 @@ {{$match := index $section.Lines $line.Match}} - + - + {{else}} - + - + {{end}} {{if and (eq .GetType 3) $hasmatch}} diff --git a/templates/repo/diff/section_unified.tmpl b/templates/repo/diff/section_unified.tmpl index 96e193df7346..e89f1a09f73c 100644 --- a/templates/repo/diff/section_unified.tmpl +++ b/templates/repo/diff/section_unified.tmpl @@ -29,7 +29,7 @@ {{if eq .GetType 4}} {{else}} - + {{end}} {{if gt (len $line.Comments) 0}} diff --git a/web_src/js/features/repo-issue.js b/web_src/js/features/repo-issue.js index c95b6c13079b..782957c5b16c 100644 --- a/web_src/js/features/repo-issue.js +++ b/web_src/js/features/repo-issue.js @@ -517,7 +517,7 @@ export function initRepoPullRequestReview() { const td = ntr.find(`.add-comment-${side}`); let commentCloud = td.find('.comment-code-cloud'); if (commentCloud.length === 0 && !ntr.find('button[name="is_review"]').length) { - const data = await $.get($(this).data('new-comment-url')); + const data = await $.get($(this).closest('[data-new-comment-url]').data('new-comment-url')); td.html(data); commentCloud = td.find('.comment-code-cloud'); assignMenuAttributes(commentCloud.find('.menu')); From d2163df6a0d6b9663a65438c1d960ea4ab5c2df0 Mon Sep 17 00:00:00 2001 From: Gusted Date: Sun, 14 Nov 2021 08:11:49 +0000 Subject: [PATCH 07/24] Fix offBy1 errors (#17606) * Fix offBy1 errors - Partially resolves #17596 - Resolve errors from go-critic `offBy1: Index() can return -1; maybe you wanted to do Index()+1`. * Match golang spec * Remove comments * Update migrations.go * Apply suggestions from code review Co-authored-by: delvh Co-authored-by: wxiaoguang Co-authored-by: delvh Co-authored-by: Lunny Xiao --- cmd/docs.go | 6 +++++- models/migrations/migrations.go | 9 ++++++++- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/cmd/docs.go b/cmd/docs.go index 52233c7ac872..073c57497305 100644 --- a/cmd/docs.go +++ b/cmd/docs.go @@ -43,7 +43,11 @@ func runDocs(ctx *cli.Context) error { // Clean up markdown. The following bug was fixed in v2, but is present in v1. // It affects markdown output (even though the issue is referring to man pages) // https://github.com/urfave/cli/issues/1040 - docs = docs[strings.Index(docs, "#"):] + firstHashtagIndex := strings.Index(docs, "#") + + if firstHashtagIndex > 0 { + docs = docs[firstHashtagIndex:] + } } out := os.Stdout diff --git a/models/migrations/migrations.go b/models/migrations/migrations.go index 2686dfb3cff9..c0d8f111d376 100644 --- a/models/migrations/migrations.go +++ b/models/migrations/migrations.go @@ -7,6 +7,7 @@ package migrations import ( "context" + "errors" "fmt" "os" "reflect" @@ -791,8 +792,14 @@ func dropTableColumns(sess *xorm.Session, tableName string, columnNames ...strin } tableSQL := string(res[0]["sql"]) + // Get the string offset for column definitions: `CREATE TABLE ( column-definitions... )` + columnDefinitionsIndex := strings.Index(tableSQL, "(") + if columnDefinitionsIndex < 0 { + return errors.New("couldn't find column definitions") + } + // Separate out the column definitions - tableSQL = tableSQL[strings.Index(tableSQL, "("):] + tableSQL = tableSQL[columnDefinitionsIndex:] // Remove the required columnNames for _, name := range columnNames { From 42ea0023a30fd6a0e2e2da1e32ece0a484c03a65 Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Sun, 14 Nov 2021 20:11:10 +0100 Subject: [PATCH 08/24] Add migration from GitBucket (#16767) This PR adds [GitBucket](https://gitbucket.github.io/) as migration source. Supported: - Milestones - Issues - Pull Requests - Comments - Reviews - Labels There is no public usable instance so no integration tests added. --- modules/convert/utils.go | 2 + modules/migrations/gitbucket.go | 72 +++++++++ modules/migrations/github.go | 209 ++++++++++++++------------ modules/structs/repo.go | 18 ++- options/locale/locale_en-US.ini | 1 + public/img/svg/gitea-gitbucket.svg | 1 + templates/repo/migrate/gitbucket.tmpl | 129 ++++++++++++++++ web_src/svg/gitea-gitbucket.svg | 39 +++++ 8 files changed, 365 insertions(+), 106 deletions(-) create mode 100644 modules/migrations/gitbucket.go create mode 100644 public/img/svg/gitea-gitbucket.svg create mode 100644 templates/repo/migrate/gitbucket.tmpl create mode 100644 web_src/svg/gitea-gitbucket.svg diff --git a/modules/convert/utils.go b/modules/convert/utils.go index a0463d7b1006..52fbcf547f72 100644 --- a/modules/convert/utils.go +++ b/modules/convert/utils.go @@ -35,6 +35,8 @@ func ToGitServiceType(value string) structs.GitServiceType { return structs.GogsService case "onedev": return structs.OneDevService + case "gitbucket": + return structs.GitBucketService default: return structs.PlainGitService } diff --git a/modules/migrations/gitbucket.go b/modules/migrations/gitbucket.go new file mode 100644 index 000000000000..72090c24900c --- /dev/null +++ b/modules/migrations/gitbucket.go @@ -0,0 +1,72 @@ +// Copyright 2021 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package migrations + +import ( + "context" + "net/url" + "strings" + + "code.gitea.io/gitea/modules/migrations/base" + "code.gitea.io/gitea/modules/structs" +) + +var ( + _ base.Downloader = &GitBucketDownloader{} + _ base.DownloaderFactory = &GitBucketDownloaderFactory{} +) + +func init() { + RegisterDownloaderFactory(&GitBucketDownloaderFactory{}) +} + +// GitBucketDownloaderFactory defines a GitBucket downloader factory +type GitBucketDownloaderFactory struct { +} + +// New returns a Downloader related to this factory according MigrateOptions +func (f *GitBucketDownloaderFactory) New(ctx context.Context, opts base.MigrateOptions) (base.Downloader, error) { + u, err := url.Parse(opts.CloneAddr) + if err != nil { + return nil, err + } + + baseURL := u.Scheme + "://" + u.Host + fields := strings.Split(u.Path, "/") + oldOwner := fields[1] + oldName := strings.TrimSuffix(fields[2], ".git") + + return NewGitBucketDownloader(ctx, baseURL, opts.AuthUsername, opts.AuthPassword, opts.AuthToken, oldOwner, oldName), nil +} + +// GitServiceType returns the type of git service +func (f *GitBucketDownloaderFactory) GitServiceType() structs.GitServiceType { + return structs.GitBucketService +} + +// GitBucketDownloader implements a Downloader interface to get repository information +// from GitBucket via GithubDownloader +type GitBucketDownloader struct { + *GithubDownloaderV3 +} + +// NewGitBucketDownloader creates a GitBucket downloader +func NewGitBucketDownloader(ctx context.Context, baseURL, userName, password, token, repoOwner, repoName string) *GitBucketDownloader { + githubDownloader := NewGithubDownloaderV3(ctx, baseURL, userName, password, token, repoOwner, repoName) + githubDownloader.SkipReactions = true + return &GitBucketDownloader{ + githubDownloader, + } +} + +// SupportGetRepoComments return true if it supports get repo comments +func (g *GitBucketDownloader) SupportGetRepoComments() bool { + return false +} + +// GetReviews is not supported +func (g *GitBucketDownloader) GetReviews(context base.IssueContext) ([]*base.Review, error) { + return nil, &base.ErrNotSupported{Entity: "Reviews"} +} diff --git a/modules/migrations/github.go b/modules/migrations/github.go index 874cd054394f..50cffc467a70 100644 --- a/modules/migrations/github.go +++ b/modules/migrations/github.go @@ -68,15 +68,16 @@ func (f *GithubDownloaderV3Factory) GitServiceType() structs.GitServiceType { // from github via APIv3 type GithubDownloaderV3 struct { base.NullDownloader - ctx context.Context - clients []*github.Client - repoOwner string - repoName string - userName string - password string - rates []*github.Rate - curClientIdx int - maxPerPage int + ctx context.Context + clients []*github.Client + repoOwner string + repoName string + userName string + password string + rates []*github.Rate + curClientIdx int + maxPerPage int + SkipReactions bool } // NewGithubDownloaderV3 creates a github Downloader via github v3 API @@ -428,25 +429,27 @@ func (g *GithubDownloaderV3) GetIssues(page, perPage int) ([]*base.Issue, bool, // get reactions var reactions []*base.Reaction - for i := 1; ; i++ { - g.waitAndPickClient() - res, resp, err := g.getClient().Reactions.ListIssueReactions(g.ctx, g.repoOwner, g.repoName, issue.GetNumber(), &github.ListOptions{ - Page: i, - PerPage: perPage, - }) - if err != nil { - return nil, false, err - } - g.setRate(&resp.Rate) - if len(res) == 0 { - break - } - for _, reaction := range res { - reactions = append(reactions, &base.Reaction{ - UserID: reaction.User.GetID(), - UserName: reaction.User.GetLogin(), - Content: reaction.GetContent(), + if !g.SkipReactions { + for i := 1; ; i++ { + g.waitAndPickClient() + res, resp, err := g.getClient().Reactions.ListIssueReactions(g.ctx, g.repoOwner, g.repoName, issue.GetNumber(), &github.ListOptions{ + Page: i, + PerPage: perPage, }) + if err != nil { + return nil, false, err + } + g.setRate(&resp.Rate) + if len(res) == 0 { + break + } + for _, reaction := range res { + reactions = append(reactions, &base.Reaction{ + UserID: reaction.User.GetID(), + UserName: reaction.User.GetLogin(), + Content: reaction.GetContent(), + }) + } } } @@ -516,25 +519,27 @@ func (g *GithubDownloaderV3) getComments(issueContext base.IssueContext) ([]*bas for _, comment := range comments { // get reactions var reactions []*base.Reaction - for i := 1; ; i++ { - g.waitAndPickClient() - res, resp, err := g.getClient().Reactions.ListIssueCommentReactions(g.ctx, g.repoOwner, g.repoName, comment.GetID(), &github.ListOptions{ - Page: i, - PerPage: g.maxPerPage, - }) - if err != nil { - return nil, err - } - g.setRate(&resp.Rate) - if len(res) == 0 { - break - } - for _, reaction := range res { - reactions = append(reactions, &base.Reaction{ - UserID: reaction.User.GetID(), - UserName: reaction.User.GetLogin(), - Content: reaction.GetContent(), + if !g.SkipReactions { + for i := 1; ; i++ { + g.waitAndPickClient() + res, resp, err := g.getClient().Reactions.ListIssueCommentReactions(g.ctx, g.repoOwner, g.repoName, comment.GetID(), &github.ListOptions{ + Page: i, + PerPage: g.maxPerPage, }) + if err != nil { + return nil, err + } + g.setRate(&resp.Rate) + if len(res) == 0 { + break + } + for _, reaction := range res { + reactions = append(reactions, &base.Reaction{ + UserID: reaction.User.GetID(), + UserName: reaction.User.GetLogin(), + Content: reaction.GetContent(), + }) + } } } @@ -588,25 +593,27 @@ func (g *GithubDownloaderV3) GetAllComments(page, perPage int) ([]*base.Comment, for _, comment := range comments { // get reactions var reactions []*base.Reaction - for i := 1; ; i++ { - g.waitAndPickClient() - res, resp, err := g.getClient().Reactions.ListIssueCommentReactions(g.ctx, g.repoOwner, g.repoName, comment.GetID(), &github.ListOptions{ - Page: i, - PerPage: g.maxPerPage, - }) - if err != nil { - return nil, false, err - } - g.setRate(&resp.Rate) - if len(res) == 0 { - break - } - for _, reaction := range res { - reactions = append(reactions, &base.Reaction{ - UserID: reaction.User.GetID(), - UserName: reaction.User.GetLogin(), - Content: reaction.GetContent(), + if !g.SkipReactions { + for i := 1; ; i++ { + g.waitAndPickClient() + res, resp, err := g.getClient().Reactions.ListIssueCommentReactions(g.ctx, g.repoOwner, g.repoName, comment.GetID(), &github.ListOptions{ + Page: i, + PerPage: g.maxPerPage, }) + if err != nil { + return nil, false, err + } + g.setRate(&resp.Rate) + if len(res) == 0 { + break + } + for _, reaction := range res { + reactions = append(reactions, &base.Reaction{ + UserID: reaction.User.GetID(), + UserName: reaction.User.GetLogin(), + Content: reaction.GetContent(), + }) + } } } idx := strings.LastIndex(*comment.IssueURL, "/") @@ -656,25 +663,27 @@ func (g *GithubDownloaderV3) GetPullRequests(page, perPage int) ([]*base.PullReq // get reactions var reactions []*base.Reaction - for i := 1; ; i++ { - g.waitAndPickClient() - res, resp, err := g.getClient().Reactions.ListIssueReactions(g.ctx, g.repoOwner, g.repoName, pr.GetNumber(), &github.ListOptions{ - Page: i, - PerPage: perPage, - }) - if err != nil { - return nil, false, err - } - g.setRate(&resp.Rate) - if len(res) == 0 { - break - } - for _, reaction := range res { - reactions = append(reactions, &base.Reaction{ - UserID: reaction.User.GetID(), - UserName: reaction.User.GetLogin(), - Content: reaction.GetContent(), + if !g.SkipReactions { + for i := 1; ; i++ { + g.waitAndPickClient() + res, resp, err := g.getClient().Reactions.ListIssueReactions(g.ctx, g.repoOwner, g.repoName, pr.GetNumber(), &github.ListOptions{ + Page: i, + PerPage: perPage, }) + if err != nil { + return nil, false, err + } + g.setRate(&resp.Rate) + if len(res) == 0 { + break + } + for _, reaction := range res { + reactions = append(reactions, &base.Reaction{ + UserID: reaction.User.GetID(), + UserName: reaction.User.GetLogin(), + Content: reaction.GetContent(), + }) + } } } @@ -737,25 +746,27 @@ func (g *GithubDownloaderV3) convertGithubReviewComments(cs []*github.PullReques for _, c := range cs { // get reactions var reactions []*base.Reaction - for i := 1; ; i++ { - g.waitAndPickClient() - res, resp, err := g.getClient().Reactions.ListPullRequestCommentReactions(g.ctx, g.repoOwner, g.repoName, c.GetID(), &github.ListOptions{ - Page: i, - PerPage: g.maxPerPage, - }) - if err != nil { - return nil, err - } - g.setRate(&resp.Rate) - if len(res) == 0 { - break - } - for _, reaction := range res { - reactions = append(reactions, &base.Reaction{ - UserID: reaction.User.GetID(), - UserName: reaction.User.GetLogin(), - Content: reaction.GetContent(), + if !g.SkipReactions { + for i := 1; ; i++ { + g.waitAndPickClient() + res, resp, err := g.getClient().Reactions.ListPullRequestCommentReactions(g.ctx, g.repoOwner, g.repoName, c.GetID(), &github.ListOptions{ + Page: i, + PerPage: g.maxPerPage, }) + if err != nil { + return nil, err + } + g.setRate(&resp.Rate) + if len(res) == 0 { + break + } + for _, reaction := range res { + reactions = append(reactions, &base.Reaction{ + UserID: reaction.User.GetID(), + UserName: reaction.User.GetLogin(), + Content: reaction.GetContent(), + }) + } } } diff --git a/modules/structs/repo.go b/modules/structs/repo.go index 313a982f43d6..8482a2128d7f 100644 --- a/modules/structs/repo.go +++ b/modules/structs/repo.go @@ -242,13 +242,14 @@ type GitServiceType int // enumerate all GitServiceType const ( - NotMigrated GitServiceType = iota // 0 not migrated from external sites - PlainGitService // 1 plain git service - GithubService // 2 github.com - GiteaService // 3 gitea service - GitlabService // 4 gitlab service - GogsService // 5 gogs service - OneDevService // 6 onedev service + NotMigrated GitServiceType = iota // 0 not migrated from external sites + PlainGitService // 1 plain git service + GithubService // 2 github.com + GiteaService // 3 gitea service + GitlabService // 4 gitlab service + GogsService // 5 gogs service + OneDevService // 6 onedev service + GitBucketService // 7 gitbucket service ) // Name represents the service type's name @@ -270,6 +271,8 @@ func (gt GitServiceType) Title() string { return "Gogs" case OneDevService: return "OneDev" + case GitBucketService: + return "GitBucket" case PlainGitService: return "Git" } @@ -326,5 +329,6 @@ var ( GiteaService, GogsService, OneDevService, + GitBucketService, } ) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 6fad20c87ed0..7d6c878ad6c2 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -911,6 +911,7 @@ migrate.gitlab.description = Migrate data from gitlab.com or other GitLab instan migrate.gitea.description = Migrate data from gitea.com or other Gitea instances. migrate.gogs.description = Migrate data from notabug.org or other Gogs instances. migrate.onedev.description = Migrate data from code.onedev.io or other OneDev instances. +migrate.gitbucket.description = Migrating data from GitBucket instances. migrate.migrating_git = Migrating Git Data migrate.migrating_topics = Migrating Topics migrate.migrating_milestones = Migrating Milestones diff --git a/public/img/svg/gitea-gitbucket.svg b/public/img/svg/gitea-gitbucket.svg new file mode 100644 index 000000000000..50ddd44e1b7c --- /dev/null +++ b/public/img/svg/gitea-gitbucket.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/templates/repo/migrate/gitbucket.tmpl b/templates/repo/migrate/gitbucket.tmpl new file mode 100644 index 000000000000..b554a3a75606 --- /dev/null +++ b/templates/repo/migrate/gitbucket.tmpl @@ -0,0 +1,129 @@ +{{template "base/head" .}} +
+
+
+
+ {{.CsrfTokenHtml}} +

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

+
+ {{template "base/alert" .}} +
+ + + + {{.i18n.Tr "repo.migrate.clone_address_desc"}}{{if .ContextUser.CanImportLocal}} {{.i18n.Tr "repo.migrate.clone_local_path"}}{{end}} + +
+ +
+ + +
+ +
+ + +
+ + {{template "repo/migrate/options" .}} + + {{.i18n.Tr "repo.migrate.migrate_items_options"}} +
+
+ +
+ + +
+
+ + +
+
+
+ +
+ + +
+
+ + +
+
+
+ +
+ + +
+
+ + +
+
+
+ +
+ +
+ + +
+ +
+ + +
+
+ +
+ {{if .IsForcedPrivate}} + + + {{else}} + + + {{end}} +
+
+
+ + +
+ +
+ + + {{.i18n.Tr "cancel"}} +
+
+ +
+
+
+{{template "base/footer" .}} diff --git a/web_src/svg/gitea-gitbucket.svg b/web_src/svg/gitea-gitbucket.svg new file mode 100644 index 000000000000..24da15496843 --- /dev/null +++ b/web_src/svg/gitea-gitbucket.svg @@ -0,0 +1,39 @@ + + + + +Created by potrace 1.14, written by Peter Selinger 2001-2017 + + + + + + + + + + \ No newline at end of file From cd32b84811851992dd8fbb30ba1ac94cfbbcf317 Mon Sep 17 00:00:00 2001 From: silverwind Date: Sun, 14 Nov 2021 22:48:26 +0100 Subject: [PATCH 09/24] Add icon to vscode clone link (#17641) --- public/img/svg/gitea-vscode.svg | 1 + templates/repo/home.tmpl | 10 ++++------ web_src/svg/gitea-vscode.svg | 1 + 3 files changed, 6 insertions(+), 6 deletions(-) create mode 100644 public/img/svg/gitea-vscode.svg create mode 100644 web_src/svg/gitea-vscode.svg diff --git a/public/img/svg/gitea-vscode.svg b/public/img/svg/gitea-vscode.svg new file mode 100644 index 000000000000..4ef94dec3b63 --- /dev/null +++ b/public/img/svg/gitea-vscode.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/templates/repo/home.tmpl b/templates/repo/home.tmpl index 0c377251fa3f..eb6ee8c0a29b 100644 --- a/templates/repo/home.tmpl +++ b/templates/repo/home.tmpl @@ -113,12 +113,10 @@ diff --git a/web_src/svg/gitea-vscode.svg b/web_src/svg/gitea-vscode.svg new file mode 100644 index 000000000000..62cd1a3b7388 --- /dev/null +++ b/web_src/svg/gitea-vscode.svg @@ -0,0 +1 @@ + \ No newline at end of file From 83a04e42cc9d70dd48bfa590869b0ef379fc5a74 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BC=98=E7=94=9F?= Date: Mon, 15 Nov 2021 06:32:48 +0800 Subject: [PATCH 10/24] fix typo (#17614) --- docs/content/doc/installation/with-docker-rootless.en-us.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/content/doc/installation/with-docker-rootless.en-us.md b/docs/content/doc/installation/with-docker-rootless.en-us.md index 12aad592c823..896ef5aebbbc 100644 --- a/docs/content/doc/installation/with-docker-rootless.en-us.md +++ b/docs/content/doc/installation/with-docker-rootless.en-us.md @@ -168,7 +168,9 @@ named volumes; Docker will deal with that automatically. version: "2" +volumes: -+ gitea: ++ gitea-data: ++ driver: local ++ gitea-config: + driver: local + services: From 10db864c66a5c7f8829887a28299864a7da22122 Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Mon, 15 Nov 2021 00:24:54 +0000 Subject: [PATCH 11/24] [skip ci] Updated translations via Crowdin --- options/locale/locale_ja-JP.ini | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/options/locale/locale_ja-JP.ini b/options/locale/locale_ja-JP.ini index a87efcecc717..c0bb04b56233 100644 --- a/options/locale/locale_ja-JP.ini +++ b/options/locale/locale_ja-JP.ini @@ -149,6 +149,8 @@ lfs_path=Git LFSルートパス lfs_path_helper=Git LFSで管理するファイルが、このディレクトリに保存されます。 空欄にするとGit LFSを無効にします。 run_user=実行ユーザー名 run_user_helper=Giteaを実行するユーザーを、オペレーティングシステムのユーザー名で入力します。 このユーザーはリポジトリルートパスへのアクセス権を持っている必要があります。 +domain=サーバードメイン +domain_helper=サーバーのドメインまたはホストアドレス。 ssh_port=SSHサーバーのポート ssh_port_helper=SSHサーバーが使うポート番号。 空の場合はSSHサーバーを無効にします。 http_port=Gitea HTTPポート @@ -2544,6 +2546,7 @@ config.app_ver=Giteaのバージョン config.app_url=GiteaのベースURL config.custom_conf=設定ファイルのパス config.custom_file_root_path=カスタムファイルのルートパス +config.domain=サーバードメイン config.offline_mode=ローカルモード config.disable_router_log=ルーターのログが無効 config.run_user=実行ユーザー名 @@ -2559,6 +2562,7 @@ config.reverse_auth_user=リバース認証ユーザー config.ssh_config=SSH設定 config.ssh_enabled=有効 config.ssh_start_builtin_server=ビルトインサーバーを使用 +config.ssh_domain=SSHサーバーのドメイン config.ssh_port=ポート config.ssh_listen_port=待受ポート config.ssh_root_path=ルートパス From 562785ef4ea8ea4b24da726a4fbf515358ee7084 Mon Sep 17 00:00:00 2001 From: Gusted Date: Mon, 15 Nov 2021 01:05:12 +0000 Subject: [PATCH 12/24] Add download button for file viewer (#17640) - Resolves #17286 - Use the `download` attribute such that the browser will natively initate a download dialog for the given URL. Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: techknowlogick --- options/locale/locale_en-US.ini | 1 + templates/repo/view_file.tmpl | 1 + 2 files changed, 2 insertions(+) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 7d6c878ad6c2..2069b2053014 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -989,6 +989,7 @@ commit_graph.hide_pr_refs = Hide Pull Requests commit_graph.monochrome = Mono commit_graph.color = Color blame = Blame +download_file = Download file normal_view = Normal View line = line lines = lines diff --git a/templates/repo/view_file.tmpl b/templates/repo/view_file.tmpl index 0c8990a4f5c8..2c678beb9073 100644 --- a/templates/repo/view_file.tmpl +++ b/templates/repo/view_file.tmpl @@ -48,6 +48,7 @@ {{end}} {{.i18n.Tr "repo.file_history"}} + {{svg "octicon-download"}} {{if .Repository.CanEnableEditor}} {{if .CanEditFile}} {{svg "octicon-pencil"}} From 253d9e415813e90543cca8d94112c9e4238d39a4 Mon Sep 17 00:00:00 2001 From: Gusted Date: Mon, 15 Nov 2021 06:02:53 +0000 Subject: [PATCH 13/24] Remove unnecassary calls to `filepath.Join` (#17608) - Partialy resolvess #17596 - Resolves `badCall` errors from go-critic `badCall: suspicious Join on 1 argument` - When only 1 argument is passed into `filepath.Join`, it won't do anything special other than `filepath.Clean(...)` will be applied over it. Co-authored-by: Lunny Xiao Co-authored-by: 6543 <6543@obermui.de> --- modules/repository/adopt.go | 2 +- routers/web/user/setting/adopt.go | 2 +- routers/web/user/setting/profile.go | 2 +- services/pull/merge.go | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/repository/adopt.go b/modules/repository/adopt.go index 21477ab7d771..3d895ac4843c 100644 --- a/modules/repository/adopt.go +++ b/modules/repository/adopt.go @@ -154,7 +154,7 @@ func ListUnadoptedRepositories(query string, opts *db.ListOptions) ([]string, in count := 0 // We're going to iterate by pagesize. - root := filepath.Join(setting.RepoRootPath) + root := filepath.Clean(setting.RepoRootPath) if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { return err diff --git a/routers/web/user/setting/adopt.go b/routers/web/user/setting/adopt.go index e45a8a132465..2caccb69a501 100644 --- a/routers/web/user/setting/adopt.go +++ b/routers/web/user/setting/adopt.go @@ -27,7 +27,7 @@ func AdoptOrDeleteRepository(ctx *context.Context) { action := ctx.FormString("action") ctxUser := ctx.User - root := filepath.Join(models.UserPath(ctxUser.LowerName)) + root := models.UserPath(ctxUser.LowerName) // check not a repo has, err := models.IsRepositoryExist(ctxUser, dir) diff --git a/routers/web/user/setting/profile.go b/routers/web/user/setting/profile.go index 4a0900615099..d7aa3264c58a 100644 --- a/routers/web/user/setting/profile.go +++ b/routers/web/user/setting/profile.go @@ -250,7 +250,7 @@ func Repos(ctx *context.Context) { repoNames := make([]string, 0, setting.UI.Admin.UserPagingNum) repos := map[string]*models.Repository{} // We're going to iterate by pagesize. - root := filepath.Join(models.UserPath(ctxUser.Name)) + root := models.UserPath(ctxUser.Name) if err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error { if err != nil { if os.IsNotExist(err) { diff --git a/services/pull/merge.go b/services/pull/merge.go index f59931e1bfd3..e4ed4e38bd9c 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -275,8 +275,8 @@ func rawMerge(pr *models.PullRequest, doer *models.User, mergeStyle models.Merge filepath.Join(tmpBasePath, ".git", "rebase-merge", "stopped-sha"), // Git >= 2.26 } for _, failingCommitPath := range failingCommitPaths { - if _, statErr := os.Stat(filepath.Join(failingCommitPath)); statErr == nil { - commitShaBytes, readErr := os.ReadFile(filepath.Join(failingCommitPath)) + if _, statErr := os.Stat(failingCommitPath); statErr == nil { + commitShaBytes, readErr := os.ReadFile(failingCommitPath) if readErr != nil { // Abandon this attempt to handle the error log.Error("git rebase staging on to base [%s:%s -> %s:%s]: %v\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String()) From ab1379743e812eb1430e4d15a00c3f7b9e759da6 Mon Sep 17 00:00:00 2001 From: Gusted Date: Mon, 15 Nov 2021 13:16:11 +0000 Subject: [PATCH 14/24] Fix nil checking on typed interface (#17598) * Fix nil checking on typed interface - Partially resoles #17596 - Resolves SA4023 errors. - Ensure correctly that typed interface are nil. * Remove unnecessary code `NewBleveIndexer` will never return nil, even on errors. * Patch `NewBleveIndexer` * Fix low-level functions * Remove deadcode * Fix GetSession * Close Elastic search when err isn't nil * Update elastic_search.go Co-authored-by: Lunny Xiao Co-authored-by: wxiaoguang --- modules/indexer/code/bleve.go | 4 ++++ modules/indexer/code/elastic_search.go | 5 ++++- modules/indexer/code/indexer.go | 6 ------ routers/web/base.go | 8 -------- 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/modules/indexer/code/bleve.go b/modules/indexer/code/bleve.go index 8e5df34e60be..66b2602d3bf2 100644 --- a/modules/indexer/code/bleve.go +++ b/modules/indexer/code/bleve.go @@ -173,6 +173,10 @@ func NewBleveIndexer(indexDir string) (*BleveIndexer, bool, error) { indexDir: indexDir, } created, err := indexer.init() + if err != nil { + indexer.Close() + return nil, false, err + } return indexer, created, err } diff --git a/modules/indexer/code/elastic_search.go b/modules/indexer/code/elastic_search.go index 49633c31916d..f76f316f6494 100644 --- a/modules/indexer/code/elastic_search.go +++ b/modules/indexer/code/elastic_search.go @@ -82,7 +82,10 @@ func NewElasticSearchIndexer(url, indexerName string) (*ElasticSearchIndexer, bo indexerAliasName: indexerName, } exists, err := indexer.init() - + if err != nil { + indexer.Close() + return nil, false, err + } return indexer, !exists, err } diff --git a/modules/indexer/code/indexer.go b/modules/indexer/code/indexer.go index 981167a8254a..c56b1b2bb0c5 100644 --- a/modules/indexer/code/indexer.go +++ b/modules/indexer/code/indexer.go @@ -185,9 +185,6 @@ func Init() { rIndexer, populate, err = NewBleveIndexer(setting.Indexer.RepoPath) if err != nil { - if rIndexer != nil { - rIndexer.Close() - } cancel() indexer.Close() close(waitChannel) @@ -205,9 +202,6 @@ func Init() { rIndexer, populate, err = NewElasticSearchIndexer(setting.Indexer.RepoConnStr, setting.Indexer.RepoIndexerName) if err != nil { - if rIndexer != nil { - rIndexer.Close() - } cancel() indexer.Close() close(waitChannel) diff --git a/routers/web/base.go b/routers/web/base.go index 16d3192da21d..98713bc8818f 100644 --- a/routers/web/base.go +++ b/routers/web/base.go @@ -130,14 +130,6 @@ func Recovery() func(next http.Handler) http.Handler { log.Error("%v", combinedErr) sessionStore := session.GetSession(req) - if sessionStore == nil { - if setting.IsProd { - http.Error(w, http.StatusText(500), 500) - } else { - http.Error(w, combinedErr, 500) - } - return - } var lc = middleware.Locale(w, req) var store = dataStore{ From ff9564a6798897007ad6d040ebdf0f667188200b Mon Sep 17 00:00:00 2001 From: KN4CK3R Date: Tue, 16 Nov 2021 00:12:09 +0100 Subject: [PATCH 15/24] Changed migration text. (#17654) --- options/locale/locale_en-US.ini | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/options/locale/locale_en-US.ini b/options/locale/locale_en-US.ini index 2069b2053014..78efb3d3ff11 100644 --- a/options/locale/locale_en-US.ini +++ b/options/locale/locale_en-US.ini @@ -911,7 +911,7 @@ migrate.gitlab.description = Migrate data from gitlab.com or other GitLab instan migrate.gitea.description = Migrate data from gitea.com or other Gitea instances. migrate.gogs.description = Migrate data from notabug.org or other Gogs instances. migrate.onedev.description = Migrate data from code.onedev.io or other OneDev instances. -migrate.gitbucket.description = Migrating data from GitBucket instances. +migrate.gitbucket.description = Migrate data from GitBucket instances. migrate.migrating_git = Migrating Git Data migrate.migrating_topics = Migrating Topics migrate.migrating_milestones = Migrating Milestones From 3a60e0ad8969b2e248a2f78e0ce02d2645d80dfa Mon Sep 17 00:00:00 2001 From: GiteaBot Date: Tue, 16 Nov 2021 00:25:21 +0000 Subject: [PATCH 16/24] [skip ci] Updated translations via Crowdin --- options/locale/locale_fi-FI.ini | 1 - options/locale/locale_zh-TW.ini | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/options/locale/locale_fi-FI.ini b/options/locale/locale_fi-FI.ini index a44d99a9bf21..4065b4acf7b0 100644 --- a/options/locale/locale_fi-FI.ini +++ b/options/locale/locale_fi-FI.ini @@ -494,7 +494,6 @@ delete_prompt=Tämä toiminto poistaa käyttäjätilisi pysyvästi. Toimintoa %s 遷移... migrate.migrating_failed=從 %s 遷移失敗 migrate.migrating_failed.error=錯誤:%s +migrate.migrating_failed_no_addr=遷移失敗。 migrate.github.description=從 github.com 或其他 Github 實例遷移資料。 migrate.git.description=從任何 Git 服務遷移儲存庫。 migrate.gitlab.description=從 gitlab.com 或其他 GitLab 實例遷移資料。 migrate.gitea.description=從 gitea.com 或其他 Gitea 實例遷移資料。 migrate.gogs.description=從 notabug.org 或其他 Gogs 實例遷移資料。 migrate.onedev.description=從 code.onedev.io 或其他 OneDev 實例遷移資料。 +migrate.gitbucket.description=從 GitBucket 實例遷移資料。 migrate.migrating_git=正在遷移 Git 資料 migrate.migrating_topics=正在遷移主題 migrate.migrating_milestones=正在遷移里程碑 From 62926032155eef30bd380a27601fe770eb00e855 Mon Sep 17 00:00:00 2001 From: wxiaoguang Date: Tue, 16 Nov 2021 10:21:13 +0800 Subject: [PATCH 17/24] Fix database deadlock when update issue labels (#17649) This fix updates issue labels one by one, and won't cause database deadlock. In future, we can use a batch API to update all changed labels by one request. --- web_src/js/features/repo-issue.js | 24 ++++++++++-------------- web_src/js/features/repo-legacy.js | 24 ++++++++++++------------ 2 files changed, 22 insertions(+), 26 deletions(-) diff --git a/web_src/js/features/repo-issue.js b/web_src/js/features/repo-issue.js index 782957c5b16c..b69ba2571978 100644 --- a/web_src/js/features/repo-issue.js +++ b/web_src/js/features/repo-issue.js @@ -332,20 +332,16 @@ export function initRepoIssueWipTitle() { }); } -export function updateIssuesMeta(url, action, issueIds, elementId) { - return new Promise((resolve, reject) => { - $.ajax({ - type: 'POST', - url, - data: { - _csrf: csrfToken, - action, - issue_ids: issueIds, - id: elementId, - }, - success: resolve, - error: reject, - }); +export async function updateIssuesMeta(url, action, issueIds, elementId) { + return $.ajax({ + type: 'POST', + url, + data: { + _csrf: csrfToken, + action, + issue_ids: issueIds, + id: elementId, + }, }); } diff --git a/web_src/js/features/repo-legacy.js b/web_src/js/features/repo-legacy.js index 8945360cd580..74880c5dc774 100644 --- a/web_src/js/features/repo-legacy.js +++ b/web_src/js/features/repo-legacy.js @@ -84,18 +84,18 @@ export function initRepoCommentForm() { $(`.${selector}`).dropdown('setting', 'onHide', () => { hasUpdateAction = $listMenu.data('action') === 'update'; // Update the var if (hasUpdateAction) { - const promises = []; - Object.keys(items).forEach((elementId) => { - const item = items[elementId]; - const promise = updateIssuesMeta( - item['update-url'], - item.action, - item['issue-id'], - elementId, - ); - promises.push(promise); - }); - Promise.all(promises).then(() => window.location.reload()); + // TODO: Add batch functionality and make this 1 network request. + (async function() { + for (const [elementId, item] of Object.entries(items)) { + await updateIssuesMeta( + item['update-url'], + item.action, + item['issue-id'], + elementId, + ); + } + window.location.reload(); + })(); } }); From 6f7082ff563d06e4b2ff3e11c32f160028c98975 Mon Sep 17 00:00:00 2001 From: silverwind Date: Tue, 16 Nov 2021 05:24:22 +0100 Subject: [PATCH 18/24] Fix GitBucket icon (#17644) Partial fix for https://github.com/go-gitea/gitea/issues/17642. Co-authored-by: wxiaoguang --- public/img/svg/gitea-gitbucket.svg | 2 +- web_src/svg/gitea-gitbucket.svg | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/public/img/svg/gitea-gitbucket.svg b/public/img/svg/gitea-gitbucket.svg index 50ddd44e1b7c..3d07adebdd00 100644 --- a/public/img/svg/gitea-gitbucket.svg +++ b/public/img/svg/gitea-gitbucket.svg @@ -1 +1 @@ - \ No newline at end of file + \ No newline at end of file diff --git a/web_src/svg/gitea-gitbucket.svg b/web_src/svg/gitea-gitbucket.svg index 24da15496843..a960d6dfaf6f 100644 --- a/web_src/svg/gitea-gitbucket.svg +++ b/web_src/svg/gitea-gitbucket.svg @@ -8,7 +8,7 @@ Created by potrace 1.14, written by Peter Selinger 2001-2017 +stroke="none"> {{.i18n.Tr "username"}} -
@@ -30,19 +29,16 @@ {{template "repo/migrate/options" .}} - {{.i18n.Tr "repo.migrate.migrate_items_options"}} -
-
- -
- - -
-
- - -
+
+ +
+ +
+
+ +
+ {{.i18n.Tr "repo.migrate.migrate_items_options"}}
@@ -65,6 +61,13 @@
+
+ +
+ + +
+
diff --git a/templates/repo/migrate/gitea.tmpl b/templates/repo/migrate/gitea.tmpl index 901524d11227..d0532923e130 100644 --- a/templates/repo/migrate/gitea.tmpl +++ b/templates/repo/migrate/gitea.tmpl @@ -26,19 +26,16 @@ {{template "repo/migrate/options" .}} - {{.i18n.Tr "repo.migrate.migrate_items_options"}} -
-
- -
- - -
-
- - -
+
+ +
+ +
+
+ +
+ {{.i18n.Tr "repo.migrate.migrate_items_options"}}
@@ -61,6 +58,13 @@
+
+ +
+ + +
+
diff --git a/templates/repo/migrate/github.tmpl b/templates/repo/migrate/github.tmpl index 9bd7228a43b4..1dfd164c8553 100644 --- a/templates/repo/migrate/github.tmpl +++ b/templates/repo/migrate/github.tmpl @@ -29,19 +29,15 @@ {{template "repo/migrate/options" .}} - {{.i18n.Tr "repo.migrate.migrate_items_options"}} -
-
- -
- - -
-
- - -
+
+ +
+ +
+
+
+ {{.i18n.Tr "repo.migrate.migrate_items_options"}}
@@ -64,6 +60,13 @@
+
+ +
+ + +
+
diff --git a/templates/repo/migrate/gitlab.tmpl b/templates/repo/migrate/gitlab.tmpl index e1424c250fb0..b730164a8ff0 100644 --- a/templates/repo/migrate/gitlab.tmpl +++ b/templates/repo/migrate/gitlab.tmpl @@ -26,19 +26,15 @@ {{template "repo/migrate/options" .}} - {{.i18n.Tr "repo.migrate.migrate_items_options"}} -
-
- -
- - -
-
- - -
+
+ +
+ +
+
+
+ {{.i18n.Tr "repo.migrate.migrate_items_options"}}
@@ -61,6 +57,13 @@
+
+ +
+ + +
+
diff --git a/templates/repo/migrate/gogs.tmpl b/templates/repo/migrate/gogs.tmpl index b1900e83d101..c35ef017b335 100644 --- a/templates/repo/migrate/gogs.tmpl +++ b/templates/repo/migrate/gogs.tmpl @@ -26,19 +26,16 @@ {{template "repo/migrate/options" .}} - {{.i18n.Tr "repo.migrate.migrate_items_options"}} -
-
- -
- - -
-
- - -
+
+ +
+ +
+
+ +
+ {{.i18n.Tr "repo.migrate.migrate_items_options"}}
@@ -50,6 +47,13 @@
+
+ +
+ + +
+
{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{if $line.LeftIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{if $line.LeftIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}} {{if $match.RightIdx}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{if $match.RightIdx}}{{$section.GetComputedInlineDiffFor $match}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{if $match.RightIdx}}{{$section.GetComputedInlineDiffFor $match}}{{end}} {{if $line.LeftIdx}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles (not (eq .GetType 2))}}{{svg "octicon-plus"}}{{end}}{{if $line.LeftIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles (not (eq .GetType 2))}}{{svg "octicon-plus"}}{{end}}{{if $line.LeftIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}} {{if $line.RightIdx}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles (not (eq .GetType 3))}}{{svg "octicon-plus"}}{{end}}{{if $line.RightIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}}{{if and $.root.SignedUserID $.root.PageIsPullFiles (not (eq .GetType 3))}}{{svg "octicon-plus"}}{{end}}{{if $line.RightIdx}}{{$section.GetComputedInlineDiffFor $line}}{{end}}
{{$section.GetComputedInlineDiffFor $line}}{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{$section.GetComputedInlineDiffFor $line}}{{if and $.root.SignedUserID $.root.PageIsPullFiles}}{{svg "octicon-plus"}}{{end}}{{$section.GetComputedInlineDiffFor $line}}