diff options
Diffstat (limited to 'models')
112 files changed, 1706 insertions, 1609 deletions
diff --git a/models/actions/forgejo_test.go b/models/actions/forgejo_test.go index 8d4145b53e..9295fc698e 100644 --- a/models/actions/forgejo_test.go +++ b/models/actions/forgejo_test.go @@ -15,7 +15,7 @@ import ( ) func TestActions_RegisterRunner_Token(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ownerID := int64(0) repoID := int64(0) token := "0123456789012345678901234567890123456789" @@ -23,7 +23,7 @@ func TestActions_RegisterRunner_Token(t *testing.T) { name := "runner" version := "v1.2.3" runner, err := RegisterRunner(db.DefaultContext, ownerID, repoID, token, &labels, name, version) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, name, runner.Name) assert.EqualValues(t, 1, subtle.ConstantTimeCompare([]byte(runner.TokenHash), []byte(auth_model.HashToken(token, runner.TokenSalt))), "the token cannot be verified with the same method as routers/api/actions/runner/interceptor.go as of 8228751c55d6a4263f0fec2932ca16181c09c97d") @@ -37,7 +37,7 @@ func TestActions_RegisterRunner_TokenUpdate(t *testing.T) { const recordID = 12345678 oldToken := "7e577e577e577e57feedfacefeedfacefeedface" newToken := "7e577e577e577e57deadbeefdeadbeefdeadbeef" - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) before := unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID}) require.Equal(t, before.TokenHash, auth_model.HashToken(oldToken, before.TokenSalt), @@ -60,7 +60,7 @@ func TestActions_RegisterRunner_TokenUpdate(t *testing.T) { } func TestActions_RegisterRunner_CreateWithLabels(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ownerID := int64(0) repoID := int64(0) token := "0123456789012345678901234567890123456789" @@ -70,7 +70,7 @@ func TestActions_RegisterRunner_CreateWithLabels(t *testing.T) { labelsCopy := labels // labels may be affected by the tested function so we copy them runner, err := RegisterRunner(db.DefaultContext, ownerID, repoID, token, &labels, name, version) - assert.NoError(t, err) + require.NoError(t, err) // Check that the returned record has been updated, except for the labels assert.EqualValues(t, ownerID, runner.OwnerID) @@ -89,7 +89,7 @@ func TestActions_RegisterRunner_CreateWithLabels(t *testing.T) { } func TestActions_RegisterRunner_CreateWithoutLabels(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ownerID := int64(0) repoID := int64(0) token := "0123456789012345678901234567890123456789" @@ -97,7 +97,7 @@ func TestActions_RegisterRunner_CreateWithoutLabels(t *testing.T) { version := "v1.2.3" runner, err := RegisterRunner(db.DefaultContext, ownerID, repoID, token, nil, name, version) - assert.NoError(t, err) + require.NoError(t, err) // Check that the returned record has been updated, except for the labels assert.EqualValues(t, ownerID, runner.OwnerID) @@ -118,7 +118,7 @@ func TestActions_RegisterRunner_CreateWithoutLabels(t *testing.T) { func TestActions_RegisterRunner_UpdateWithLabels(t *testing.T) { const recordID = 12345678 token := "7e577e577e577e57feedfacefeedfacefeedface" - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID}) newOwnerID := int64(1) @@ -129,7 +129,7 @@ func TestActions_RegisterRunner_UpdateWithLabels(t *testing.T) { labelsCopy := newLabels // labels may be affected by the tested function so we copy them runner, err := RegisterRunner(db.DefaultContext, newOwnerID, newRepoID, token, &newLabels, newName, newVersion) - assert.NoError(t, err) + require.NoError(t, err) // Check that the returned record has been updated assert.EqualValues(t, newOwnerID, runner.OwnerID) @@ -150,7 +150,7 @@ func TestActions_RegisterRunner_UpdateWithLabels(t *testing.T) { func TestActions_RegisterRunner_UpdateWithoutLabels(t *testing.T) { const recordID = 12345678 token := "7e577e577e577e57feedfacefeedfacefeedface" - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) before := unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID}) newOwnerID := int64(1) @@ -159,7 +159,7 @@ func TestActions_RegisterRunner_UpdateWithoutLabels(t *testing.T) { newVersion := "v4.5.6" runner, err := RegisterRunner(db.DefaultContext, newOwnerID, newRepoID, token, nil, newName, newVersion) - assert.NoError(t, err) + require.NoError(t, err) // Check that the returned record has been updated, except for the labels assert.EqualValues(t, newOwnerID, runner.OwnerID) diff --git a/models/actions/runner_test.go b/models/actions/runner_test.go index 311a6eb0b4..26ef4c44c6 100644 --- a/models/actions/runner_test.go +++ b/models/actions/runner_test.go @@ -31,15 +31,15 @@ func TestUpdateSecret(t *testing.T) { func TestDeleteRunner(t *testing.T) { const recordID = 12345678 - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) before := unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID}) err := DeleteRunner(db.DefaultContext, recordID) - assert.NoError(t, err) + require.NoError(t, err) var after ActionRunner found, err := db.GetEngine(db.DefaultContext).ID(recordID).Unscoped().Get(&after) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, found) // Most fields (namely Name, Version, OwnerID, RepoID, Description, Base, RepoRange, diff --git a/models/actions/runner_token_test.go b/models/actions/runner_token_test.go index e85e99abe5..35c9a9d3c3 100644 --- a/models/actions/runner_token_test.go +++ b/models/actions/runner_token_test.go @@ -10,31 +10,32 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetLatestRunnerToken(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) token := unittest.AssertExistsAndLoadBean(t, &ActionRunnerToken{ID: 3}) expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0) - assert.NoError(t, err) - assert.EqualValues(t, token, expectedToken) + require.NoError(t, err) + assert.EqualValues(t, expectedToken, token) } func TestNewRunnerToken(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) token, err := NewRunnerToken(db.DefaultContext, 1, 0) - assert.NoError(t, err) + require.NoError(t, err) expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0) - assert.NoError(t, err) - assert.EqualValues(t, token, expectedToken) + require.NoError(t, err) + assert.EqualValues(t, expectedToken, token) } func TestUpdateRunnerToken(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) token := unittest.AssertExistsAndLoadBean(t, &ActionRunnerToken{ID: 3}) token.IsActive = true - assert.NoError(t, UpdateRunnerToken(db.DefaultContext, token)) + require.NoError(t, UpdateRunnerToken(db.DefaultContext, token)) expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0) - assert.NoError(t, err) - assert.EqualValues(t, token, expectedToken) + require.NoError(t, err) + assert.EqualValues(t, expectedToken, token) } diff --git a/models/activities/action_test.go b/models/activities/action_test.go index 5467bd35fb..4ce030dd48 100644 --- a/models/activities/action_test.go +++ b/models/activities/action_test.go @@ -17,10 +17,11 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAction_GetRepoPath(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) action := &activities_model.Action{RepoID: repo.ID} @@ -28,7 +29,7 @@ func TestAction_GetRepoPath(t *testing.T) { } func TestAction_GetRepoLink(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) comment := unittest.AssertExistsAndLoadBean(t, &issue_model.Comment{ID: 2}) @@ -42,7 +43,7 @@ func TestAction_GetRepoLink(t *testing.T) { func TestGetFeeds(t *testing.T) { // test with an individual user - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{ @@ -52,7 +53,7 @@ func TestGetFeeds(t *testing.T) { OnlyPerformedBy: false, IncludeDeleted: true, }) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, actions, 1) { assert.EqualValues(t, 1, actions[0].ID) assert.EqualValues(t, user.ID, actions[0].UserID) @@ -65,13 +66,13 @@ func TestGetFeeds(t *testing.T) { IncludePrivate: false, OnlyPerformedBy: false, }) - assert.NoError(t, err) - assert.Len(t, actions, 0) + require.NoError(t, err) + assert.Empty(t, actions) assert.Equal(t, int64(0), count) } func TestGetFeedsForRepos(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) privRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) pubRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 8}) @@ -81,8 +82,8 @@ func TestGetFeedsForRepos(t *testing.T) { RequestedRepo: privRepo, IncludePrivate: true, }) - assert.NoError(t, err) - assert.Len(t, actions, 0) + require.NoError(t, err) + assert.Empty(t, actions) assert.Equal(t, int64(0), count) // public repo & no login @@ -90,7 +91,7 @@ func TestGetFeedsForRepos(t *testing.T) { RequestedRepo: pubRepo, IncludePrivate: true, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, actions, 1) assert.Equal(t, int64(1), count) @@ -100,7 +101,7 @@ func TestGetFeedsForRepos(t *testing.T) { IncludePrivate: true, Actor: user, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, actions, 1) assert.Equal(t, int64(1), count) @@ -110,14 +111,14 @@ func TestGetFeedsForRepos(t *testing.T) { IncludePrivate: true, Actor: user, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, actions, 1) assert.Equal(t, int64(1), count) } func TestGetFeeds2(t *testing.T) { // test with an organization user - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -128,7 +129,7 @@ func TestGetFeeds2(t *testing.T) { OnlyPerformedBy: false, IncludeDeleted: true, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, actions, 1) if assert.Len(t, actions, 1) { assert.EqualValues(t, 2, actions[0].ID) @@ -143,8 +144,8 @@ func TestGetFeeds2(t *testing.T) { OnlyPerformedBy: false, IncludeDeleted: true, }) - assert.NoError(t, err) - assert.Len(t, actions, 0) + require.NoError(t, err) + assert.Empty(t, actions) assert.Equal(t, int64(0), count) } @@ -189,14 +190,14 @@ func TestActivityReadable(t *testing.T) { } func TestNotifyWatchers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) action := &activities_model.Action{ ActUserID: 8, RepoID: 1, OpType: activities_model.ActionStarRepo, } - assert.NoError(t, activities_model.NotifyWatchers(db.DefaultContext, action)) + require.NoError(t, activities_model.NotifyWatchers(db.DefaultContext, action)) // One watchers are inactive, thus action is only created for user 8, 1, 4, 11 unittest.AssertExistsAndLoadBean(t, &activities_model.Action{ @@ -226,7 +227,7 @@ func TestNotifyWatchers(t *testing.T) { } func TestGetFeedsCorrupted(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) unittest.AssertExistsAndLoadBean(t, &activities_model.Action{ ID: 8, @@ -238,8 +239,8 @@ func TestGetFeedsCorrupted(t *testing.T) { Actor: user, IncludePrivate: true, }) - assert.NoError(t, err) - assert.Len(t, actions, 0) + require.NoError(t, err) + assert.Empty(t, actions) assert.Equal(t, int64(0), count) } @@ -247,47 +248,46 @@ func TestConsistencyUpdateAction(t *testing.T) { if !setting.Database.Type.IsSQLite3() { t.Skip("Test is only for SQLite database.") } - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) id := 8 unittest.AssertExistsAndLoadBean(t, &activities_model.Action{ ID: int64(id), }) _, err := db.GetEngine(db.DefaultContext).Exec(`UPDATE action SET created_unix = "" WHERE id = ?`, id) - assert.NoError(t, err) + require.NoError(t, err) actions := make([]*activities_model.Action, 0, 1) // // XORM returns an error when created_unix is a string // err = db.GetEngine(db.DefaultContext).Where("id = ?", id).Find(&actions) - if assert.Error(t, err) { - assert.Contains(t, err.Error(), "type string to a int64: invalid syntax") - } + require.ErrorContains(t, err, "type string to a int64: invalid syntax") + // // Get rid of incorrectly set created_unix // count, err := activities_model.CountActionCreatedUnixString(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, count) count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, count) count, err = activities_model.CountActionCreatedUnixString(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, count) count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, count) // // XORM must be happy now // - assert.NoError(t, db.GetEngine(db.DefaultContext).Where("id = ?", id).Find(&actions)) + require.NoError(t, db.GetEngine(db.DefaultContext).Where("id = ?", id).Find(&actions)) unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestDeleteIssueActions(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // load an issue issue := unittest.AssertExistsAndLoadBean(t, &issue_model.Issue{ID: 4}) @@ -295,26 +295,26 @@ func TestDeleteIssueActions(t *testing.T) { // insert a comment err := db.Insert(db.DefaultContext, &issue_model.Comment{Type: issue_model.CommentTypeComment, IssueID: issue.ID}) - assert.NoError(t, err) + require.NoError(t, err) comment := unittest.AssertExistsAndLoadBean(t, &issue_model.Comment{Type: issue_model.CommentTypeComment, IssueID: issue.ID}) // truncate action table and insert some actions err = db.TruncateBeans(db.DefaultContext, &activities_model.Action{}) - assert.NoError(t, err) + require.NoError(t, err) err = db.Insert(db.DefaultContext, &activities_model.Action{ OpType: activities_model.ActionCommentIssue, CommentID: comment.ID, }) - assert.NoError(t, err) + require.NoError(t, err) err = db.Insert(db.DefaultContext, &activities_model.Action{ OpType: activities_model.ActionCreateIssue, RepoID: issue.RepoID, Content: fmt.Sprintf("%d|content...", issue.Index), }) - assert.NoError(t, err) + require.NoError(t, err) // assert that the actions exist, then delete them unittest.AssertCount(t, &activities_model.Action{}, 2) - assert.NoError(t, activities_model.DeleteIssueActions(db.DefaultContext, issue.RepoID, issue.ID, issue.Index)) + require.NoError(t, activities_model.DeleteIssueActions(db.DefaultContext, issue.RepoID, issue.ID, issue.Index)) unittest.AssertCount(t, &activities_model.Action{}, 0) } diff --git a/models/activities/notification_test.go b/models/activities/notification_test.go index 52f0eacba1..3ff223d870 100644 --- a/models/activities/notification_test.go +++ b/models/activities/notification_test.go @@ -14,13 +14,14 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCreateOrUpdateIssueNotifications(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) - assert.NoError(t, activities_model.CreateOrUpdateIssueNotifications(db.DefaultContext, issue.ID, 0, 2, 0)) + require.NoError(t, activities_model.CreateOrUpdateIssueNotifications(db.DefaultContext, issue.ID, 0, 2, 0)) // User 9 is inactive, thus notifications for user 1 and 4 are created notf := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{UserID: 1, IssueID: issue.ID}) @@ -32,7 +33,7 @@ func TestCreateOrUpdateIssueNotifications(t *testing.T) { } func TestNotificationsForUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) notfs, err := db.Find[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{ UserID: user.ID, @@ -41,7 +42,7 @@ func TestNotificationsForUser(t *testing.T) { activities_model.NotificationStatusUnread, }, }) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, notfs, 3) { assert.EqualValues(t, 5, notfs[0].ID) assert.EqualValues(t, user.ID, notfs[0].UserID) @@ -53,25 +54,25 @@ func TestNotificationsForUser(t *testing.T) { } func TestNotification_GetRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) notf := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{RepoID: 1}) repo, err := notf.GetRepo(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, repo, notf.Repository) assert.EqualValues(t, notf.RepoID, repo.ID) } func TestNotification_GetIssue(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) notf := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{RepoID: 1}) issue, err := notf.GetIssue(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, issue, notf.Issue) assert.EqualValues(t, notf.IssueID, issue.ID) } func TestGetNotificationCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) cnt, err := db.Count[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{ UserID: user.ID, @@ -79,7 +80,7 @@ func TestGetNotificationCount(t *testing.T) { activities_model.NotificationStatusRead, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, cnt) cnt, err = db.Count[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{ @@ -88,28 +89,28 @@ func TestGetNotificationCount(t *testing.T) { activities_model.NotificationStatusUnread, }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, cnt) } func TestSetNotificationStatus(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) notf := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead}) _, err := activities_model.SetNotificationStatus(db.DefaultContext, notf.ID, user, activities_model.NotificationStatusPinned) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: notf.ID, Status: activities_model.NotificationStatusPinned}) _, err = activities_model.SetNotificationStatus(db.DefaultContext, 1, user, activities_model.NotificationStatusRead) - assert.Error(t, err) + require.Error(t, err) _, err = activities_model.SetNotificationStatus(db.DefaultContext, unittest.NonexistentID, user, activities_model.NotificationStatusRead) - assert.Error(t, err) + require.Error(t, err) } func TestUpdateNotificationStatuses(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) notfUnread := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusUnread}) @@ -117,7 +118,7 @@ func TestUpdateNotificationStatuses(t *testing.T) { &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead}) notfPinned := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusPinned}) - assert.NoError(t, activities_model.UpdateNotificationStatuses(db.DefaultContext, user, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead)) + require.NoError(t, activities_model.UpdateNotificationStatuses(db.DefaultContext, user, activities_model.NotificationStatusUnread, activities_model.NotificationStatusRead)) unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: notfUnread.ID, Status: activities_model.NotificationStatusRead}) unittest.AssertExistsAndLoadBean(t, @@ -127,14 +128,14 @@ func TestUpdateNotificationStatuses(t *testing.T) { } func TestSetIssueReadBy(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) - assert.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error { + require.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error { return activities_model.SetIssueReadBy(ctx, issue.ID, user.ID) })) nt, err := activities_model.GetIssueNotification(db.DefaultContext, user.ID, issue.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, activities_model.NotificationStatusRead, nt.Status) } diff --git a/models/activities/user_heatmap_test.go b/models/activities/user_heatmap_test.go index b7babcbde1..7063da8bd1 100644 --- a/models/activities/user_heatmap_test.go +++ b/models/activities/user_heatmap_test.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetUserHeatmapDataByUser(t *testing.T) { @@ -56,7 +57,7 @@ func TestGetUserHeatmapDataByUser(t *testing.T) { }, } // Prepare - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // Mock time timeutil.MockSet(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)) @@ -67,7 +68,7 @@ func TestGetUserHeatmapDataByUser(t *testing.T) { doer := &user_model.User{ID: tc.doerID} _, err := unittest.LoadBeanIfExists(doer) - assert.NoError(t, err) + require.NoError(t, err) if tc.doerID == 0 { doer = nil } @@ -80,7 +81,7 @@ func TestGetUserHeatmapDataByUser(t *testing.T) { OnlyPerformedBy: true, IncludeDeleted: true, }) - assert.NoError(t, err) + require.NoError(t, err) // Get the heatmap and compare heatmap, err := activities_model.GetUserHeatmapDataByUser(db.DefaultContext, user, doer) @@ -88,14 +89,14 @@ func TestGetUserHeatmapDataByUser(t *testing.T) { for _, hm := range heatmap { contributions += int(hm.Contributions) } - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, actions, contributions, "invalid action count: did the test data became too old?") assert.Equal(t, count, int64(contributions)) assert.Equal(t, tc.CountResult, contributions, fmt.Sprintf("testcase '%s'", tc.desc)) // Test JSON rendering jsonData, err := json.Marshal(heatmap) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.JSONResult, string(jsonData)) } } diff --git a/models/asymkey/gpg_key_test.go b/models/asymkey/gpg_key_test.go index cc31f5dc01..e9aa9cf5ec 100644 --- a/models/asymkey/gpg_key_test.go +++ b/models/asymkey/gpg_key_test.go @@ -15,6 +15,7 @@ import ( "github.com/ProtonMail/go-crypto/openpgp/packet" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCheckArmoredGPGKeyString(t *testing.T) { @@ -50,7 +51,7 @@ MkM/fdpyc2hY7Dl/+qFmN5MG5yGmMpQcX+RNNR222ibNC1D3wg== -----END PGP PUBLIC KEY BLOCK-----` key, err := checkArmoredGPGKeyString(testGPGArmor) - assert.NoError(t, err, "Could not parse a valid GPG public armored rsa key", key) + require.NoError(t, err, "Could not parse a valid GPG public armored rsa key", key) // TODO verify value of key } @@ -71,7 +72,7 @@ OyjLLnFQiVmq7kEA/0z0CQe3ZQiQIq5zrs7Nh1XRkFAo8GlU/SGC9XFFi722 -----END PGP PUBLIC KEY BLOCK-----` key, err := checkArmoredGPGKeyString(testGPGArmor) - assert.NoError(t, err, "Could not parse a valid GPG public armored brainpoolP256r1 key", key) + require.NoError(t, err, "Could not parse a valid GPG public armored brainpoolP256r1 key", key) // TODO verify value of key } @@ -111,11 +112,11 @@ MkM/fdpyc2hY7Dl/+qFmN5MG5yGmMpQcX+RNNR222ibNC1D3wg== return } ekey := keys[0] - assert.NoError(t, err, "Could not parse a valid GPG armored key", ekey) + require.NoError(t, err, "Could not parse a valid GPG armored key", ekey) pubkey := ekey.PrimaryKey content, err := base64EncPubKey(pubkey) - assert.NoError(t, err, "Could not base64 encode a valid PublicKey content", ekey) + require.NoError(t, err, "Could not base64 encode a valid PublicKey content", ekey) key := &GPGKey{ KeyID: pubkey.KeyIdString(), @@ -176,27 +177,27 @@ Unknown GPG key with good email ` // Reading Sign goodSig, err := extractSignature(testGoodSigArmor) - assert.NoError(t, err, "Could not parse a valid GPG armored signature", testGoodSigArmor) + require.NoError(t, err, "Could not parse a valid GPG armored signature", testGoodSigArmor) badSig, err := extractSignature(testBadSigArmor) - assert.NoError(t, err, "Could not parse a valid GPG armored signature", testBadSigArmor) + require.NoError(t, err, "Could not parse a valid GPG armored signature", testBadSigArmor) // Generating hash of commit goodHash, err := populateHash(goodSig.Hash, []byte(testGoodPayload)) - assert.NoError(t, err, "Could not generate a valid hash of payload", testGoodPayload) + require.NoError(t, err, "Could not generate a valid hash of payload", testGoodPayload) badHash, err := populateHash(badSig.Hash, []byte(testBadPayload)) - assert.NoError(t, err, "Could not generate a valid hash of payload", testBadPayload) + require.NoError(t, err, "Could not generate a valid hash of payload", testBadPayload) // Verify err = verifySign(goodSig, goodHash, key) - assert.NoError(t, err, "Could not validate a good signature") + require.NoError(t, err, "Could not validate a good signature") err = verifySign(badSig, badHash, key) - assert.Error(t, err, "Validate a bad signature") + require.Error(t, err, "Validate a bad signature") err = verifySign(goodSig, goodHash, cannotsignkey) - assert.Error(t, err, "Validate a bad signature with a kay that can not sign") + require.Error(t, err, "Validate a bad signature with a kay that can not sign") } func TestCheckGPGUserEmail(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) _ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -232,7 +233,7 @@ Q0KHb+QcycSgbDx0ZAvdIacuKvBBcbxrsmFUI4LR+oIup0G9gUc0roPvr014jYQL -----END PGP PUBLIC KEY BLOCK-----` keys, err := AddGPGKey(db.DefaultContext, 1, testEmailWithUpperCaseLetters, "", "") - assert.NoError(t, err) + require.NoError(t, err) if assert.NotEmpty(t, keys) { key := keys[0] if assert.Len(t, key.Emails, 1) { @@ -242,10 +243,10 @@ Q0KHb+QcycSgbDx0ZAvdIacuKvBBcbxrsmFUI4LR+oIup0G9gUc0roPvr014jYQL } func TestCheckGPGRevokedIdentity(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) - assert.NoError(t, db.Insert(db.DefaultContext, &user_model.EmailAddress{UID: 1, Email: "no-reply@golang.com", IsActivated: true})) - assert.NoError(t, db.Insert(db.DefaultContext, &user_model.EmailAddress{UID: 1, Email: "revoked@golang.com", IsActivated: true})) + require.NoError(t, db.Insert(db.DefaultContext, &user_model.EmailAddress{UID: 1, Email: "no-reply@golang.com", IsActivated: true})) + require.NoError(t, db.Insert(db.DefaultContext, &user_model.EmailAddress{UID: 1, Email: "revoked@golang.com", IsActivated: true})) _ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) revokedUserKey := `-----BEGIN PGP PUBLIC KEY BLOCK----- @@ -289,7 +290,7 @@ heiQvzkApQup5c+BhH5zFDFdKJ2CBByxw9+7QjMFI/wgLixKuE0Ob2kAokXf7RlB ` keys, err := AddGPGKey(db.DefaultContext, 1, revokedUserKey, "", "") - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, keys, 1) assert.Len(t, keys[0].Emails, 1) assert.EqualValues(t, "no-reply@golang.com", keys[0].Emails[0].Email) @@ -446,7 +447,7 @@ epiDVQ== -----END PGP PUBLIC KEY BLOCK----- ` keys, err := checkArmoredGPGKeyString(testIssue6599) - assert.NoError(t, err) + require.NoError(t, err) if assert.NotEmpty(t, keys) { ekey := keys[0] expire := getExpiryTime(ekey) diff --git a/models/asymkey/ssh_key_object_verification_test.go b/models/asymkey/ssh_key_object_verification_test.go index 4e229c9b13..0d5ebabb70 100644 --- a/models/asymkey/ssh_key_object_verification_test.go +++ b/models/asymkey/ssh_key_object_verification_test.go @@ -14,10 +14,11 @@ import ( "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParseCommitWithSSHSignature(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) sshKey := unittest.AssertExistsAndLoadBean(t, &PublicKey{ID: 1000, OwnerID: 2}) diff --git a/models/asymkey/ssh_key_test.go b/models/asymkey/ssh_key_test.go index d3e886b97f..4c1c44967f 100644 --- a/models/asymkey/ssh_key_test.go +++ b/models/asymkey/ssh_key_test.go @@ -16,6 +16,7 @@ import ( "github.com/42wim/sshsig" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_SSHParsePublicKey(t *testing.T) { @@ -39,7 +40,7 @@ func Test_SSHParsePublicKey(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Run("Native", func(t *testing.T) { keyTypeN, lengthN, err := SSHNativeParsePublicKey(tc.content) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.keyType, keyTypeN) assert.EqualValues(t, tc.length, lengthN) }) @@ -146,7 +147,7 @@ AAAAC3NzaC1lZDI1NTE5AAAAICV0MGX/W9IvLA4FXpIuUcdDcbj5KX4syHgsTy7soVgf `}, } { _, err := CheckPublicKeyString(test.content) - assert.NoError(t, err) + require.NoError(t, err) } setting.SSH.MinimumKeySizeCheck = oldValue for _, invalidKeys := range []struct { @@ -159,7 +160,7 @@ AAAAC3NzaC1lZDI1NTE5AAAAICV0MGX/W9IvLA4FXpIuUcdDcbj5KX4syHgsTy7soVgf {"\r\ntest \r\ngitea\r\n\r\n"}, } { _, err := CheckPublicKeyString(invalidKeys.content) - assert.Error(t, err) + require.Error(t, err) } } @@ -183,7 +184,7 @@ func Test_calcFingerprint(t *testing.T) { t.Run(tc.name, func(t *testing.T) { t.Run("Native", func(t *testing.T) { fpN, err := calcFingerprintNative(tc.content) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.fp, fpN) }) if tc.skipSSHKeygen { @@ -191,7 +192,7 @@ func Test_calcFingerprint(t *testing.T) { } t.Run("SSHKeygen", func(t *testing.T) { fpK, err := calcFingerprintSSHKeygen(tc.content) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tc.fp, fpK) }) }) diff --git a/models/auth/access_token_test.go b/models/auth/access_token_test.go index 4360f1a214..e6ea4876e5 100644 --- a/models/auth/access_token_test.go +++ b/models/auth/access_token_test.go @@ -11,15 +11,16 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewAccessToken(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) token := &auth_model.AccessToken{ UID: 3, Name: "Token C", } - assert.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token)) + require.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token)) unittest.AssertExistsAndLoadBean(t, token) invalidToken := &auth_model.AccessToken{ @@ -27,13 +28,13 @@ func TestNewAccessToken(t *testing.T) { UID: 2, Name: "Token F", } - assert.Error(t, auth_model.NewAccessToken(db.DefaultContext, invalidToken)) + require.Error(t, auth_model.NewAccessToken(db.DefaultContext, invalidToken)) } func TestAccessTokenByNameExists(t *testing.T) { name := "Token Gitea" - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) token := &auth_model.AccessToken{ UID: 3, Name: name, @@ -41,16 +42,16 @@ func TestAccessTokenByNameExists(t *testing.T) { // Check to make sure it doesn't exists already exist, err := auth_model.AccessTokenByNameExists(db.DefaultContext, token) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exist) // Save it to the database - assert.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token)) + require.NoError(t, auth_model.NewAccessToken(db.DefaultContext, token)) unittest.AssertExistsAndLoadBean(t, token) // This token must be found by name in the DB now exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, token) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exist) user4Token := &auth_model.AccessToken{ @@ -61,32 +62,32 @@ func TestAccessTokenByNameExists(t *testing.T) { // Name matches but different user ID, this shouldn't exists in the // database exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, user4Token) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exist) } func TestGetAccessTokenBySHA(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "d2c6c1ba3890b309189a8e618c72a162e4efbf36") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), token.UID) assert.Equal(t, "Token A", token.Name) assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash) assert.Equal(t, "e4efbf36", token.TokenLastEight) _, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "notahash") - assert.Error(t, err) + require.Error(t, err) assert.True(t, auth_model.IsErrAccessTokenNotExist(err)) _, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "") - assert.Error(t, err) + require.Error(t, err) assert.True(t, auth_model.IsErrAccessTokenEmpty(err)) } func TestListAccessTokens(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) tokens, err := db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 1}) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, tokens, 2) { assert.Equal(t, int64(1), tokens[0].UID) assert.Equal(t, int64(1), tokens[1].UID) @@ -95,38 +96,38 @@ func TestListAccessTokens(t *testing.T) { } tokens, err = db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 2}) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, tokens, 1) { assert.Equal(t, int64(2), tokens[0].UID) assert.Equal(t, "Token A", tokens[0].Name) } tokens, err = db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 100}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, tokens) } func TestUpdateAccessToken(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c") - assert.NoError(t, err) + require.NoError(t, err) token.Name = "Token Z" - assert.NoError(t, auth_model.UpdateAccessToken(db.DefaultContext, token)) + require.NoError(t, auth_model.UpdateAccessToken(db.DefaultContext, token)) unittest.AssertExistsAndLoadBean(t, token) } func TestDeleteAccessTokenByID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), token.UID) - assert.NoError(t, auth_model.DeleteAccessTokenByID(db.DefaultContext, token.ID, 1)) + require.NoError(t, auth_model.DeleteAccessTokenByID(db.DefaultContext, token.ID, 1)) unittest.AssertNotExistsBean(t, token) err = auth_model.DeleteAccessTokenByID(db.DefaultContext, 100, 100) - assert.Error(t, err) + require.Error(t, err) assert.True(t, auth_model.IsErrAccessTokenNotExist(err)) } diff --git a/models/auth/oauth2_test.go b/models/auth/oauth2_test.go index a6fbcdaa4f..c43d9d36c2 100644 --- a/models/auth/oauth2_test.go +++ b/models/auth/oauth2_test.go @@ -14,19 +14,20 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestOAuth2Application_GenerateClientSecret(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1}) secret, err := app.GenerateClientSecret(db.DefaultContext) - assert.NoError(t, err) - assert.True(t, len(secret) > 0) + require.NoError(t, err) + assert.Positive(t, len(secret)) unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1, ClientSecret: app.ClientSecret}) } func BenchmarkOAuth2Application_GenerateClientSecret(b *testing.B) { - assert.NoError(b, unittest.PrepareTestDatabase()) + require.NoError(b, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(b, &auth_model.OAuth2Application{ID: 1}) for i := 0; i < b.N; i++ { _, _ = app.GenerateClientSecret(db.DefaultContext) @@ -77,29 +78,29 @@ func TestOAuth2Application_ContainsRedirect_Slash(t *testing.T) { } func TestOAuth2Application_ValidateClientSecret(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1}) secret, err := app.GenerateClientSecret(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, app.ValidateClientSecret([]byte(secret))) assert.False(t, app.ValidateClientSecret([]byte("fewijfowejgfiowjeoifew"))) } func TestGetOAuth2ApplicationByClientID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) app, err := auth_model.GetOAuth2ApplicationByClientID(db.DefaultContext, "da7da3ba-9a13-4167-856f-3899de0b0138") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "da7da3ba-9a13-4167-856f-3899de0b0138", app.ClientID) app, err = auth_model.GetOAuth2ApplicationByClientID(db.DefaultContext, "invalid client id") - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, app) } func TestCreateOAuth2Application(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) app, err := auth_model.CreateOAuth2Application(db.DefaultContext, auth_model.CreateOAuth2ApplicationOptions{Name: "newapp", UserID: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "newapp", app.Name) assert.Len(t, app.ClientID, 36) unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{Name: "newapp"}) @@ -110,22 +111,22 @@ func TestOAuth2Application_TableName(t *testing.T) { } func TestOAuth2Application_GetGrantByUserID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1}) grant, err := app.GetGrantByUserID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), grant.UserID) grant, err = app.GetGrantByUserID(db.DefaultContext, 34923458) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, grant) } func TestOAuth2Application_CreateGrant(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1}) grant, err := app.CreateGrant(db.DefaultContext, 2, "") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, grant) assert.Equal(t, int64(2), grant.UserID) assert.Equal(t, int64(1), grant.ApplicationID) @@ -135,26 +136,26 @@ func TestOAuth2Application_CreateGrant(t *testing.T) { //////////////////// Grant func TestGetOAuth2GrantByID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) grant, err := auth_model.GetOAuth2GrantByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), grant.ID) grant, err = auth_model.GetOAuth2GrantByID(db.DefaultContext, 34923458) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, grant) } func TestOAuth2Grant_IncreaseCounter(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 1}) - assert.NoError(t, grant.IncreaseCounter(db.DefaultContext)) + require.NoError(t, grant.IncreaseCounter(db.DefaultContext)) assert.Equal(t, int64(2), grant.Counter) unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 2}) } func TestOAuth2Grant_ScopeContains(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Scope: "openid profile"}) assert.True(t, grant.ScopeContains("openid")) assert.True(t, grant.ScopeContains("profile")) @@ -163,12 +164,12 @@ func TestOAuth2Grant_ScopeContains(t *testing.T) { } func TestOAuth2Grant_GenerateNewAuthorizationCode(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1}) code, err := grant.GenerateNewAuthorizationCode(db.DefaultContext, "https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, code) - assert.True(t, len(code.Code) > 32) // secret length > 32 + assert.Greater(t, len(code.Code), 32) // secret length > 32 } func TestOAuth2Grant_TableName(t *testing.T) { @@ -176,36 +177,36 @@ func TestOAuth2Grant_TableName(t *testing.T) { } func TestGetOAuth2GrantsByUserID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) result, err := auth_model.GetOAuth2GrantsByUserID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, result, 1) assert.Equal(t, int64(1), result[0].ID) assert.Equal(t, result[0].ApplicationID, result[0].Application.ID) result, err = auth_model.GetOAuth2GrantsByUserID(db.DefaultContext, 34134) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, result) } func TestRevokeOAuth2Grant(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - assert.NoError(t, auth_model.RevokeOAuth2Grant(db.DefaultContext, 1, 1)) + require.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, auth_model.RevokeOAuth2Grant(db.DefaultContext, 1, 1)) unittest.AssertNotExistsBean(t, &auth_model.OAuth2Grant{ID: 1, UserID: 1}) } //////////////////// Authorization Code func TestGetOAuth2AuthorizationByCode(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) code, err := auth_model.GetOAuth2AuthorizationByCode(db.DefaultContext, "authcode") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, code) assert.Equal(t, "authcode", code.Code) assert.Equal(t, int64(1), code.ID) code, err = auth_model.GetOAuth2AuthorizationByCode(db.DefaultContext, "does not exist") - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, code) } @@ -248,18 +249,18 @@ func TestOAuth2AuthorizationCode_GenerateRedirectURI(t *testing.T) { } redirect, err := code.GenerateRedirectURI("thestate") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "https://example.com/callback?code=thecode&state=thestate", redirect.String()) redirect, err = code.GenerateRedirectURI("") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "https://example.com/callback?code=thecode", redirect.String()) } func TestOAuth2AuthorizationCode_Invalidate(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) code := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2AuthorizationCode{Code: "authcode"}) - assert.NoError(t, code.Invalidate(db.DefaultContext)) + require.NoError(t, code.Invalidate(db.DefaultContext)) unittest.AssertNotExistsBean(t, &auth_model.OAuth2AuthorizationCode{Code: "authcode"}) } @@ -281,18 +282,18 @@ func TestOrphanedOAuth2Applications(t *testing.T) { Dirs: []string{"models/auth/TestOrphanedOAuth2Applications/"}, }, )() - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) count, err := auth_model.CountOrphanedOAuth2Applications(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, count) unittest.AssertExistsIf(t, true, &auth_model.OAuth2Application{ID: 1002}) _, err = auth_model.DeleteOrphanedOAuth2Applications(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) count, err = auth_model.CountOrphanedOAuth2Applications(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, count) unittest.AssertExistsIf(t, false, &auth_model.OAuth2Application{ID: 1002}) } diff --git a/models/auth/session_test.go b/models/auth/session_test.go index 8cc0abc737..3b57239704 100644 --- a/models/auth/session_test.go +++ b/models/auth/session_test.go @@ -13,10 +13,11 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAuthSession(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) defer timeutil.MockUnset() key := "I-Like-Free-Software" @@ -24,30 +25,30 @@ func TestAuthSession(t *testing.T) { t.Run("Create Session", func(t *testing.T) { // Ensure it doesn't exist. ok, err := auth.ExistSession(db.DefaultContext, key) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, ok) preCount, err := auth.CountSessions(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) now := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC) timeutil.MockSet(now) // New session is created. sess, err := auth.ReadSession(db.DefaultContext, key) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, key, sess.Key) assert.Empty(t, sess.Data) assert.EqualValues(t, now.Unix(), sess.Expiry) // Ensure it exists. ok, err = auth.ExistSession(db.DefaultContext, key) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, ok) // Ensure the session is taken into account for count.. postCount, err := auth.CountSessions(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Greater(t, postCount, preCount) }) @@ -58,14 +59,14 @@ func TestAuthSession(t *testing.T) { // Update session. err := auth.UpdateSession(db.DefaultContext, key, data) - assert.NoError(t, err) + require.NoError(t, err) timeutil.MockSet(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)) // Read updated session. // Ensure data is updated and expiry is set from the update session call. sess, err := auth.ReadSession(db.DefaultContext, key) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, key, sess.Key) assert.EqualValues(t, data, sess.Data) assert.EqualValues(t, now.Unix(), sess.Expiry) @@ -76,23 +77,23 @@ func TestAuthSession(t *testing.T) { t.Run("Delete session", func(t *testing.T) { // Ensure it't exist. ok, err := auth.ExistSession(db.DefaultContext, key) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, ok) preCount, err := auth.CountSessions(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) err = auth.DestroySession(db.DefaultContext, key) - assert.NoError(t, err) + require.NoError(t, err) // Ensure it doesn't exists. ok, err = auth.ExistSession(db.DefaultContext, key) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, ok) // Ensure the session is taken into account for count.. postCount, err := auth.CountSessions(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Less(t, postCount, preCount) }) @@ -100,43 +101,43 @@ func TestAuthSession(t *testing.T) { timeutil.MockSet(time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC)) _, err := auth.ReadSession(db.DefaultContext, "sess-1") - assert.NoError(t, err) + require.NoError(t, err) // One minute later. timeutil.MockSet(time.Date(2023, 1, 1, 0, 1, 0, 0, time.UTC)) _, err = auth.ReadSession(db.DefaultContext, "sess-2") - assert.NoError(t, err) + require.NoError(t, err) // 5 minutes, shouldn't clean up anything. err = auth.CleanupSessions(db.DefaultContext, 5*60) - assert.NoError(t, err) + require.NoError(t, err) ok, err := auth.ExistSession(db.DefaultContext, "sess-1") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, ok) ok, err = auth.ExistSession(db.DefaultContext, "sess-2") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, ok) // 1 minute, should clean up sess-1. err = auth.CleanupSessions(db.DefaultContext, 60) - assert.NoError(t, err) + require.NoError(t, err) ok, err = auth.ExistSession(db.DefaultContext, "sess-1") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, ok) ok, err = auth.ExistSession(db.DefaultContext, "sess-2") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, ok) // Now, should clean up sess-2. err = auth.CleanupSessions(db.DefaultContext, 0) - assert.NoError(t, err) + require.NoError(t, err) ok, err = auth.ExistSession(db.DefaultContext, "sess-2") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, ok) }) } diff --git a/models/auth/source_test.go b/models/auth/source_test.go index 36e76d5e28..522fecc25f 100644 --- a/models/auth/source_test.go +++ b/models/auth/source_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/xorm/schemas" ) @@ -35,10 +36,10 @@ func (source *TestSource) ToDB() ([]byte, error) { } func TestDumpAuthSource(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) authSourceSchema, err := db.TableInfo(new(auth_model.Source)) - assert.NoError(t, err) + require.NoError(t, err) auth_model.RegisterTypeConfig(auth_model.OAuth2, new(TestSource)) diff --git a/models/auth/webauthn_test.go b/models/auth/webauthn_test.go index f1cf398adf..cae590c790 100644 --- a/models/auth/webauthn_test.go +++ b/models/auth/webauthn_test.go @@ -12,25 +12,26 @@ import ( "github.com/go-webauthn/webauthn/webauthn" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetWebAuthnCredentialByID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) res, err := auth_model.GetWebAuthnCredentialByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "WebAuthn credential", res.Name) _, err = auth_model.GetWebAuthnCredentialByID(db.DefaultContext, 342432) - assert.Error(t, err) + require.Error(t, err) assert.True(t, auth_model.IsErrWebAuthnCredentialNotExist(err)) } func TestGetWebAuthnCredentialsByUID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) res, err := auth_model.GetWebAuthnCredentialsByUID(db.DefaultContext, 32) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, res, 1) assert.Equal(t, "WebAuthn credential", res[0].Name) } @@ -40,26 +41,26 @@ func TestWebAuthnCredential_TableName(t *testing.T) { } func TestWebAuthnCredential_UpdateSignCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) cred := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1}) cred.SignCount = 1 - assert.NoError(t, cred.UpdateSignCount(db.DefaultContext)) + require.NoError(t, cred.UpdateSignCount(db.DefaultContext)) unittest.AssertExistsIf(t, true, &auth_model.WebAuthnCredential{ID: 1, SignCount: 1}) } func TestWebAuthnCredential_UpdateLargeCounter(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) cred := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1}) cred.SignCount = 0xffffffff - assert.NoError(t, cred.UpdateSignCount(db.DefaultContext)) + require.NoError(t, cred.UpdateSignCount(db.DefaultContext)) unittest.AssertExistsIf(t, true, &auth_model.WebAuthnCredential{ID: 1, SignCount: 0xffffffff}) } func TestCreateCredential(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) res, err := auth_model.CreateCredential(db.DefaultContext, 1, "WebAuthn Created Credential", &webauthn.Credential{ID: []byte("Test")}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "WebAuthn Created Credential", res.Name) assert.Equal(t, []byte("Test"), res.CredentialID) diff --git a/models/avatars/avatar_test.go b/models/avatars/avatar_test.go index c8f7a6574b..85c40c3fa1 100644 --- a/models/avatars/avatar_test.go +++ b/models/avatars/avatar_test.go @@ -13,20 +13,21 @@ import ( "code.gitea.io/gitea/modules/setting/config" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const gravatarSource = "https://secure.gravatar.com/avatar/" func disableGravatar(t *testing.T) { err := system_model.SetSettings(db.DefaultContext, map[string]string{setting.Config().Picture.EnableFederatedAvatar.DynKey(): "false"}) - assert.NoError(t, err) + require.NoError(t, err) err = system_model.SetSettings(db.DefaultContext, map[string]string{setting.Config().Picture.DisableGravatar.DynKey(): "true"}) - assert.NoError(t, err) + require.NoError(t, err) } func enableGravatar(t *testing.T) { err := system_model.SetSettings(db.DefaultContext, map[string]string{setting.Config().Picture.DisableGravatar.DynKey(): "false"}) - assert.NoError(t, err) + require.NoError(t, err) setting.GravatarSource = gravatarSource } diff --git a/models/db/context_test.go b/models/db/context_test.go index 95a01d4a26..855f360b75 100644 --- a/models/db/context_test.go +++ b/models/db/context_test.go @@ -11,74 +11,75 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestInTransaction(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) assert.False(t, db.InTransaction(db.DefaultContext)) - assert.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error { + require.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error { assert.True(t, db.InTransaction(ctx)) return nil })) ctx, committer, err := db.TxContext(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) defer committer.Close() assert.True(t, db.InTransaction(ctx)) - assert.NoError(t, db.WithTx(ctx, func(ctx context.Context) error { + require.NoError(t, db.WithTx(ctx, func(ctx context.Context) error { assert.True(t, db.InTransaction(ctx)) return nil })) } func TestTxContext(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) { // create new transaction ctx, committer, err := db.TxContext(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, db.InTransaction(ctx)) - assert.NoError(t, committer.Commit()) + require.NoError(t, committer.Commit()) } { // reuse the transaction created by TxContext and commit it ctx, committer, err := db.TxContext(db.DefaultContext) engine := db.GetEngine(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, db.InTransaction(ctx)) { ctx, committer, err := db.TxContext(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, db.InTransaction(ctx)) assert.Equal(t, engine, db.GetEngine(ctx)) - assert.NoError(t, committer.Commit()) + require.NoError(t, committer.Commit()) } - assert.NoError(t, committer.Commit()) + require.NoError(t, committer.Commit()) } { // reuse the transaction created by TxContext and close it ctx, committer, err := db.TxContext(db.DefaultContext) engine := db.GetEngine(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, db.InTransaction(ctx)) { ctx, committer, err := db.TxContext(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, db.InTransaction(ctx)) assert.Equal(t, engine, db.GetEngine(ctx)) - assert.NoError(t, committer.Close()) + require.NoError(t, committer.Close()) } - assert.NoError(t, committer.Close()) + require.NoError(t, committer.Close()) } { // reuse the transaction created by WithTx - assert.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error { + require.NoError(t, db.WithTx(db.DefaultContext, func(ctx context.Context) error { assert.True(t, db.InTransaction(ctx)) { ctx, committer, err := db.TxContext(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, db.InTransaction(ctx)) - assert.NoError(t, committer.Commit()) + require.NoError(t, committer.Commit()) } return nil })) diff --git a/models/db/engine_test.go b/models/db/engine_test.go index f050c5ca28..230ee3f2b1 100644 --- a/models/db/engine_test.go +++ b/models/db/engine_test.go @@ -18,11 +18,12 @@ import ( _ "code.gitea.io/gitea/cmd" // for TestPrimaryKeys "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/xorm" ) func TestDumpDatabase(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) dir := t.TempDir() @@ -30,31 +31,31 @@ func TestDumpDatabase(t *testing.T) { ID int64 `xorm:"pk autoincr"` Version int64 } - assert.NoError(t, db.GetEngine(db.DefaultContext).Sync(new(Version))) + require.NoError(t, db.GetEngine(db.DefaultContext).Sync(new(Version))) for _, dbType := range setting.SupportedDatabaseTypes { - assert.NoError(t, db.DumpDatabase(filepath.Join(dir, dbType+".sql"), dbType)) + require.NoError(t, db.DumpDatabase(filepath.Join(dir, dbType+".sql"), dbType)) } } func TestDeleteOrphanedObjects(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) countBefore, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{}) - assert.NoError(t, err) + require.NoError(t, err) _, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003}) - assert.NoError(t, err) + require.NoError(t, err) orphaned, err := db.CountOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, orphaned) err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id") - assert.NoError(t, err) + require.NoError(t, err) countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, countBefore, countAfter) } diff --git a/models/db/index_test.go b/models/db/index_test.go index 5fce0a6012..11fbc70d8d 100644 --- a/models/db/index_test.go +++ b/models/db/index_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type TestIndex db.ResourceIndex @@ -31,96 +32,96 @@ func getCurrentResourceIndex(ctx context.Context, tableName string, groupID int6 } func TestSyncMaxResourceIndex(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) xe := unittest.GetXORMEngine() - assert.NoError(t, xe.Sync(&TestIndex{})) + require.NoError(t, xe.Sync(&TestIndex{})) err := db.SyncMaxResourceIndex(db.DefaultContext, "test_index", 10, 51) - assert.NoError(t, err) + require.NoError(t, err) // sync new max index maxIndex, err := getCurrentResourceIndex(db.DefaultContext, "test_index", 10) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 51, maxIndex) // smaller index doesn't change err = db.SyncMaxResourceIndex(db.DefaultContext, "test_index", 10, 30) - assert.NoError(t, err) + require.NoError(t, err) maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 51, maxIndex) // larger index changes err = db.SyncMaxResourceIndex(db.DefaultContext, "test_index", 10, 62) - assert.NoError(t, err) + require.NoError(t, err) maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 62, maxIndex) // commit transaction err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { err = db.SyncMaxResourceIndex(ctx, "test_index", 10, 73) - assert.NoError(t, err) + require.NoError(t, err) maxIndex, err = getCurrentResourceIndex(ctx, "test_index", 10) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 73, maxIndex) return nil }) - assert.NoError(t, err) + require.NoError(t, err) maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 73, maxIndex) // rollback transaction err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { err = db.SyncMaxResourceIndex(ctx, "test_index", 10, 84) maxIndex, err = getCurrentResourceIndex(ctx, "test_index", 10) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 84, maxIndex) return errors.New("test rollback") }) - assert.Error(t, err) + require.Error(t, err) maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 73, maxIndex) // the max index doesn't change because the transaction was rolled back } func TestGetNextResourceIndex(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) xe := unittest.GetXORMEngine() - assert.NoError(t, xe.Sync(&TestIndex{})) + require.NoError(t, xe.Sync(&TestIndex{})) // create a new record maxIndex, err := db.GetNextResourceIndex(db.DefaultContext, "test_index", 20) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, maxIndex) // increase the existing record maxIndex, err = db.GetNextResourceIndex(db.DefaultContext, "test_index", 20) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 2, maxIndex) // commit transaction err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { maxIndex, err = db.GetNextResourceIndex(ctx, "test_index", 20) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, maxIndex) return nil }) - assert.NoError(t, err) + require.NoError(t, err) maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 20) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, maxIndex) // rollback transaction err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { maxIndex, err = db.GetNextResourceIndex(ctx, "test_index", 20) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 4, maxIndex) return errors.New("test rollback") }) - assert.Error(t, err) + require.Error(t, err) maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 20) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, maxIndex) // the max index doesn't change because the transaction was rolled back } diff --git a/models/db/iterate_test.go b/models/db/iterate_test.go index 0f6ba2cc94..7535d01d56 100644 --- a/models/db/iterate_test.go +++ b/models/db/iterate_test.go @@ -12,22 +12,23 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIterate(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) xe := unittest.GetXORMEngine() - assert.NoError(t, xe.Sync(&repo_model.RepoUnit{})) + require.NoError(t, xe.Sync(&repo_model.RepoUnit{})) cnt, err := db.GetEngine(db.DefaultContext).Count(&repo_model.RepoUnit{}) - assert.NoError(t, err) + require.NoError(t, err) var repoUnitCnt int err = db.Iterate(db.DefaultContext, nil, func(ctx context.Context, repo *repo_model.RepoUnit) error { repoUnitCnt++ return nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, cnt, repoUnitCnt) err = db.Iterate(db.DefaultContext, nil, func(ctx context.Context, repoUnit *repo_model.RepoUnit) error { @@ -38,9 +39,7 @@ func TestIterate(t *testing.T) { if !has { return db.ErrNotExist{Resource: "repo_unit", ID: repoUnit.ID} } - assert.EqualValues(t, repoUnit.RepoID, repoUnit.RepoID) - assert.EqualValues(t, repoUnit.CreatedUnix, repoUnit.CreatedUnix) return nil }) - assert.NoError(t, err) + require.NoError(t, err) } diff --git a/models/db/list_test.go b/models/db/list_test.go index 45194611f8..82240d205b 100644 --- a/models/db/list_test.go +++ b/models/db/list_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/builder" ) @@ -27,26 +28,26 @@ func (opts mockListOptions) ToConds() builder.Cond { } func TestFind(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) xe := unittest.GetXORMEngine() - assert.NoError(t, xe.Sync(&repo_model.RepoUnit{})) + require.NoError(t, xe.Sync(&repo_model.RepoUnit{})) var repoUnitCount int _, err := db.GetEngine(db.DefaultContext).SQL("SELECT COUNT(*) FROM repo_unit").Get(&repoUnitCount) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, repoUnitCount) opts := mockListOptions{} repoUnits, err := db.Find[repo_model.RepoUnit](db.DefaultContext, opts) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, repoUnits, repoUnitCount) cnt, err := db.Count[repo_model.RepoUnit](db.DefaultContext, opts) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, repoUnitCount, cnt) repoUnits, newCnt, err := db.FindAndCount[repo_model.RepoUnit](db.DefaultContext, opts) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, cnt, newCnt) assert.Len(t, repoUnits, repoUnitCount) } diff --git a/models/dbfs/dbfs_test.go b/models/dbfs/dbfs_test.go index 96cb1014c7..3ad273a732 100644 --- a/models/dbfs/dbfs_test.go +++ b/models/dbfs/dbfs_test.go @@ -12,6 +12,7 @@ import ( "code.gitea.io/gitea/models/db" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func changeDefaultFileBlockSize(n int64) (restore func()) { @@ -27,102 +28,102 @@ func TestDbfsBasic(t *testing.T) { // test basic write/read f, err := OpenFile(db.DefaultContext, "test.txt", os.O_RDWR|os.O_CREATE) - assert.NoError(t, err) + require.NoError(t, err) n, err := f.Write([]byte("0123456789")) // blocks: 0123 4567 89 - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 10, n) _, err = f.Seek(0, io.SeekStart) - assert.NoError(t, err) + require.NoError(t, err) buf, err := io.ReadAll(f) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 10, n) assert.EqualValues(t, "0123456789", string(buf)) // write some new data _, err = f.Seek(1, io.SeekStart) - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Write([]byte("bcdefghi")) // blocks: 0bcd efgh i9 - assert.NoError(t, err) + require.NoError(t, err) // read from offset buf, err = io.ReadAll(f) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "9", string(buf)) // read all _, err = f.Seek(0, io.SeekStart) - assert.NoError(t, err) + require.NoError(t, err) buf, err = io.ReadAll(f) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "0bcdefghi9", string(buf)) // write to new size _, err = f.Seek(-1, io.SeekEnd) - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Write([]byte("JKLMNOP")) // blocks: 0bcd efgh iJKL MNOP - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Seek(0, io.SeekStart) - assert.NoError(t, err) + require.NoError(t, err) buf, err = io.ReadAll(f) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "0bcdefghiJKLMNOP", string(buf)) // write beyond EOF and fill with zero _, err = f.Seek(5, io.SeekCurrent) - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Write([]byte("xyzu")) // blocks: 0bcd efgh iJKL MNOP 0000 0xyz u - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Seek(0, io.SeekStart) - assert.NoError(t, err) + require.NoError(t, err) buf, err = io.ReadAll(f) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "0bcdefghiJKLMNOP\x00\x00\x00\x00\x00xyzu", string(buf)) // write to the block with zeros _, err = f.Seek(-6, io.SeekCurrent) - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Write([]byte("ABCD")) // blocks: 0bcd efgh iJKL MNOP 000A BCDz u - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Seek(0, io.SeekStart) - assert.NoError(t, err) + require.NoError(t, err) buf, err = io.ReadAll(f) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "0bcdefghiJKLMNOP\x00\x00\x00ABCDzu", string(buf)) - assert.NoError(t, f.Close()) + require.NoError(t, f.Close()) // test rename err = Rename(db.DefaultContext, "test.txt", "test2.txt") - assert.NoError(t, err) + require.NoError(t, err) _, err = OpenFile(db.DefaultContext, "test.txt", os.O_RDONLY) - assert.Error(t, err) + require.Error(t, err) f, err = OpenFile(db.DefaultContext, "test2.txt", os.O_RDONLY) - assert.NoError(t, err) - assert.NoError(t, f.Close()) + require.NoError(t, err) + require.NoError(t, f.Close()) // test remove err = Remove(db.DefaultContext, "test2.txt") - assert.NoError(t, err) + require.NoError(t, err) _, err = OpenFile(db.DefaultContext, "test2.txt", os.O_RDONLY) - assert.Error(t, err) + require.Error(t, err) // test stat f, err = OpenFile(db.DefaultContext, "test/test.txt", os.O_RDWR|os.O_CREATE) - assert.NoError(t, err) + require.NoError(t, err) stat, err := f.Stat() - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "test.txt", stat.Name()) assert.EqualValues(t, 0, stat.Size()) _, err = f.Write([]byte("0123456789")) - assert.NoError(t, err) + require.NoError(t, err) stat, err = f.Stat() - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 10, stat.Size()) } @@ -130,61 +131,61 @@ func TestDbfsReadWrite(t *testing.T) { defer changeDefaultFileBlockSize(4)() f1, err := OpenFile(db.DefaultContext, "test.log", os.O_RDWR|os.O_CREATE) - assert.NoError(t, err) + require.NoError(t, err) defer f1.Close() f2, err := OpenFile(db.DefaultContext, "test.log", os.O_RDONLY) - assert.NoError(t, err) + require.NoError(t, err) defer f2.Close() _, err = f1.Write([]byte("line 1\n")) - assert.NoError(t, err) + require.NoError(t, err) f2r := bufio.NewReader(f2) line, err := f2r.ReadString('\n') - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "line 1\n", line) _, err = f2r.ReadString('\n') - assert.ErrorIs(t, err, io.EOF) + require.ErrorIs(t, err, io.EOF) _, err = f1.Write([]byte("line 2\n")) - assert.NoError(t, err) + require.NoError(t, err) line, err = f2r.ReadString('\n') - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "line 2\n", line) _, err = f2r.ReadString('\n') - assert.ErrorIs(t, err, io.EOF) + require.ErrorIs(t, err, io.EOF) } func TestDbfsSeekWrite(t *testing.T) { defer changeDefaultFileBlockSize(4)() f, err := OpenFile(db.DefaultContext, "test2.log", os.O_RDWR|os.O_CREATE) - assert.NoError(t, err) + require.NoError(t, err) defer f.Close() n, err := f.Write([]byte("111")) - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Seek(int64(n), io.SeekStart) - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Write([]byte("222")) - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Seek(int64(n), io.SeekStart) - assert.NoError(t, err) + require.NoError(t, err) _, err = f.Write([]byte("333")) - assert.NoError(t, err) + require.NoError(t, err) fr, err := OpenFile(db.DefaultContext, "test2.log", os.O_RDONLY) - assert.NoError(t, err) + require.NoError(t, err) defer f.Close() buf, err := io.ReadAll(fr) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "111333", string(buf)) } diff --git a/models/fixture_test.go b/models/fixture_test.go index de5f412388..33429c8c2d 100644 --- a/models/fixture_test.go +++ b/models/fixture_test.go @@ -14,21 +14,20 @@ import ( "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestFixtureGeneration(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(ctx context.Context, gen func(ctx context.Context) (string, error), name string) { expected, err := gen(ctx) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + p := filepath.Join(unittest.FixturesDir(), name+".yml") bytes, err := os.ReadFile(p) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + data := string(util.NormalizeEOL(bytes)) assert.EqualValues(t, expected, data, "Differences detected for %s", p) } diff --git a/models/forgejo/semver/semver_test.go b/models/forgejo/semver/semver_test.go index 8aca7bee57..a508c69b18 100644 --- a/models/forgejo/semver/semver_test.go +++ b/models/forgejo/semver/semver_test.go @@ -10,37 +10,38 @@ import ( "github.com/hashicorp/go-version" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestForgejoSemVerSetGet(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ctx := db.DefaultContext newVersion, err := version.NewVersion("v1.2.3") - assert.NoError(t, err) - assert.NoError(t, SetVersionString(ctx, newVersion.String())) + require.NoError(t, err) + require.NoError(t, SetVersionString(ctx, newVersion.String())) databaseVersion, err := GetVersion(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, newVersion.String(), databaseVersion.String()) assert.True(t, newVersion.Equal(databaseVersion)) } func TestForgejoSemVerMissing(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ctx := db.DefaultContext e := db.GetEngine(ctx) _, err := e.Exec("delete from forgejo_sem_ver") - assert.NoError(t, err) + require.NoError(t, err) v, err := GetVersion(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "1.0.0", v.String()) _, err = e.Exec("drop table forgejo_sem_ver") - assert.NoError(t, err) + require.NoError(t, err) v, err = GetVersion(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "1.0.0", v.String()) } diff --git a/models/forgejo_migrations/migrate_test.go b/models/forgejo_migrations/migrate_test.go index cccec0bf12..48ee4f77b1 100644 --- a/models/forgejo_migrations/migrate_test.go +++ b/models/forgejo_migrations/migrate_test.go @@ -8,7 +8,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // TestEnsureUpToDate tests the behavior of EnsureUpToDate. @@ -21,19 +21,19 @@ func TestEnsureUpToDate(t *testing.T) { // Ensure error if there's no row in Forgejo Version. err := EnsureUpToDate(x) - assert.Error(t, err) + require.Error(t, err) // Insert 'good' Forgejo Version row. _, err = x.InsertOne(&ForgejoVersion{ID: 1, Version: ExpectedVersion()}) - assert.NoError(t, err) + require.NoError(t, err) err = EnsureUpToDate(x) - assert.NoError(t, err) + require.NoError(t, err) // Modify forgejo version to have a lower version. _, err = x.Exec("UPDATE `forgejo_version` SET version = ? WHERE id = 1", ExpectedVersion()-1) - assert.NoError(t, err) + require.NoError(t, err) err = EnsureUpToDate(x) - assert.Error(t, err) + require.Error(t, err) } diff --git a/models/forgejo_migrations/v1_22/v8_test.go b/models/forgejo_migrations/v1_22/v8_test.go index fd8b77714f..128fd08ab0 100644 --- a/models/forgejo_migrations/v1_22/v8_test.go +++ b/models/forgejo_migrations/v1_22/v8_test.go @@ -9,6 +9,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_RemoveSSHSignaturesFromReleaseNotes(t *testing.T) { @@ -21,11 +22,11 @@ func Test_RemoveSSHSignaturesFromReleaseNotes(t *testing.T) { x, deferable := migration_tests.PrepareTestEnv(t, 0, new(Release)) defer deferable() - assert.NoError(t, RemoveSSHSignaturesFromReleaseNotes(x)) + require.NoError(t, RemoveSSHSignaturesFromReleaseNotes(x)) var releases []Release err := x.Table("release").OrderBy("id ASC").Find(&releases) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, releases, 3) assert.Equal(t, "", releases[0].Note) diff --git a/models/git/branch_test.go b/models/git/branch_test.go index 3aa578f44b..81839eb774 100644 --- a/models/git/branch_test.go +++ b/models/git/branch_test.go @@ -16,17 +16,18 @@ import ( "code.gitea.io/gitea/modules/optional" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAddDeletedBranch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) assert.EqualValues(t, git.Sha1ObjectFormat.Name(), repo.ObjectFormatName) firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1}) assert.True(t, firstBranch.IsDeleted) - assert.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, firstBranch.Name, firstBranch.DeletedByID)) - assert.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, "branch2", int64(1))) + require.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, firstBranch.Name, firstBranch.DeletedByID)) + require.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, "branch2", int64(1))) secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: repo.ID, Name: "branch2"}) assert.True(t, secondBranch.IsDeleted) @@ -40,11 +41,11 @@ func TestAddDeletedBranch(t *testing.T) { } _, err := git_model.UpdateBranch(db.DefaultContext, repo.ID, secondBranch.PusherID, secondBranch.Name, commit) - assert.NoError(t, err) + require.NoError(t, err) } func TestGetDeletedBranches(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) branches, err := db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ @@ -52,19 +53,19 @@ func TestGetDeletedBranches(t *testing.T) { RepoID: repo.ID, IsDeletedBranch: optional.Some(true), }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, branches, 2) } func TestGetDeletedBranch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1}) assert.NotNil(t, getDeletedBranch(t, firstBranch)) } func TestDeletedBranchLoadUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1}) secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 2}) @@ -83,13 +84,13 @@ func TestDeletedBranchLoadUser(t *testing.T) { } func TestRemoveDeletedBranch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1}) err := git_model.RemoveDeletedBranchByID(db.DefaultContext, repo.ID, 1) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertNotExistsBean(t, firstBranch) unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 2}) } @@ -98,7 +99,7 @@ func getDeletedBranch(t *testing.T, branch *git_model.Branch) *git_model.Branch repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) deletedBranch, err := git_model.GetDeletedBranchByID(db.DefaultContext, repo.ID, branch.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, branch.ID, deletedBranch.ID) assert.Equal(t, branch.Name, deletedBranch.Name) assert.Equal(t, branch.CommitID, deletedBranch.CommitID) @@ -108,32 +109,32 @@ func getDeletedBranch(t *testing.T, branch *git_model.Branch) *git_model.Branch } func TestFindRenamedBranch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) branch, exist, err := git_model.FindRenamedBranch(db.DefaultContext, 1, "dev") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exist) assert.Equal(t, "master", branch.To) _, exist, err = git_model.FindRenamedBranch(db.DefaultContext, 1, "unknow") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exist) } func TestRenameBranch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) _isDefault := false ctx, committer, err := db.TxContext(db.DefaultContext) defer committer.Close() - assert.NoError(t, err) - assert.NoError(t, git_model.UpdateProtectBranch(ctx, repo1, &git_model.ProtectedBranch{ + require.NoError(t, err) + require.NoError(t, git_model.UpdateProtectBranch(ctx, repo1, &git_model.ProtectedBranch{ RepoID: repo1.ID, RuleName: "master", }, git_model.WhitelistOptions{})) - assert.NoError(t, committer.Commit()) + require.NoError(t, committer.Commit()) - assert.NoError(t, git_model.RenameBranch(db.DefaultContext, repo1, "master", "main", func(ctx context.Context, isDefault bool) error { + require.NoError(t, git_model.RenameBranch(db.DefaultContext, repo1, "master", "main", func(ctx context.Context, isDefault bool) error { _isDefault = isDefault return nil })) @@ -160,7 +161,7 @@ func TestRenameBranch(t *testing.T) { } func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.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 @@ -170,7 +171,7 @@ func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) { deletedBranch, err := git_model.GetDeletedBranchByID(db.DefaultContext, repo2.ID, 1) // Expect error, and the returned branch is nil. - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, deletedBranch) // Now get the deletedBranch with ID of 1 on repo with ID 1. @@ -180,15 +181,15 @@ func TestOnlyGetDeletedBranchOnCorrectRepo(t *testing.T) { deletedBranch, err = git_model.GetDeletedBranchByID(db.DefaultContext, repo1.ID, 1) // Expect no error, and the returned branch to be not nil. - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, deletedBranch) } func TestFindBranchesByRepoAndBranchName(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // With no repos or branches given, we find no branches. branches, err := git_model.FindBranchesByRepoAndBranchName(db.DefaultContext, map[int64]string{}) - assert.NoError(t, err) - assert.Len(t, branches, 0) + require.NoError(t, err) + assert.Empty(t, branches) } diff --git a/models/git/commit_status_test.go b/models/git/commit_status_test.go index 2ada8b3724..07b9031c5c 100644 --- a/models/git/commit_status_test.go +++ b/models/git/commit_status_test.go @@ -17,10 +17,11 @@ import ( "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetCommitStatuses(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) @@ -31,8 +32,8 @@ func TestGetCommitStatuses(t *testing.T) { RepoID: repo1.ID, SHA: sha1, }) - assert.NoError(t, err) - assert.Equal(t, int(maxResults), 5) + require.NoError(t, err) + assert.Equal(t, 5, int(maxResults)) assert.Len(t, statuses, 5) assert.Equal(t, "ci/awesomeness", statuses[0].Context) @@ -60,8 +61,8 @@ func TestGetCommitStatuses(t *testing.T) { RepoID: repo1.ID, SHA: sha1, }) - assert.NoError(t, err) - assert.Equal(t, int(maxResults), 5) + require.NoError(t, err) + assert.Equal(t, 5, int(maxResults)) assert.Empty(t, statuses) } @@ -189,16 +190,16 @@ func Test_CalcCommitStatus(t *testing.T) { } func TestFindRepoRecentCommitStatusContexts(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo2) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() commit, err := gitRepo.GetBranchCommit(repo2.DefaultBranch) - assert.NoError(t, err) + require.NoError(t, err) defer func() { _, err := db.DeleteByBean(db.DefaultContext, &git_model.CommitStatus{ @@ -206,7 +207,7 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) { CreatorID: user2.ID, SHA: commit.ID.String(), }) - assert.NoError(t, err) + require.NoError(t, err) }() err = git_model.NewCommitStatus(db.DefaultContext, git_model.NewCommitStatusOptions{ @@ -219,7 +220,7 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) { Context: "compliance/lint-backend", }, }) - assert.NoError(t, err) + require.NoError(t, err) err = git_model.NewCommitStatus(db.DefaultContext, git_model.NewCommitStatusOptions{ Repo: repo2, @@ -231,10 +232,10 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) { Context: "compliance/lint-backend", }, }) - assert.NoError(t, err) + require.NoError(t, err) contexts, err := git_model.FindRepoRecentCommitStatusContexts(db.DefaultContext, repo2.ID, time.Hour) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, contexts, 1) { assert.Equal(t, "compliance/lint-backend", contexts[0]) } diff --git a/models/git/lfs_test.go b/models/git/lfs_test.go index 565b2e9303..afb73ecf4e 100644 --- a/models/git/lfs_test.go +++ b/models/git/lfs_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIterateRepositoryIDsWithLFSMetaObjects(t *testing.T) { @@ -24,7 +25,7 @@ func TestIterateRepositoryIDsWithLFSMetaObjects(t *testing.T) { Dirs: []string{"models/git/TestIterateRepositoryIDsWithLFSMetaObjects/"}, }, )() - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) type repocount struct { repoid int64 @@ -40,7 +41,7 @@ func TestIterateRepositoryIDsWithLFSMetaObjects(t *testing.T) { cases = append(cases, repocount{repoID, count}) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expected, cases) }) @@ -52,13 +53,13 @@ func TestIterateRepositoryIDsWithLFSMetaObjects(t *testing.T) { cases = append(cases, repocount{repoID, count}) return nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expected, cases) }) } func TestIterateLFSMetaObjectsForRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) expectedIDs := []int64{1, 2, 3, 4} @@ -70,7 +71,7 @@ func TestIterateLFSMetaObjectsForRepo(t *testing.T) { actualIDs = append(actualIDs, lo.ID) return nil }, &IterateLFSMetaObjectsForRepoOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expectedIDs, actualIDs) }) @@ -82,7 +83,7 @@ func TestIterateLFSMetaObjectsForRepo(t *testing.T) { actualIDs = append(actualIDs, lo.ID) return nil }, &IterateLFSMetaObjectsForRepoOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expectedIDs, actualIDs) t.Run("Batch handles updates", func(t *testing.T) { @@ -91,10 +92,10 @@ func TestIterateLFSMetaObjectsForRepo(t *testing.T) { err := IterateLFSMetaObjectsForRepo(db.DefaultContext, 54, func(ctx context.Context, lo *LFSMetaObject) error { actualIDs = append(actualIDs, lo.ID) _, err := db.DeleteByID[LFSMetaObject](ctx, lo.ID) - assert.NoError(t, err) + require.NoError(t, err) return nil }, &IterateLFSMetaObjectsForRepoOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expectedIDs, actualIDs) }) }) diff --git a/models/git/protected_banch_list_test.go b/models/git/protected_banch_list_test.go index 4bb3136d58..09319d21a8 100644 --- a/models/git/protected_banch_list_test.go +++ b/models/git/protected_banch_list_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestBranchRuleMatchPriority(t *testing.T) { @@ -67,7 +68,7 @@ func TestBranchRuleMatchPriority(t *testing.T) { matchedPB := pbs.GetFirstMatched(kase.BranchName) if matchedPB == nil { if kase.ExpectedMatchIdx >= 0 { - assert.Error(t, fmt.Errorf("no matched rules but expected %s[%d]", kase.Rules[kase.ExpectedMatchIdx], kase.ExpectedMatchIdx)) + require.Error(t, fmt.Errorf("no matched rules but expected %s[%d]", kase.Rules[kase.ExpectedMatchIdx], kase.ExpectedMatchIdx)) } } else { assert.EqualValues(t, kase.Rules[kase.ExpectedMatchIdx], matchedPB.RuleName) diff --git a/models/git/protected_tag_test.go b/models/git/protected_tag_test.go index 164c33e28f..796e1594b9 100644 --- a/models/git/protected_tag_test.go +++ b/models/git/protected_tag_test.go @@ -11,36 +11,37 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIsUserAllowed(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pt := &git_model.ProtectedTag{} allowed, err := git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, allowed) pt = &git_model.ProtectedTag{ AllowlistUserIDs: []int64{1}, } allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, allowed) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, allowed) pt = &git_model.ProtectedTag{ AllowlistTeamIDs: []int64{1}, } allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, allowed) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, allowed) pt = &git_model.ProtectedTag{ @@ -48,11 +49,11 @@ func TestIsUserAllowed(t *testing.T) { AllowlistTeamIDs: []int64{1}, } allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, allowed) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, allowed) } @@ -136,7 +137,7 @@ func TestIsUserAllowedToControlTag(t *testing.T) { for n, c := range cases { isAllowed, err := git_model.IsUserAllowedToControlTag(db.DefaultContext, protectedTags, c.name, c.userid) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n) } }) @@ -158,7 +159,7 @@ func TestIsUserAllowedToControlTag(t *testing.T) { for n, c := range cases { isAllowed, err := git_model.IsUserAllowedToControlTag(db.DefaultContext, protectedTags, c.name, c.userid) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n) } }) diff --git a/models/issues/assignees_test.go b/models/issues/assignees_test.go index 2c33efd99e..47fb81a237 100644 --- a/models/issues/assignees_test.go +++ b/models/issues/assignees_test.go @@ -12,42 +12,43 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUpdateAssignee(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // Fake issue with assignees issue, err := issues_model.GetIssueByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) err = issue.LoadAttributes(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) // Assign multiple users user2, err := user_model.GetUserByID(db.DefaultContext, 2) - assert.NoError(t, err) + require.NoError(t, err) _, _, err = issues_model.ToggleIssueAssignee(db.DefaultContext, issue, &user_model.User{ID: 1}, user2.ID) - assert.NoError(t, err) + require.NoError(t, err) org3, err := user_model.GetUserByID(db.DefaultContext, 3) - assert.NoError(t, err) + require.NoError(t, err) _, _, err = issues_model.ToggleIssueAssignee(db.DefaultContext, issue, &user_model.User{ID: 1}, org3.ID) - assert.NoError(t, err) + require.NoError(t, err) user1, err := user_model.GetUserByID(db.DefaultContext, 1) // This user is already assigned (see the definition in fixtures), so running UpdateAssignee should unassign him - assert.NoError(t, err) + require.NoError(t, err) _, _, err = issues_model.ToggleIssueAssignee(db.DefaultContext, issue, &user_model.User{ID: 1}, user1.ID) - assert.NoError(t, err) + require.NoError(t, err) // Check if he got removed isAssigned, err := issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user1) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isAssigned) // Check if they're all there err = issue.LoadAssignees(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) var expectedAssignees []*user_model.User expectedAssignees = append(expectedAssignees, user2, org3) @@ -58,37 +59,37 @@ func TestUpdateAssignee(t *testing.T) { // Check if the user is assigned isAssigned, err = issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user2) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isAssigned) // This user should not be assigned isAssigned, err = issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, &user_model.User{ID: 4}) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isAssigned) } func TestMakeIDsFromAPIAssigneesToAdd(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) _ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) _ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) IDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{""}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []int64{}, IDs) _, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{"none_existing_user"}) - assert.Error(t, err) + require.Error(t, err) IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user1", []string{"user1"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []int64{1}, IDs) IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user2", []string{""}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []int64{2}, IDs) IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{"user1", "user2"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []int64{1, 2}, IDs) } diff --git a/models/issues/comment_list_test.go b/models/issues/comment_list_test.go index 66037d7358..5ad1cd19c9 100644 --- a/models/issues/comment_list_test.go +++ b/models/issues/comment_list_test.go @@ -16,7 +16,7 @@ import ( ) func TestCommentListLoadUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &Issue{}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) @@ -78,7 +78,7 @@ func TestCommentListLoadUser(t *testing.T) { comment.AssigneeID = testCase.assignee comment.Assignee = nil - assert.NoError(t, list.loadAssignees(db.DefaultContext)) + require.NoError(t, list.loadAssignees(db.DefaultContext)) require.NotNil(t, comment.Assignee) assert.Equal(t, testCase.user.ID, comment.Assignee.ID) }) diff --git a/models/issues/comment_test.go b/models/issues/comment_test.go index e7ceee4298..f7088cc96c 100644 --- a/models/issues/comment_test.go +++ b/models/issues/comment_test.go @@ -15,10 +15,11 @@ import ( "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCreateComment(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) @@ -32,7 +33,7 @@ func TestCreateComment(t *testing.T) { Issue: issue, Content: "Hello", }) - assert.NoError(t, err) + require.NoError(t, err) then := time.Now().Unix() assert.EqualValues(t, issues_model.CommentTypeComment, comment.Type) @@ -47,12 +48,12 @@ func TestCreateComment(t *testing.T) { } func TestFetchCodeConversations(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) res, err := issues_model.FetchCodeConversations(db.DefaultContext, issue, user, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, res, "README.md") assert.Contains(t, res["README.md"], int64(4)) assert.Len(t, res["README.md"][4], 1) @@ -60,12 +61,12 @@ func TestFetchCodeConversations(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) res, err = issues_model.FetchCodeConversations(db.DefaultContext, issue, user2, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, res, 1) } func TestAsCommentType(t *testing.T) { - assert.Equal(t, issues_model.CommentType(0), issues_model.CommentTypeComment) + assert.Equal(t, issues_model.CommentTypeComment, issues_model.CommentType(0)) assert.Equal(t, issues_model.CommentTypeUndefined, issues_model.AsCommentType("")) assert.Equal(t, issues_model.CommentTypeUndefined, issues_model.AsCommentType("nonsense")) assert.Equal(t, issues_model.CommentTypeComment, issues_model.AsCommentType("comment")) @@ -73,7 +74,7 @@ func TestAsCommentType(t *testing.T) { } func TestMigrate_InsertIssueComments(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) _ = issue.LoadRepo(db.DefaultContext) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) @@ -91,7 +92,7 @@ func TestMigrate_InsertIssueComments(t *testing.T) { } err := issues_model.InsertIssueComments(db.DefaultContext, []*issues_model.Comment{comment}) - assert.NoError(t, err) + require.NoError(t, err) issueModified := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) assert.EqualValues(t, issue.NumComments+1, issueModified.NumComments) @@ -100,7 +101,7 @@ func TestMigrate_InsertIssueComments(t *testing.T) { } func TestUpdateCommentsMigrationsByType(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) @@ -115,9 +116,9 @@ func TestUpdateCommentsMigrationsByType(t *testing.T) { comment.OriginalAuthorID = 1 comment.PosterID = 0 _, err := db.GetEngine(db.DefaultContext).ID(comment.ID).Cols("original_author", "original_author_id", "poster_id").Update(comment) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, issues_model.UpdateCommentsMigrationsByType(db.DefaultContext, structs.GiteaService, "1", 513)) + require.NoError(t, issues_model.UpdateCommentsMigrationsByType(db.DefaultContext, structs.GiteaService, "1", 513)) comment = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 1, IssueID: issue.ID}) assert.Empty(t, comment.OriginalAuthor) diff --git a/models/issues/content_history_test.go b/models/issues/content_history_test.go index 89d77a1df3..dde6f195bc 100644 --- a/models/issues/content_history_test.go +++ b/models/issues/content_history_test.go @@ -12,10 +12,11 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestContentHistory(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) dbCtx := db.DefaultContext timeStampNow := timeutil.TimeStampNow() @@ -80,7 +81,7 @@ func TestContentHistory(t *testing.T) { } func TestHasIssueContentHistory(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // Ensures that comment_id is into taken account even if it's zero. _ = issues_model.SaveIssueContentHistory(db.DefaultContext, 1, 11, 100, timeutil.TimeStampNow(), "c-a", true) diff --git a/models/issues/dependency_test.go b/models/issues/dependency_test.go index 6eed483cc9..1e73c581ee 100644 --- a/models/issues/dependency_test.go +++ b/models/issues/dependency_test.go @@ -12,51 +12,52 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCreateIssueDependency(t *testing.T) { // Prepare - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1, err := user_model.GetUserByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2) - assert.NoError(t, err) + require.NoError(t, err) // Create a dependency and check if it was successful err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2) - assert.NoError(t, err) + require.NoError(t, err) // Do it again to see if it will check if the dependency already exists err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrDependencyExists(err)) // Check for circular dependencies err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue2, issue1) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrCircularDependency(err)) _ = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{Type: issues_model.CommentTypeAddDependency, PosterID: user1.ID, IssueID: issue1.ID}) // Check if dependencies left is correct left, err := issues_model.IssueNoDependenciesLeft(db.DefaultContext, issue1) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, left) // Close #2 and check again _, err = issues_model.ChangeIssueStatus(db.DefaultContext, issue2, user1, true) - assert.NoError(t, err) + require.NoError(t, err) left, err = issues_model.IssueNoDependenciesLeft(db.DefaultContext, issue1) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, left) // Test removing the dependency err = issues_model.RemoveIssueDependency(db.DefaultContext, user1, issue1, issue2, issues_model.DependencyTypeBlockedBy) - assert.NoError(t, err) + require.NoError(t, err) } diff --git a/models/issues/issue_index_test.go b/models/issues/issue_index_test.go index 9937aac70e..eb79a0806c 100644 --- a/models/issues/issue_index_test.go +++ b/models/issues/issue_index_test.go @@ -12,27 +12,28 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetMaxIssueIndexForRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) maxPR, err := issues_model.GetMaxIssueIndexForRepo(db.DefaultContext, repo.ID) - assert.NoError(t, err) + require.NoError(t, err) issue := testCreateIssue(t, repo.ID, repo.OwnerID, "title1", "content1", false) assert.Greater(t, issue.Index, maxPR) maxPR, err = issues_model.GetMaxIssueIndexForRepo(db.DefaultContext, repo.ID) - assert.NoError(t, err) + require.NoError(t, err) pull := testCreateIssue(t, repo.ID, repo.OwnerID, "title2", "content2", true) assert.Greater(t, pull.Index, maxPR) maxPR, err = issues_model.GetMaxIssueIndexForRepo(db.DefaultContext, repo.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, maxPR, pull.Index) } diff --git a/models/issues/issue_label_test.go b/models/issues/issue_label_test.go index 0470b99e24..b6b39d683d 100644 --- a/models/issues/issue_label_test.go +++ b/models/issues/issue_label_test.go @@ -12,17 +12,18 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewIssueLabelsScope(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 18}) label1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 7}) label2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{label1, label2}, doer)) + require.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{label1, label2}, doer)) assert.Len(t, issue.Labels, 1) assert.Equal(t, label2.ID, issue.Labels[0].ID) diff --git a/models/issues/issue_list_test.go b/models/issues/issue_list_test.go index 50bbd5c667..32cc0fe423 100644 --- a/models/issues/issue_list_test.go +++ b/models/issues/issue_list_test.go @@ -17,7 +17,7 @@ import ( ) func TestIssueList_LoadRepositories(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issueList := issues_model.IssueList{ unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}), @@ -26,7 +26,7 @@ func TestIssueList_LoadRepositories(t *testing.T) { } repos, err := issueList.LoadRepositories(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, repos, 2) for _, issue := range issueList { assert.EqualValues(t, issue.RepoID, issue.Repo.ID) @@ -34,14 +34,14 @@ func TestIssueList_LoadRepositories(t *testing.T) { } func TestIssueList_LoadAttributes(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) setting.Service.EnableTimetracking = true issueList := issues_model.IssueList{ unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}), unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}), } - assert.NoError(t, issueList.LoadAttributes(db.DefaultContext)) + require.NoError(t, issueList.LoadAttributes(db.DefaultContext)) for _, issue := range issueList { assert.EqualValues(t, issue.RepoID, issue.Repo.ID) for _, label := range issue.Labels { @@ -75,14 +75,14 @@ func TestIssueList_LoadAttributes(t *testing.T) { } } - assert.NoError(t, issueList.LoadIsRead(db.DefaultContext, 1)) + require.NoError(t, issueList.LoadIsRead(db.DefaultContext, 1)) for _, issue := range issueList { assert.Equal(t, issue.ID == 1, issue.IsRead, "unexpected is_read value for issue[%d]", issue.ID) } } func TestIssueListLoadUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -121,7 +121,7 @@ func TestIssueListLoadUser(t *testing.T) { issue.PosterID = testCase.poster issue.Poster = nil - assert.NoError(t, list.LoadPosters(db.DefaultContext)) + require.NoError(t, list.LoadPosters(db.DefaultContext)) require.NotNil(t, issue.Poster) assert.Equal(t, testCase.user.ID, issue.Poster.ID) }) diff --git a/models/issues/issue_test.go b/models/issues/issue_test.go index bdab6bddc4..580be9663b 100644 --- a/models/issues/issue_test.go +++ b/models/issues/issue_test.go @@ -19,11 +19,12 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/builder" ) func TestIssue_ReplaceLabels(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(issueID int64, labelIDs, expectedLabelIDs []int64) { issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issueID}) @@ -34,7 +35,7 @@ func TestIssue_ReplaceLabels(t *testing.T) { for i, labelID := range labelIDs { labels[i] = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID, RepoID: repo.ID}) } - assert.NoError(t, issues_model.ReplaceIssueLabels(db.DefaultContext, issue, labels, doer)) + require.NoError(t, issues_model.ReplaceIssueLabels(db.DefaultContext, issue, labels, doer)) unittest.AssertCount(t, &issues_model.IssueLabel{IssueID: issueID}, len(expectedLabelIDs)) for _, labelID := range expectedLabelIDs { unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issueID, LabelID: labelID}) @@ -52,27 +53,27 @@ func TestIssue_ReplaceLabels(t *testing.T) { } func Test_GetIssueIDsByRepoID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ids, err := issues_model.GetIssueIDsByRepoID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, ids, 5) } func TestIssueAPIURL(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) err := issue.LoadAttributes(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/issues/1", issue.APIURL(db.DefaultContext)) } func TestGetIssuesByIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(expectedIssueIDs, nonExistentIssueIDs []int64) { issues, err := issues_model.GetIssuesByIDs(db.DefaultContext, append(expectedIssueIDs, nonExistentIssueIDs...), true) - assert.NoError(t, err) + require.NoError(t, err) actualIssueIDs := make([]int64, len(issues)) for i, issue := range issues { actualIssueIDs[i] = issue.ID @@ -85,21 +86,22 @@ func TestGetIssuesByIDs(t *testing.T) { } func TestGetParticipantIDsByIssue(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) checkParticipants := func(issueID int64, userIDs []int) { issue, err := issues_model.GetIssueByID(db.DefaultContext, issueID) - assert.NoError(t, err) + require.NoError(t, err) + participants, err := issue.GetParticipantIDsByIssue(db.DefaultContext) - if assert.NoError(t, err) { - participantsIDs := make([]int, len(participants)) - for i, uid := range participants { - participantsIDs[i] = int(uid) - } - sort.Ints(participantsIDs) - sort.Ints(userIDs) - assert.Equal(t, userIDs, participantsIDs) + require.NoError(t, err) + + participantsIDs := make([]int, len(participants)) + for i, uid := range participants { + participantsIDs[i] = int(uid) } + sort.Ints(participantsIDs) + sort.Ints(userIDs) + assert.Equal(t, userIDs, participantsIDs) } // User 1 is issue1 poster (see fixtures/issue.yml) @@ -119,16 +121,16 @@ func TestIssue_ClearLabels(t *testing.T) { {3, 2}, // pull-request, has no labels } for _, test := range tests { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID}) - assert.NoError(t, issues_model.ClearIssueLabels(db.DefaultContext, issue, doer)) + require.NoError(t, issues_model.ClearIssueLabels(db.DefaultContext, issue, doer)) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: test.issueID}) } } func TestUpdateIssueCols(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{}) const newTitle = "New Title for unit test" @@ -138,7 +140,7 @@ func TestUpdateIssueCols(t *testing.T) { issue.Content = "This should have no effect" now := time.Now().Unix() - assert.NoError(t, issues_model.UpdateIssueCols(db.DefaultContext, issue, "name")) + require.NoError(t, issues_model.UpdateIssueCols(db.DefaultContext, issue, "name")) then := time.Now().Unix() updatedIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issue.ID}) @@ -148,7 +150,7 @@ func TestUpdateIssueCols(t *testing.T) { } func TestIssues(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) for _, test := range []struct { Opts issues_model.IssuesOptions ExpectedIssueIDs []int64 @@ -212,7 +214,7 @@ func TestIssues(t *testing.T) { }, } { issues, err := issues_model.Issues(db.DefaultContext, &test.Opts) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, issues, len(test.ExpectedIssueIDs)) { for i, issue := range issues { assert.EqualValues(t, test.ExpectedIssueIDs[i], issue.ID) @@ -222,10 +224,10 @@ func TestIssues(t *testing.T) { } func TestIssue_loadTotalTimes(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ms, err := issues_model.GetIssueByID(db.DefaultContext, 2) - assert.NoError(t, err) - assert.NoError(t, ms.LoadTotalTimes(db.DefaultContext)) + require.NoError(t, err) + require.NoError(t, ms.LoadTotalTimes(db.DefaultContext)) assert.Equal(t, int64(3682), ms.TotalTrackedTime) } @@ -243,10 +245,10 @@ func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *is Content: content, } err := issues_model.NewIssue(db.DefaultContext, repo, &issue, nil, nil) - assert.NoError(t, err) + require.NoError(t, err) has, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Get(&newIssue) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, has) assert.EqualValues(t, issue.Title, newIssue.Title) assert.EqualValues(t, issue.Content, newIssue.Content) @@ -258,20 +260,20 @@ func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *is } func TestIssue_InsertIssue(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.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) _, err := db.DeleteByID[issues_model.Issue](db.DefaultContext, issue.ID) - assert.NoError(t, err) + require.NoError(t, err) issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7) _, err = db.DeleteByID[issues_model.Issue](db.DefaultContext, issue.ID) - assert.NoError(t, err) + require.NoError(t, err) } func TestIssue_ResolveMentions(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(owner, repo, doer string, mentions []string, expected []int64) { o := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: owner}) @@ -279,7 +281,7 @@ func TestIssue_ResolveMentions(t *testing.T) { issue := &issues_model.Issue{RepoID: r.ID} d := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: doer}) resolved, err := issues_model.ResolveIssueMentionsByVisibility(db.DefaultContext, issue, d, mentions) - assert.NoError(t, err) + require.NoError(t, err) ids := make([]int64, len(resolved)) for i, user := range resolved { ids[i] = user.ID @@ -305,21 +307,33 @@ func TestIssue_ResolveMentions(t *testing.T) { } func TestResourceIndex(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) + + beforeCount, err := issues_model.CountIssues(context.Background(), &issues_model.IssuesOptions{}) + require.NoError(t, err) var wg sync.WaitGroup for i := 0; i < 100; i++ { wg.Add(1) - go func(i int) { + t.Run(fmt.Sprintf("issue %d", i+1), func(t *testing.T) { + t.Parallel() testInsertIssue(t, fmt.Sprintf("issue %d", i+1), "my issue", 0) wg.Done() - }(i) + }) } - wg.Wait() + + t.Run("Check the count", func(t *testing.T) { + t.Parallel() + + wg.Wait() + afterCount, err := issues_model.CountIssues(context.Background(), &issues_model.IssuesOptions{}) + require.NoError(t, err) + assert.EqualValues(t, 100, afterCount-beforeCount) + }) } func TestCorrectIssueStats(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // Because the condition is to have chunked database look-ups, // We have to more issues than `maxQueryParameters`, we will insert. @@ -355,7 +369,7 @@ func TestCorrectIssueStats(t *testing.T) { } // Just to be sure. - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, issueAmount, total) // Now we will call the GetIssueStats with these IDs and if working, @@ -366,39 +380,39 @@ func TestCorrectIssueStats(t *testing.T) { }) // Now check the values. - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, issueStats.OpenCount, issueAmount) } func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) miles := issues_model.MilestoneList{ unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}), } - assert.NoError(t, miles.LoadTotalTrackedTimes(db.DefaultContext)) + require.NoError(t, miles.LoadTotalTrackedTimes(db.DefaultContext)) assert.Equal(t, int64(3682), miles[0].TotalTrackedTime) } func TestLoadTotalTrackedTime(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) - assert.NoError(t, milestone.LoadTotalTrackedTime(db.DefaultContext)) + require.NoError(t, milestone.LoadTotalTrackedTime(db.DefaultContext)) assert.Equal(t, int64(3682), milestone.TotalTrackedTime) } func TestCountIssues(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) count, err := issues_model.CountIssues(db.DefaultContext, &issues_model.IssuesOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 22, count) } func TestIssueLoadAttributes(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) setting.Service.EnableTimetracking = true issueList := issues_model.IssueList{ @@ -407,7 +421,7 @@ func TestIssueLoadAttributes(t *testing.T) { } for _, issue := range issueList { - assert.NoError(t, issue.LoadAttributes(db.DefaultContext)) + require.NoError(t, issue.LoadAttributes(db.DefaultContext)) assert.EqualValues(t, issue.RepoID, issue.Repo.ID) for _, label := range issue.Labels { assert.EqualValues(t, issue.RepoID, label.RepoID) @@ -442,13 +456,13 @@ func TestIssueLoadAttributes(t *testing.T) { } func assertCreateIssues(t *testing.T, isPull bool) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) reponame := "repo1" repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) - assert.EqualValues(t, milestone.ID, 1) + assert.EqualValues(t, 1, milestone.ID) reaction := &issues_model.Reaction{ Type: "heart", UserID: owner.ID, @@ -469,7 +483,7 @@ func assertCreateIssues(t *testing.T, isPull bool) { Reactions: []*issues_model.Reaction{reaction}, } err := issues_model.InsertIssues(db.DefaultContext, is) - assert.NoError(t, err) + require.NoError(t, err) i := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: title}) unittest.AssertExistsAndLoadBean(t, &issues_model.Reaction{Type: "heart", UserID: owner.ID, IssueID: i.ID}) diff --git a/models/issues/issue_user_test.go b/models/issues/issue_user_test.go index ce47adb53a..e059e43e8b 100644 --- a/models/issues/issue_user_test.go +++ b/models/issues/issue_user_test.go @@ -11,11 +11,11 @@ import ( repo_model "code.gitea.io/gitea/models/repo" "code.gitea.io/gitea/models/unittest" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_NewIssueUsers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) newIssue := &issues_model.Issue{ @@ -29,7 +29,7 @@ func Test_NewIssueUsers(t *testing.T) { // artificially insert new issue unittest.AssertSuccessfulInsert(t, newIssue) - assert.NoError(t, issues_model.NewIssueUsers(db.DefaultContext, repo, newIssue)) + require.NoError(t, issues_model.NewIssueUsers(db.DefaultContext, repo, newIssue)) // issue_user table should now have entries for new issue unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID}) @@ -37,24 +37,24 @@ func Test_NewIssueUsers(t *testing.T) { } func TestUpdateIssueUserByRead(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) - assert.NoError(t, issues_model.UpdateIssueUserByRead(db.DefaultContext, 4, issue.ID)) + require.NoError(t, issues_model.UpdateIssueUserByRead(db.DefaultContext, 4, issue.ID)) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1") - assert.NoError(t, issues_model.UpdateIssueUserByRead(db.DefaultContext, 4, issue.ID)) + require.NoError(t, issues_model.UpdateIssueUserByRead(db.DefaultContext, 4, issue.ID)) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: 4}, "is_read=1") - assert.NoError(t, issues_model.UpdateIssueUserByRead(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) + require.NoError(t, issues_model.UpdateIssueUserByRead(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) } func TestUpdateIssueUsersByMentions(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) uids := []int64{2, 5} - assert.NoError(t, issues_model.UpdateIssueUsersByMentions(db.DefaultContext, issue.ID, uids)) + require.NoError(t, issues_model.UpdateIssueUsersByMentions(db.DefaultContext, issue.ID, uids)) for _, uid := range uids { unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1") } diff --git a/models/issues/issue_watch_test.go b/models/issues/issue_watch_test.go index d4ce8d8d3d..573215d577 100644 --- a/models/issues/issue_watch_test.go +++ b/models/issues/issue_watch_test.go @@ -11,57 +11,58 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCreateOrUpdateIssueWatch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) - assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(db.DefaultContext, 3, 1, true)) + require.NoError(t, issues_model.CreateOrUpdateIssueWatch(db.DefaultContext, 3, 1, true)) iw := unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 3, IssueID: 1}) assert.True(t, iw.IsWatching) - assert.NoError(t, issues_model.CreateOrUpdateIssueWatch(db.DefaultContext, 1, 1, false)) + require.NoError(t, issues_model.CreateOrUpdateIssueWatch(db.DefaultContext, 1, 1, false)) iw = unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 1, IssueID: 1}) assert.False(t, iw.IsWatching) } func TestGetIssueWatch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) _, exists, err := issues_model.GetIssueWatch(db.DefaultContext, 9, 1) assert.True(t, exists) - assert.NoError(t, err) + require.NoError(t, err) iw, exists, err := issues_model.GetIssueWatch(db.DefaultContext, 2, 2) assert.True(t, exists) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, iw.IsWatching) _, exists, err = issues_model.GetIssueWatch(db.DefaultContext, 3, 1) assert.False(t, exists) - assert.NoError(t, err) + require.NoError(t, err) } func TestGetIssueWatchers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) iws, err := issues_model.GetIssueWatchers(db.DefaultContext, 1, db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) // Watcher is inactive, thus 0 - assert.Len(t, iws, 0) + assert.Empty(t, iws) iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 2, db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) // Watcher is explicit not watching - assert.Len(t, iws, 0) + assert.Empty(t, iws) iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 5, db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) // Issue has no Watchers - assert.Len(t, iws, 0) + assert.Empty(t, iws) iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 7, db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) // Issue has one watcher assert.Len(t, iws, 1) } diff --git a/models/issues/issue_xref_test.go b/models/issues/issue_xref_test.go index f1b1bb2a6b..a24d1b04ee 100644 --- a/models/issues/issue_xref_test.go +++ b/models/issues/issue_xref_test.go @@ -15,10 +15,11 @@ import ( "code.gitea.io/gitea/modules/references" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestXRef_AddCrossReferences(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // Issue #1 to test against itarget := testCreateIssue(t, 1, 2, "title1", "content1", false) @@ -69,7 +70,7 @@ func TestXRef_AddCrossReferences(t *testing.T) { } func TestXRef_NeuterCrossReferences(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // Issue #1 to test against itarget := testCreateIssue(t, 1, 2, "title1", "content1", false) @@ -83,7 +84,7 @@ func TestXRef_NeuterCrossReferences(t *testing.T) { d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) i.Title = "title2, no mentions" - assert.NoError(t, issues_model.ChangeIssueTitle(db.DefaultContext, i, d, title)) + require.NoError(t, issues_model.ChangeIssueTitle(db.DefaultContext, i, d, title)) ref = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0}) assert.Equal(t, issues_model.CommentTypeIssueRef, ref.Type) @@ -91,7 +92,7 @@ func TestXRef_NeuterCrossReferences(t *testing.T) { } func TestXRef_ResolveCrossReferences(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -99,7 +100,7 @@ func TestXRef_ResolveCrossReferences(t *testing.T) { i2 := testCreateIssue(t, 1, 2, "title2", "content2", false) i3 := testCreateIssue(t, 1, 2, "title3", "content3", false) _, err := issues_model.ChangeIssueStatus(db.DefaultContext, i3, d, true) - assert.NoError(t, err) + require.NoError(t, err) pr := testCreatePR(t, 1, 2, "titlepr", fmt.Sprintf("closes #%d", i1.Index)) rp := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{IssueID: i1.ID, RefIssueID: pr.Issue.ID, RefCommentID: 0}) @@ -119,7 +120,7 @@ func TestXRef_ResolveCrossReferences(t *testing.T) { r4 := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{IssueID: i3.ID, RefIssueID: pr.Issue.ID, RefCommentID: c4.ID}) refs, err := pr.ResolveCrossReferences(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, refs, 3) assert.Equal(t, rp.ID, refs[0].ID, "bad ref rp: %+v", refs[0]) assert.Equal(t, r1.ID, refs[1].ID, "bad ref r1: %+v", refs[1]) @@ -131,11 +132,11 @@ func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispu d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer}) ctx, committer, err := db.TxContext(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) defer committer.Close() idx, err := db.GetNextResourceIndex(ctx, "issue_index", r.ID) - assert.NoError(t, err) + require.NoError(t, err) i := &issues_model.Issue{ RepoID: r.ID, PosterID: d.ID, @@ -150,11 +151,11 @@ func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispu Repo: r, Issue: i, }) - assert.NoError(t, err) + require.NoError(t, err) i, err = issues_model.GetIssueByID(ctx, i.ID) - assert.NoError(t, err) - assert.NoError(t, i.AddCrossReferences(ctx, d, false)) - assert.NoError(t, committer.Commit()) + require.NoError(t, err) + require.NoError(t, i.AddCrossReferences(ctx, d, false)) + require.NoError(t, committer.Commit()) return i } @@ -163,7 +164,7 @@ func testCreatePR(t *testing.T, repo, doer int64, title, content string) *issues d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer}) i := &issues_model.Issue{RepoID: r.ID, PosterID: d.ID, Poster: d, Title: title, Content: content, IsPull: true} pr := &issues_model.PullRequest{HeadRepoID: repo, BaseRepoID: repo, HeadBranch: "head", BaseBranch: "base", Status: issues_model.PullRequestStatusMergeable} - assert.NoError(t, issues_model.NewPullRequest(db.DefaultContext, r, i, nil, nil, pr)) + require.NoError(t, issues_model.NewPullRequest(db.DefaultContext, r, i, nil, nil, pr)) pr.Issue = i return pr } @@ -174,11 +175,11 @@ func testCreateComment(t *testing.T, doer, issue int64, content string) *issues_ c := &issues_model.Comment{Type: issues_model.CommentTypeComment, PosterID: doer, Poster: d, IssueID: issue, Issue: i, Content: content} ctx, committer, err := db.TxContext(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) defer committer.Close() err = db.Insert(ctx, c) - assert.NoError(t, err) - assert.NoError(t, c.AddCrossReferences(ctx, d, false)) - assert.NoError(t, committer.Commit()) + require.NoError(t, err) + require.NoError(t, c.AddCrossReferences(ctx, d, false)) + require.NoError(t, committer.Commit()) return c } diff --git a/models/issues/label_test.go b/models/issues/label_test.go index 9934429748..b03fc1cd20 100644 --- a/models/issues/label_test.go +++ b/models/issues/label_test.go @@ -14,17 +14,18 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLabel_CalOpenIssues(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) label.CalOpenIssues() assert.EqualValues(t, 2, label.NumOpenIssues) } func TestLabel_LoadSelectedLabelsAfterClick(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // Loading the label id:8 (scope/label2) which have a scope and an // exclusivity with id:7 (scope/label1) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8}) @@ -32,12 +33,12 @@ func TestLabel_LoadSelectedLabelsAfterClick(t *testing.T) { // First test : with negative and scope label.LoadSelectedLabelsAfterClick([]int64{1, -8}, []string{"", "scope"}) assert.Equal(t, "1", label.QueryString) - assert.Equal(t, true, label.IsSelected) + assert.True(t, label.IsSelected) // Second test : with duplicates label.LoadSelectedLabelsAfterClick([]int64{1, 7, 1, 7, 7}, []string{"", "scope", "", "scope", "scope"}) assert.Equal(t, "1,8", label.QueryString) - assert.Equal(t, false, label.IsSelected) + assert.False(t, label.IsSelected) // Third test : empty set label.LoadSelectedLabelsAfterClick([]int64{}, []string{}) @@ -46,7 +47,7 @@ func TestLabel_LoadSelectedLabelsAfterClick(t *testing.T) { } func TestLabel_ExclusiveScope(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 7}) assert.Equal(t, "scope", label.ExclusiveScope()) @@ -55,22 +56,22 @@ func TestLabel_ExclusiveScope(t *testing.T) { } func TestNewLabels(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) labels := []*issues_model.Label{ {RepoID: 2, Name: "labelName2", Color: "#123456"}, {RepoID: 3, Name: "labelName3", Color: "#123"}, {RepoID: 4, Name: "labelName4", Color: "ABCDEF"}, {RepoID: 5, Name: "labelName5", Color: "DEF"}, } - assert.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: ""})) - assert.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "#45G"})) - assert.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "#12345G"})) - assert.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "45G"})) - assert.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "12345G"})) + require.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: ""})) + require.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "#45G"})) + require.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "#12345G"})) + require.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "45G"})) + require.Error(t, issues_model.NewLabel(db.DefaultContext, &issues_model.Label{RepoID: 3, Name: "invalid Color", Color: "12345G"})) for _, label := range labels { unittest.AssertNotExistsBean(t, label) } - assert.NoError(t, issues_model.NewLabels(db.DefaultContext, labels...)) + require.NoError(t, issues_model.NewLabels(db.DefaultContext, labels...)) for _, label := range labels { unittest.AssertExistsAndLoadBean(t, label, unittest.Cond("id = ?", label.ID)) } @@ -78,9 +79,9 @@ func TestNewLabels(t *testing.T) { } func TestGetLabelByID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label, err := issues_model.GetLabelByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, label.ID) _, err = issues_model.GetLabelByID(db.DefaultContext, unittest.NonexistentID) @@ -88,9 +89,9 @@ func TestGetLabelByID(t *testing.T) { } func TestGetLabelInRepoByName(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label, err := issues_model.GetLabelInRepoByName(db.DefaultContext, 1, "label1") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, label.ID) assert.Equal(t, "label1", label.Name) @@ -102,9 +103,9 @@ func TestGetLabelInRepoByName(t *testing.T) { } func TestGetLabelInRepoByNames(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) labelIDs, err := issues_model.GetLabelIDsInRepoByNames(db.DefaultContext, 1, []string{"label1", "label2"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, labelIDs, 2) @@ -113,22 +114,22 @@ func TestGetLabelInRepoByNames(t *testing.T) { } func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // label3 doesn't exists.. See labels.yml labelIDs, err := issues_model.GetLabelIDsInRepoByNames(db.DefaultContext, 1, []string{"label1", "label2", "label3"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, labelIDs, 2) assert.Equal(t, int64(1), labelIDs[0]) assert.Equal(t, int64(2), labelIDs[1]) - assert.NoError(t, err) + require.NoError(t, err) } func TestGetLabelInRepoByID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label, err := issues_model.GetLabelInRepoByID(db.DefaultContext, 1, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, label.ID) _, err = issues_model.GetLabelInRepoByID(db.DefaultContext, 1, -1) @@ -139,9 +140,9 @@ func TestGetLabelInRepoByID(t *testing.T) { } func TestGetLabelsInRepoByIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) labels, err := issues_model.GetLabelsInRepoByIDs(db.DefaultContext, 1, []int64{1, 2, unittest.NonexistentID}) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, labels, 2) { assert.EqualValues(t, 1, labels[0].ID) assert.EqualValues(t, 2, labels[1].ID) @@ -149,10 +150,10 @@ func TestGetLabelsInRepoByIDs(t *testing.T) { } func TestGetLabelsByRepoID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) { labels, err := issues_model.GetLabelsByRepoID(db.DefaultContext, repoID, sortType, db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, labels, len(expectedIssueIDs)) for i, label := range labels { assert.EqualValues(t, expectedIssueIDs[i], label.ID) @@ -167,9 +168,9 @@ func TestGetLabelsByRepoID(t *testing.T) { // Org versions func TestGetLabelInOrgByName(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label, err := issues_model.GetLabelInOrgByName(db.DefaultContext, 3, "orglabel3") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, label.ID) assert.Equal(t, "orglabel3", label.Name) @@ -187,9 +188,9 @@ func TestGetLabelInOrgByName(t *testing.T) { } func TestGetLabelInOrgByID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label, err := issues_model.GetLabelInOrgByID(db.DefaultContext, 3, 3) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, label.ID) _, err = issues_model.GetLabelInOrgByID(db.DefaultContext, 3, -1) @@ -206,9 +207,9 @@ func TestGetLabelInOrgByID(t *testing.T) { } func TestGetLabelsInOrgByIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) labels, err := issues_model.GetLabelsInOrgByIDs(db.DefaultContext, 3, []int64{3, 4, unittest.NonexistentID}) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, labels, 2) { assert.EqualValues(t, 3, labels[0].ID) assert.EqualValues(t, 4, labels[1].ID) @@ -216,10 +217,10 @@ func TestGetLabelsInOrgByIDs(t *testing.T) { } func TestGetLabelsByOrgID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) { labels, err := issues_model.GetLabelsByOrgID(db.DefaultContext, orgID, sortType, db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, labels, len(expectedIssueIDs)) for i, label := range labels { assert.EqualValues(t, expectedIssueIDs[i], label.ID) @@ -241,20 +242,20 @@ func TestGetLabelsByOrgID(t *testing.T) { // func TestGetLabelsByIssueID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) labels, err := issues_model.GetLabelsByIssueID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, labels, 1) { assert.EqualValues(t, 1, labels[0].ID) } labels, err = issues_model.GetLabelsByIssueID(db.DefaultContext, unittest.NonexistentID) - assert.NoError(t, err) - assert.Len(t, labels, 0) + require.NoError(t, err) + assert.Empty(t, labels) } func TestUpdateLabel(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) // make sure update won't overwrite it update := &issues_model.Label{ @@ -267,45 +268,45 @@ func TestUpdateLabel(t *testing.T) { } label.Color = update.Color label.Name = update.Name - assert.NoError(t, issues_model.UpdateLabel(db.DefaultContext, update)) + require.NoError(t, issues_model.UpdateLabel(db.DefaultContext, update)) newLabel := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) assert.EqualValues(t, label.ID, newLabel.ID) assert.EqualValues(t, label.Color, newLabel.Color) assert.EqualValues(t, label.Name, newLabel.Name) assert.EqualValues(t, label.Description, newLabel.Description) - assert.EqualValues(t, newLabel.ArchivedUnix, 0) + assert.EqualValues(t, 0, newLabel.ArchivedUnix) unittest.CheckConsistencyFor(t, &issues_model.Label{}, &repo_model.Repository{}) } func TestDeleteLabel(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) - assert.NoError(t, issues_model.DeleteLabel(db.DefaultContext, label.RepoID, label.ID)) + require.NoError(t, issues_model.DeleteLabel(db.DefaultContext, label.RepoID, label.ID)) unittest.AssertNotExistsBean(t, &issues_model.Label{ID: label.ID, RepoID: label.RepoID}) - assert.NoError(t, issues_model.DeleteLabel(db.DefaultContext, label.RepoID, label.ID)) + require.NoError(t, issues_model.DeleteLabel(db.DefaultContext, label.RepoID, label.ID)) unittest.AssertNotExistsBean(t, &issues_model.Label{ID: label.ID}) - assert.NoError(t, issues_model.DeleteLabel(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) + require.NoError(t, issues_model.DeleteLabel(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) unittest.CheckConsistencyFor(t, &issues_model.Label{}, &repo_model.Repository{}) } func TestHasIssueLabel(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, issues_model.HasIssueLabel(db.DefaultContext, 1, 1)) assert.False(t, issues_model.HasIssueLabel(db.DefaultContext, 1, 2)) assert.False(t, issues_model.HasIssueLabel(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) } func TestNewIssueLabel(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 2}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // add new IssueLabel prevNumIssues := label.NumIssues - assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, label, doer)) + require.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, label, doer)) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ Type: issues_model.CommentTypeLabel, @@ -318,12 +319,12 @@ func TestNewIssueLabel(t *testing.T) { assert.EqualValues(t, prevNumIssues+1, label.NumIssues) // re-add existing IssueLabel - assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, label, doer)) + require.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, label, doer)) unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{}) } func TestNewIssueExclusiveLabel(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 18}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -332,32 +333,32 @@ func TestNewIssueExclusiveLabel(t *testing.T) { exclusiveLabelB := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8}) // coexisting regular and exclusive label - assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, otherLabel, doer)) - assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelA, doer)) + require.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, otherLabel, doer)) + require.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelA, doer)) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID}) // exclusive label replaces existing one - assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelB, doer)) + require.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelB, doer)) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID}) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID}) // exclusive label replaces existing one again - assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelA, doer)) + require.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, exclusiveLabelA, doer)) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID}) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID}) } func TestNewIssueLabels(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) label2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 2}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 5}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{label1, label2}, doer)) + require.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{label1, label2}, doer)) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: label1.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ Type: issues_model.CommentTypeLabel, @@ -375,13 +376,13 @@ func TestNewIssueLabels(t *testing.T) { assert.EqualValues(t, 1, label2.NumClosedIssues) // corner case: test empty slice - assert.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{}, doer)) + require.NoError(t, issues_model.NewIssueLabels(db.DefaultContext, issue, []*issues_model.Label{}, doer)) unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{}) } func TestDeleteIssueLabel(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(labelID, issueID, doerID int64) { label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issueID}) @@ -398,9 +399,9 @@ func TestDeleteIssueLabel(t *testing.T) { ctx, committer, err := db.TxContext(db.DefaultContext) defer committer.Close() - assert.NoError(t, err) - assert.NoError(t, issues_model.DeleteIssueLabel(ctx, issue, label, doer)) - assert.NoError(t, committer.Commit()) + require.NoError(t, err) + require.NoError(t, issues_model.DeleteIssueLabel(ctx, issue, label, doer)) + require.NoError(t, committer.Commit()) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issueID, LabelID: labelID}) unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ diff --git a/models/issues/main_test.go b/models/issues/main_test.go index ba83ca5552..baabd6646a 100644 --- a/models/issues/main_test.go +++ b/models/issues/main_test.go @@ -15,11 +15,11 @@ import ( _ "code.gitea.io/gitea/models/repo" _ "code.gitea.io/gitea/models/user" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestFixturesAreConsistent(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.PullRequest{}, diff --git a/models/issues/milestone_test.go b/models/issues/milestone_test.go index e5f6f15ca2..314cba308c 100644 --- a/models/issues/milestone_test.go +++ b/models/issues/milestone_test.go @@ -17,6 +17,7 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMilestone_State(t *testing.T) { @@ -25,10 +26,10 @@ func TestMilestone_State(t *testing.T) { } func TestGetMilestoneByRepoID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) milestone, err := issues_model.GetMilestoneByRepoID(db.DefaultContext, 1, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, milestone.ID) assert.EqualValues(t, 1, milestone.RepoID) @@ -37,7 +38,7 @@ func TestGetMilestoneByRepoID(t *testing.T) { } func TestGetMilestonesByRepoID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64, state api.StateType) { var isClosed optional.Option[bool] switch state { @@ -49,7 +50,7 @@ func TestGetMilestonesByRepoID(t *testing.T) { RepoID: repo.ID, IsClosed: isClosed, }) - assert.NoError(t, err) + require.NoError(t, err) var n int @@ -86,12 +87,12 @@ func TestGetMilestonesByRepoID(t *testing.T) { RepoID: unittest.NonexistentID, IsClosed: optional.Some(false), }) - assert.NoError(t, err) - assert.Len(t, milestones, 0) + require.NoError(t, err) + assert.Empty(t, milestones) } func TestGetMilestones(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) test := func(sortType string, sortCond func(*issues_model.Milestone) int) { for _, page := range []int{0, 1} { @@ -104,7 +105,7 @@ func TestGetMilestones(t *testing.T) { IsClosed: optional.Some(false), SortType: sortType, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, milestones, repo.NumMilestones-repo.NumClosedMilestones) values := make([]int, len(milestones)) for i, milestone := range milestones { @@ -122,7 +123,7 @@ func TestGetMilestones(t *testing.T) { Name: "", SortType: sortType, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, milestones, repo.NumClosedMilestones) values = make([]int, len(milestones)) for i, milestone := range milestones { @@ -152,13 +153,13 @@ func TestGetMilestones(t *testing.T) { } func TestCountRepoMilestones(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{ RepoID: repoID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, repo.NumMilestones, count) } test(1) @@ -168,19 +169,19 @@ func TestCountRepoMilestones(t *testing.T) { count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{ RepoID: unittest.NonexistentID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, count) } func TestCountRepoClosedMilestones(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{ RepoID: repoID, IsClosed: optional.Some(true), }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, repo.NumClosedMilestones, count) } test(1) @@ -191,12 +192,12 @@ func TestCountRepoClosedMilestones(t *testing.T) { RepoID: unittest.NonexistentID, IsClosed: optional.Some(true), }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, count) } func TestCountMilestonesByRepoIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) milestonesCount := func(repoID int64) (int, int) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) return repo.NumOpenMilestones, repo.NumClosedMilestones @@ -208,7 +209,7 @@ func TestCountMilestonesByRepoIDs(t *testing.T) { RepoIDs: []int64{1, 2}, IsClosed: optional.Some(false), }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, repo1OpenCount, openCounts[1]) assert.EqualValues(t, repo2OpenCount, openCounts[2]) @@ -217,13 +218,13 @@ func TestCountMilestonesByRepoIDs(t *testing.T) { RepoIDs: []int64{1, 2}, IsClosed: optional.Some(true), }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, repo1ClosedCount, closedCounts[1]) assert.EqualValues(t, repo2ClosedCount, closedCounts[2]) } func TestGetMilestonesByRepoIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) test := func(sortType string, sortCond func(*issues_model.Milestone) int) { @@ -237,7 +238,7 @@ func TestGetMilestonesByRepoIDs(t *testing.T) { IsClosed: optional.Some(false), SortType: sortType, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, openMilestones, repo1.NumOpenMilestones+repo2.NumOpenMilestones) values := make([]int, len(openMilestones)) for i, milestone := range openMilestones { @@ -255,7 +256,7 @@ func TestGetMilestonesByRepoIDs(t *testing.T) { IsClosed: optional.Some(true), SortType: sortType, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, closedMilestones, repo1.NumClosedMilestones+repo2.NumClosedMilestones) values = make([]int, len(closedMilestones)) for i, milestone := range closedMilestones { @@ -285,74 +286,74 @@ func TestGetMilestonesByRepoIDs(t *testing.T) { } func TestNewMilestone(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) milestone := &issues_model.Milestone{ RepoID: 1, Name: "milestoneName", Content: "milestoneContent", } - assert.NoError(t, issues_model.NewMilestone(db.DefaultContext, milestone)) + require.NoError(t, issues_model.NewMilestone(db.DefaultContext, milestone)) unittest.AssertExistsAndLoadBean(t, milestone) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{}) } func TestChangeMilestoneStatus(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) - assert.NoError(t, issues_model.ChangeMilestoneStatus(db.DefaultContext, milestone, true)) + require.NoError(t, issues_model.ChangeMilestoneStatus(db.DefaultContext, milestone, true)) unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}, "is_closed=1") unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{}) - assert.NoError(t, issues_model.ChangeMilestoneStatus(db.DefaultContext, milestone, false)) + require.NoError(t, issues_model.ChangeMilestoneStatus(db.DefaultContext, milestone, false)) unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}, "is_closed=0") unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{}) } func TestDeleteMilestoneByRepoID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - assert.NoError(t, issues_model.DeleteMilestoneByRepoID(db.DefaultContext, 1, 1)) + require.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, issues_model.DeleteMilestoneByRepoID(db.DefaultContext, 1, 1)) unittest.AssertNotExistsBean(t, &issues_model.Milestone{ID: 1}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: 1}) - assert.NoError(t, issues_model.DeleteMilestoneByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) + require.NoError(t, issues_model.DeleteMilestoneByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) } func TestUpdateMilestone(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) milestone.Name = " newMilestoneName " milestone.Content = "newMilestoneContent" - assert.NoError(t, issues_model.UpdateMilestone(db.DefaultContext, milestone, milestone.IsClosed)) + require.NoError(t, issues_model.UpdateMilestone(db.DefaultContext, milestone, milestone.IsClosed)) milestone = unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) assert.EqualValues(t, "newMilestoneName", milestone.Name) unittest.CheckConsistencyFor(t, &issues_model.Milestone{}) } func TestUpdateMilestoneCounters(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{MilestoneID: 1}, "is_closed=0") issue.IsClosed = true issue.ClosedUnix = timeutil.TimeStampNow() _, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) - assert.NoError(t, err) - assert.NoError(t, issues_model.UpdateMilestoneCounters(db.DefaultContext, issue.MilestoneID)) + require.NoError(t, err) + require.NoError(t, issues_model.UpdateMilestoneCounters(db.DefaultContext, issue.MilestoneID)) unittest.CheckConsistencyFor(t, &issues_model.Milestone{}) issue.IsClosed = false issue.ClosedUnix = 0 _, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) - assert.NoError(t, err) - assert.NoError(t, issues_model.UpdateMilestoneCounters(db.DefaultContext, issue.MilestoneID)) + require.NoError(t, err) + require.NoError(t, issues_model.UpdateMilestoneCounters(db.DefaultContext, issue.MilestoneID)) unittest.CheckConsistencyFor(t, &issues_model.Milestone{}) } func TestMigrate_InsertMilestones(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) reponame := "repo1" repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) name := "milestonetest1" @@ -361,7 +362,7 @@ func TestMigrate_InsertMilestones(t *testing.T) { Name: name, } err := issues_model.InsertMilestones(db.DefaultContext, ms) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, ms) repoModified := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID}) assert.EqualValues(t, repo.NumMilestones+1, repoModified.NumMilestones) diff --git a/models/issues/pull_test.go b/models/issues/pull_test.go index a9d4edc8a5..8e0c020ad9 100644 --- a/models/issues/pull_test.go +++ b/models/issues/pull_test.go @@ -17,42 +17,43 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPullRequest_LoadAttributes(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadAttributes(db.DefaultContext)) + require.NoError(t, pr.LoadAttributes(db.DefaultContext)) assert.NotNil(t, pr.Merger) assert.Equal(t, pr.MergerID, pr.Merger.ID) } func TestPullRequest_LoadIssue(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + require.NoError(t, pr.LoadIssue(db.DefaultContext)) assert.NotNil(t, pr.Issue) assert.Equal(t, int64(2), pr.Issue.ID) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + require.NoError(t, pr.LoadIssue(db.DefaultContext)) assert.NotNil(t, pr.Issue) assert.Equal(t, int64(2), pr.Issue.ID) } func TestPullRequest_LoadBaseRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) + require.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) assert.NotNil(t, pr.BaseRepo) assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) + require.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) assert.NotNil(t, pr.BaseRepo) assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID) } func TestPullRequest_LoadHeadRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadHeadRepo(db.DefaultContext)) + require.NoError(t, pr.LoadHeadRepo(db.DefaultContext)) assert.NotNil(t, pr.HeadRepo) assert.Equal(t, pr.HeadRepoID, pr.HeadRepo.ID) } @@ -62,7 +63,7 @@ func TestPullRequest_LoadHeadRepo(t *testing.T) { // TODO TestNewPullRequest func TestPullRequestsNewest(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{ ListOptions: db.ListOptions{ Page: 1, @@ -70,7 +71,7 @@ func TestPullRequestsNewest(t *testing.T) { State: "open", SortType: "newest", }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, count) if assert.Len(t, prs, 3) { assert.EqualValues(t, 5, prs[0].ID) @@ -80,35 +81,35 @@ func TestPullRequestsNewest(t *testing.T) { } func TestLoadRequestedReviewers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pull := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pull.LoadIssue(db.DefaultContext)) + require.NoError(t, pull.LoadIssue(db.DefaultContext)) issue := pull.Issue - assert.NoError(t, issue.LoadRepo(db.DefaultContext)) - assert.Len(t, pull.RequestedReviewers, 0) + require.NoError(t, issue.LoadRepo(db.DefaultContext)) + assert.Empty(t, pull.RequestedReviewers) user1, err := user_model.GetUserByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) comment, err := issues_model.AddReviewRequest(db.DefaultContext, issue, user1, &user_model.User{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, comment) - assert.NoError(t, pull.LoadRequestedReviewers(db.DefaultContext)) + require.NoError(t, pull.LoadRequestedReviewers(db.DefaultContext)) assert.Len(t, pull.RequestedReviewers, 1) comment, err = issues_model.RemoveReviewRequest(db.DefaultContext, issue, user1, &user_model.User{}) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, comment) pull.RequestedReviewers = nil - assert.NoError(t, pull.LoadRequestedReviewers(db.DefaultContext)) + require.NoError(t, pull.LoadRequestedReviewers(db.DefaultContext)) assert.Empty(t, pull.RequestedReviewers) } func TestPullRequestsOldest(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{ ListOptions: db.ListOptions{ Page: 1, @@ -116,7 +117,7 @@ func TestPullRequestsOldest(t *testing.T) { State: "open", SortType: "oldest", }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, count) if assert.Len(t, prs, 3) { assert.EqualValues(t, 1, prs[0].ID) @@ -126,32 +127,32 @@ func TestPullRequestsOldest(t *testing.T) { } func TestGetUnmergedPullRequest(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr, err := issues_model.GetUnmergedPullRequest(db.DefaultContext, 1, 1, "branch2", "master", issues_model.PullRequestFlowGithub) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), pr.ID) _, err = issues_model.GetUnmergedPullRequest(db.DefaultContext, 1, 9223372036854775807, "branch1", "master", issues_model.PullRequestFlowGithub) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrPullRequestNotExist(err)) } func TestHasUnmergedPullRequestsByHeadInfo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) exist, err := issues_model.HasUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "branch2") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exist) exist, err = issues_model.HasUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "not_exist_branch") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exist) } func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) prs, err := issues_model.GetUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "branch2") - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, prs, 1) for _, pr := range prs { assert.Equal(t, int64(1), pr.HeadRepoID) @@ -161,25 +162,25 @@ func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) { func TestGetUnmergedPullRequestsByHeadInfoMax(t *testing.T) { defer tests.AddFixtures("models/fixtures/TestGetUnmergedPullRequestsByHeadInfoMax/")() - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repoID := int64(1) olderThan := int64(0) // for NULL created field the olderThan condition is ignored prs, err := issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, "branch2") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), prs[0].HeadRepoID) // test for when the created field is set branch := "branchmax" prs, err = issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, branch) - assert.NoError(t, err) - assert.Len(t, prs, 0) + require.NoError(t, err) + assert.Empty(t, prs) olderThan = time.Now().UnixNano() - assert.NoError(t, err) + require.NoError(t, err) prs, err = issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, branch) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, prs, 1) for _, pr := range prs { assert.Equal(t, int64(1), pr.HeadRepoID) @@ -235,16 +236,16 @@ func TestGetUnmergedPullRequestsByHeadInfoMax(t *testing.T) { // expect no match _, err = db.GetEngine(db.DefaultContext).Exec(update, testCase.nomatch, testCase.id) - assert.NoError(t, err) + require.NoError(t, err) prs, err = issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, branch) - assert.NoError(t, err) - assert.Len(t, prs, 0) + require.NoError(t, err) + assert.Empty(t, prs) // expect one match _, err = db.GetEngine(db.DefaultContext).Exec(update, testCase.match, testCase.id) - assert.NoError(t, err) + require.NoError(t, err) prs, err = issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, branch) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, prs, 1) // identical to the known PR @@ -254,9 +255,9 @@ func TestGetUnmergedPullRequestsByHeadInfoMax(t *testing.T) { } func TestGetUnmergedPullRequestsByBaseInfo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) prs, err := issues_model.GetUnmergedPullRequestsByBaseInfo(db.DefaultContext, 1, "master") - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, prs, 1) pr := prs[0] assert.Equal(t, int64(2), pr.ID) @@ -265,46 +266,46 @@ func TestGetUnmergedPullRequestsByBaseInfo(t *testing.T) { } func TestGetPullRequestByIndex(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr, err := issues_model.GetPullRequestByIndex(db.DefaultContext, 1, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), pr.BaseRepoID) assert.Equal(t, int64(2), pr.Index) _, err = issues_model.GetPullRequestByIndex(db.DefaultContext, 9223372036854775807, 9223372036854775807) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrPullRequestNotExist(err)) _, err = issues_model.GetPullRequestByIndex(db.DefaultContext, 1, 0) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrPullRequestNotExist(err)) } func TestGetPullRequestByID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr, err := issues_model.GetPullRequestByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), pr.ID) assert.Equal(t, int64(2), pr.IssueID) _, err = issues_model.GetPullRequestByID(db.DefaultContext, 9223372036854775807) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrPullRequestNotExist(err)) } func TestGetPullRequestByIssueID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr, err := issues_model.GetPullRequestByIssueID(db.DefaultContext, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), pr.IssueID) _, err = issues_model.GetPullRequestByIssueID(db.DefaultContext, 9223372036854775807) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrPullRequestNotExist(err)) } func TestPullRequest_Update(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) pr.BaseBranch = "baseBranch" pr.HeadBranch = "headBranch" @@ -317,13 +318,13 @@ func TestPullRequest_Update(t *testing.T) { } func TestPullRequest_UpdateCols(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr := &issues_model.PullRequest{ ID: 1, BaseBranch: "baseBranch", HeadBranch: "headBranch", } - assert.NoError(t, pr.UpdateCols(db.DefaultContext, "head_branch")) + require.NoError(t, pr.UpdateCols(db.DefaultContext, "head_branch")) pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) assert.Equal(t, "master", pr.BaseBranch) @@ -332,25 +333,25 @@ func TestPullRequest_UpdateCols(t *testing.T) { } func TestPullRequestList_LoadAttributes(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) prs := []*issues_model.PullRequest{ unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}), unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}), } - assert.NoError(t, issues_model.PullRequestList(prs).LoadAttributes(db.DefaultContext)) + require.NoError(t, issues_model.PullRequestList(prs).LoadAttributes(db.DefaultContext)) for _, pr := range prs { assert.NotNil(t, pr.Issue) assert.Equal(t, pr.IssueID, pr.Issue.ID) } - assert.NoError(t, issues_model.PullRequestList([]*issues_model.PullRequest{}).LoadAttributes(db.DefaultContext)) + require.NoError(t, issues_model.PullRequestList([]*issues_model.PullRequest{}).LoadAttributes(db.DefaultContext)) } // TODO TestAddTestPullRequestTask func TestPullRequest_IsWorkInProgress(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) pr.LoadIssue(db.DefaultContext) @@ -365,7 +366,7 @@ func TestPullRequest_IsWorkInProgress(t *testing.T) { } func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) pr.LoadIssue(db.DefaultContext) @@ -381,23 +382,23 @@ func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) { } func TestDeleteOrphanedObjects(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) countBefore, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{}) - assert.NoError(t, err) + require.NoError(t, err) _, err = db.GetEngine(db.DefaultContext).Insert(&issues_model.PullRequest{IssueID: 1000}, &issues_model.PullRequest{IssueID: 1001}, &issues_model.PullRequest{IssueID: 1003}) - assert.NoError(t, err) + require.NoError(t, err) orphaned, err := db.CountOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, orphaned) err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id") - assert.NoError(t, err) + require.NoError(t, err) countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{}) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, countBefore, countAfter) } @@ -424,7 +425,7 @@ func TestParseCodeOwnersLine(t *testing.T) { } func TestGetApprovers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 5}) // Official reviews are already deduplicated. Allow unofficial reviews // to assert that there are no duplicated approvers. @@ -435,19 +436,19 @@ func TestGetApprovers(t *testing.T) { } func TestGetPullRequestByMergedCommit(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr, err := issues_model.GetPullRequestByMergedCommit(db.DefaultContext, 1, "1a8823cd1a9549fde083f992f6b9b87a7ab74fb3") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, pr.ID) _, err = issues_model.GetPullRequestByMergedCommit(db.DefaultContext, 0, "1a8823cd1a9549fde083f992f6b9b87a7ab74fb3") - assert.ErrorAs(t, err, &issues_model.ErrPullRequestNotExist{}) + require.ErrorAs(t, err, &issues_model.ErrPullRequestNotExist{}) _, err = issues_model.GetPullRequestByMergedCommit(db.DefaultContext, 1, "") - assert.ErrorAs(t, err, &issues_model.ErrPullRequestNotExist{}) + require.ErrorAs(t, err, &issues_model.ErrPullRequestNotExist{}) } func TestMigrate_InsertPullRequests(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) reponame := "repo1" repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) @@ -467,7 +468,7 @@ func TestMigrate_InsertPullRequests(t *testing.T) { } err := issues_model.InsertPullRequests(db.DefaultContext, p) - assert.NoError(t, err) + require.NoError(t, err) _ = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{IssueID: i.ID}) diff --git a/models/issues/reaction_test.go b/models/issues/reaction_test.go index eb59e36ecd..e02e6d7e0c 100644 --- a/models/issues/reaction_test.go +++ b/models/issues/reaction_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func addReaction(t *testing.T, doerID, issueID, commentID int64, content string) { @@ -27,12 +28,12 @@ func addReaction(t *testing.T, doerID, issueID, commentID int64, content string) Type: content, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, reaction) } func TestIssueAddReaction(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -44,7 +45,7 @@ func TestIssueAddReaction(t *testing.T) { } func TestIssueAddDuplicateReaction(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -57,7 +58,7 @@ func TestIssueAddDuplicateReaction(t *testing.T) { IssueID: issue1ID, Type: "heart", }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, issues_model.ErrReactionAlreadyExist{Reaction: "heart"}, err) existingR := unittest.AssertExistsAndLoadBean(t, &issues_model.Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1ID}) @@ -65,7 +66,7 @@ func TestIssueAddDuplicateReaction(t *testing.T) { } func TestIssueDeleteReaction(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -74,13 +75,13 @@ func TestIssueDeleteReaction(t *testing.T) { addReaction(t, user1.ID, issue1ID, 0, "heart") err := issues_model.DeleteIssueReaction(db.DefaultContext, user1.ID, issue1ID, "heart") - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertNotExistsBean(t, &issues_model.Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1ID}) } func TestIssueReactionCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) setting.UI.ReactionMaxUserNum = 2 @@ -104,10 +105,10 @@ func TestIssueReactionCount(t *testing.T) { reactionsList, _, err := issues_model.FindReactions(db.DefaultContext, issues_model.FindReactionsOptions{ IssueID: issueID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, reactionsList, 7) _, err = reactionsList.LoadUsers(db.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) reactions := reactionsList.GroupByType() assert.Len(t, reactions["heart"], 4) @@ -122,7 +123,7 @@ func TestIssueReactionCount(t *testing.T) { } func TestIssueCommentAddReaction(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -135,7 +136,7 @@ func TestIssueCommentAddReaction(t *testing.T) { } func TestIssueCommentDeleteReaction(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -154,7 +155,7 @@ func TestIssueCommentDeleteReaction(t *testing.T) { IssueID: issue1ID, CommentID: comment1ID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, reactionsList, 4) reactions := reactionsList.GroupByType() @@ -163,7 +164,7 @@ func TestIssueCommentDeleteReaction(t *testing.T) { } func TestIssueCommentReactionCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -171,7 +172,7 @@ func TestIssueCommentReactionCount(t *testing.T) { var comment1ID int64 = 1 addReaction(t, user1.ID, issue1ID, comment1ID, "heart") - assert.NoError(t, issues_model.DeleteCommentReaction(db.DefaultContext, user1.ID, issue1ID, comment1ID, "heart")) + require.NoError(t, issues_model.DeleteCommentReaction(db.DefaultContext, user1.ID, issue1ID, comment1ID, "heart")) unittest.AssertNotExistsBean(t, &issues_model.Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1ID, CommentID: comment1ID}) } diff --git a/models/issues/review_test.go b/models/issues/review_test.go index ac1b84adeb..43dc9ed2c1 100644 --- a/models/issues/review_test.go +++ b/models/issues/review_test.go @@ -13,40 +13,41 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetReviewByID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) review, err := issues_model.GetReviewByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Demo Review", review.Content) assert.Equal(t, issues_model.ReviewTypeApprove, review.Type) _, err = issues_model.GetReviewByID(db.DefaultContext, 23892) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrReviewNotExist(err), "IsErrReviewNotExist") } func TestReview_LoadAttributes(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) review := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 1}) - assert.NoError(t, review.LoadAttributes(db.DefaultContext)) + require.NoError(t, review.LoadAttributes(db.DefaultContext)) assert.NotNil(t, review.Issue) assert.NotNil(t, review.Reviewer) invalidReview1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 2}) - assert.Error(t, invalidReview1.LoadAttributes(db.DefaultContext)) + require.Error(t, invalidReview1.LoadAttributes(db.DefaultContext)) invalidReview2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 3}) - assert.Error(t, invalidReview2.LoadAttributes(db.DefaultContext)) + require.Error(t, invalidReview2.LoadAttributes(db.DefaultContext)) } func TestReview_LoadCodeComments(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) review := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 4}) - assert.NoError(t, review.LoadAttributes(db.DefaultContext)) - assert.NoError(t, review.LoadCodeComments(db.DefaultContext)) + require.NoError(t, review.LoadAttributes(db.DefaultContext)) + require.NoError(t, review.LoadCodeComments(db.DefaultContext)) assert.Len(t, review.CodeComments, 1) assert.Equal(t, int64(4), review.CodeComments["README.md"][int64(4)][0].Line) } @@ -61,49 +62,49 @@ func TestReviewType_Icon(t *testing.T) { } func TestFindReviews(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) reviews, err := issues_model.FindReviews(db.DefaultContext, issues_model.FindReviewOptions{ Type: issues_model.ReviewTypeApprove, IssueID: 2, ReviewerID: 1, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, reviews, 1) assert.Equal(t, "Demo Review", reviews[0].Content) } func TestFindLatestReviews(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) reviews, err := issues_model.FindLatestReviews(db.DefaultContext, issues_model.FindReviewOptions{ Type: issues_model.ReviewTypeApprove, IssueID: 11, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, reviews, 2) assert.Equal(t, "duplicate review from user5 (latest)", reviews[0].Content) assert.Equal(t, "singular review from org6 and final review for this pr", reviews[1].Content) } func TestGetCurrentReview(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) review, err := issues_model.GetCurrentReview(db.DefaultContext, user, issue) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, review) assert.Equal(t, issues_model.ReviewTypePending, review.Type) assert.Equal(t, "Pending Review", review.Content) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 7}) review2, err := issues_model.GetCurrentReview(db.DefaultContext, user2, issue) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrReviewNotExist(err)) assert.Nil(t, review2) } func TestCreateReview(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -114,13 +115,13 @@ func TestCreateReview(t *testing.T) { Issue: issue, Reviewer: user, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "New Review", review.Content) unittest.AssertExistsAndLoadBean(t, &issues_model.Review{Content: "New Review"}) } func TestGetReviewersByIssueID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -146,9 +147,9 @@ func TestGetReviewersByIssueID(t *testing.T) { }) allReviews, err := issues_model.GetReviewsByIssueID(db.DefaultContext, issue.ID) - assert.NoError(t, err) + require.NoError(t, err) for _, review := range allReviews { - assert.NoError(t, review.LoadReviewer(db.DefaultContext)) + require.NoError(t, review.LoadReviewer(db.DefaultContext)) } if assert.Len(t, allReviews, 3) { for i, review := range allReviews { @@ -159,8 +160,8 @@ func TestGetReviewersByIssueID(t *testing.T) { } allReviews, err = issues_model.GetReviewsByIssueID(db.DefaultContext, issue.ID) - assert.NoError(t, err) - assert.NoError(t, allReviews.LoadReviewers(db.DefaultContext)) + require.NoError(t, err) + require.NoError(t, allReviews.LoadReviewers(db.DefaultContext)) if assert.Len(t, allReviews, 3) { for i, review := range allReviews { assert.Equal(t, expectedReviews[i].Reviewer, review.Reviewer) @@ -171,7 +172,7 @@ func TestGetReviewersByIssueID(t *testing.T) { } func TestDismissReview(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) rejectReviewExample := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9}) requestReviewExample := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) @@ -180,53 +181,53 @@ func TestDismissReview(t *testing.T) { assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) - assert.NoError(t, issues_model.DismissReview(db.DefaultContext, rejectReviewExample, true)) + require.NoError(t, issues_model.DismissReview(db.DefaultContext, rejectReviewExample, true)) rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9}) requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) assert.True(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) - assert.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, true)) + require.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, true)) rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9}) requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) assert.True(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) - assert.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, true)) + require.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, true)) rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9}) requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) assert.True(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) - assert.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, false)) + require.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, false)) rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9}) requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) assert.True(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) - assert.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, false)) + require.NoError(t, issues_model.DismissReview(db.DefaultContext, requestReviewExample, false)) rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9}) requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) assert.True(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) - assert.NoError(t, issues_model.DismissReview(db.DefaultContext, rejectReviewExample, false)) + require.NoError(t, issues_model.DismissReview(db.DefaultContext, rejectReviewExample, false)) assert.False(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.False(t, approveReviewExample.Dismissed) - assert.NoError(t, issues_model.DismissReview(db.DefaultContext, approveReviewExample, true)) + require.NoError(t, issues_model.DismissReview(db.DefaultContext, approveReviewExample, true)) assert.False(t, rejectReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed) assert.True(t, approveReviewExample.Dismissed) } func TestDeleteReview(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -238,7 +239,7 @@ func TestDeleteReview(t *testing.T) { Issue: issue, Reviewer: user, }) - assert.NoError(t, err) + require.NoError(t, err) review2, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{ Content: "Official approval", @@ -247,21 +248,21 @@ func TestDeleteReview(t *testing.T) { Issue: issue, Reviewer: user, }) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, issues_model.DeleteReview(db.DefaultContext, review2)) + require.NoError(t, issues_model.DeleteReview(db.DefaultContext, review2)) _, err = issues_model.GetReviewByID(db.DefaultContext, review2.ID) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrReviewNotExist(err), "IsErrReviewNotExist") review1, err = issues_model.GetReviewByID(db.DefaultContext, review1.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, review1.Official) } func TestDeleteDismissedReview(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -273,8 +274,8 @@ func TestDeleteDismissedReview(t *testing.T) { Issue: issue, Reviewer: user, }) - assert.NoError(t, err) - assert.NoError(t, issues_model.DismissReview(db.DefaultContext, review, true)) + require.NoError(t, err) + require.NoError(t, issues_model.DismissReview(db.DefaultContext, review, true)) comment, err := issues_model.CreateComment(db.DefaultContext, &issues_model.CreateCommentOptions{ Type: issues_model.CommentTypeDismissReview, Doer: user, @@ -283,19 +284,19 @@ func TestDeleteDismissedReview(t *testing.T) { ReviewID: review.ID, Content: "dismiss", }) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: comment.ID}) - assert.NoError(t, issues_model.DeleteReview(db.DefaultContext, review)) + require.NoError(t, issues_model.DeleteReview(db.DefaultContext, review)) unittest.AssertNotExistsBean(t, &issues_model.Comment{ID: comment.ID}) } func TestAddReviewRequest(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pull := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pull.LoadIssue(db.DefaultContext)) + require.NoError(t, pull.LoadIssue(db.DefaultContext)) issue := pull.Issue - assert.NoError(t, issue.LoadRepo(db.DefaultContext)) + require.NoError(t, issue.LoadRepo(db.DefaultContext)) reviewer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) _, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{ Issue: issue, @@ -303,18 +304,18 @@ func TestAddReviewRequest(t *testing.T) { Type: issues_model.ReviewTypeReject, }) - assert.NoError(t, err) + require.NoError(t, err) pull.HasMerged = false - assert.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) + require.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) issue.IsClosed = true _, err = issues_model.AddReviewRequest(db.DefaultContext, issue, reviewer, &user_model.User{}) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrReviewRequestOnClosedPR(err)) pull.HasMerged = true - assert.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) + require.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) issue.IsClosed = false _, err = issues_model.AddReviewRequest(db.DefaultContext, issue, reviewer, &user_model.User{}) - assert.Error(t, err) + require.Error(t, err) assert.True(t, issues_model.IsErrReviewRequestOnClosedPR(err)) } diff --git a/models/issues/stopwatch_test.go b/models/issues/stopwatch_test.go index 39958a7f36..68a11acd96 100644 --- a/models/issues/stopwatch_test.go +++ b/models/issues/stopwatch_test.go @@ -13,66 +13,67 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCancelStopwatch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1, err := user_model.GetUserByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2) - assert.NoError(t, err) + require.NoError(t, err) err = issues_model.CancelStopwatch(db.DefaultContext, user1, issue1) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertNotExistsBean(t, &issues_model.Stopwatch{UserID: user1.ID, IssueID: issue1.ID}) _ = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{Type: issues_model.CommentTypeCancelTracking, PosterID: user1.ID, IssueID: issue1.ID}) - assert.Nil(t, issues_model.CancelStopwatch(db.DefaultContext, user1, issue2)) + require.NoError(t, issues_model.CancelStopwatch(db.DefaultContext, user1, issue2)) } func TestStopwatchExists(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, issues_model.StopwatchExists(db.DefaultContext, 1, 1)) assert.False(t, issues_model.StopwatchExists(db.DefaultContext, 1, 2)) } func TestHasUserStopwatch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) exists, sw, _, err := issues_model.HasUserStopwatch(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exists) assert.Equal(t, int64(1), sw.ID) exists, _, _, err = issues_model.HasUserStopwatch(db.DefaultContext, 3) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exists) } func TestCreateOrStopIssueStopwatch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user2, err := user_model.GetUserByID(db.DefaultContext, 2) - assert.NoError(t, err) + require.NoError(t, err) org3, err := user_model.GetUserByID(db.DefaultContext, 3) - assert.NoError(t, err) + require.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, issues_model.CreateOrStopIssueStopwatch(db.DefaultContext, org3, issue1)) + require.NoError(t, issues_model.CreateOrStopIssueStopwatch(db.DefaultContext, org3, issue1)) sw := unittest.AssertExistsAndLoadBean(t, &issues_model.Stopwatch{UserID: 3, IssueID: 1}) assert.LessOrEqual(t, sw.CreatedUnix, timeutil.TimeStampNow()) - assert.NoError(t, issues_model.CreateOrStopIssueStopwatch(db.DefaultContext, user2, issue2)) + require.NoError(t, issues_model.CreateOrStopIssueStopwatch(db.DefaultContext, user2, issue2)) unittest.AssertNotExistsBean(t, &issues_model.Stopwatch{UserID: 2, IssueID: 2}) unittest.AssertExistsAndLoadBean(t, &issues_model.TrackedTime{UserID: 2, IssueID: 2}) } diff --git a/models/issues/tracked_time_test.go b/models/issues/tracked_time_test.go index d82bff967a..4d4e232012 100644 --- a/models/issues/tracked_time_test.go +++ b/models/issues/tracked_time_test.go @@ -14,20 +14,21 @@ import ( "code.gitea.io/gitea/modules/optional" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAddTime(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org3, err := user_model.GetUserByID(db.DefaultContext, 3) - assert.NoError(t, err) + require.NoError(t, err) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) // 3661 = 1h 1min 1s trackedTime, err := issues_model.AddTime(db.DefaultContext, org3, issue1, 3661, time.Now()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(3), trackedTime.UserID) assert.Equal(t, int64(1), trackedTime.IssueID) assert.Equal(t, int64(3661), trackedTime.Time) @@ -40,51 +41,51 @@ func TestAddTime(t *testing.T) { } func TestGetTrackedTimes(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // by Issue times, err := issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, times, 1) assert.Equal(t, int64(400), times[0].Time) times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: -1}) - assert.NoError(t, err) - assert.Len(t, times, 0) + require.NoError(t, err) + assert.Empty(t, times) // by User times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{UserID: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, times, 3) assert.Equal(t, int64(400), times[0].Time) times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{UserID: 3}) - assert.NoError(t, err) - assert.Len(t, times, 0) + require.NoError(t, err) + assert.Empty(t, times) // by Repo times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{RepositoryID: 2}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, times, 3) assert.Equal(t, int64(1), times[0].Time) issue, err := issues_model.GetIssueByID(db.DefaultContext, times[0].IssueID) - assert.NoError(t, err) - assert.Equal(t, issue.RepoID, int64(2)) + require.NoError(t, err) + assert.Equal(t, int64(2), issue.RepoID) times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{RepositoryID: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, times, 5) times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{RepositoryID: 10}) - assert.NoError(t, err) - assert.Len(t, times, 0) + require.NoError(t, err) + assert.Empty(t, times) } func TestTotalTimesForEachUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) total, err := issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, total, 1) for user, time := range total { assert.EqualValues(t, 1, user.ID) @@ -92,7 +93,7 @@ func TestTotalTimesForEachUser(t *testing.T) { } total, err = issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 2}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, total, 2) for user, time := range total { if user.ID == 2 { @@ -100,12 +101,12 @@ func TestTotalTimesForEachUser(t *testing.T) { } else if user.ID == 1 { assert.EqualValues(t, 20, time) } else { - assert.Error(t, assert.AnError) + require.Error(t, assert.AnError) } } total, err = issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 5}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, total, 1) for user, time := range total { assert.EqualValues(t, 2, user.ID) @@ -113,22 +114,22 @@ func TestTotalTimesForEachUser(t *testing.T) { } total, err = issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 4}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, total, 2) } func TestGetIssueTotalTrackedTime(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ttt, err := issues_model.GetIssueTotalTrackedTime(db.DefaultContext, &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.Some(false)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3682, ttt) ttt, err = issues_model.GetIssueTotalTrackedTime(db.DefaultContext, &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.Some(true)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, ttt) ttt, err = issues_model.GetIssueTotalTrackedTime(db.DefaultContext, &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.None[bool]()) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3682, ttt) } diff --git a/models/main_test.go b/models/main_test.go index 600dcc889b..a694130e53 100644 --- a/models/main_test.go +++ b/models/main_test.go @@ -15,12 +15,12 @@ import ( _ "code.gitea.io/gitea/models/actions" _ "code.gitea.io/gitea/models/system" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // TestFixturesAreConsistent assert that test fixtures are consistent func TestFixturesAreConsistent(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) unittest.CheckConsistencyFor(t, &user_model.User{}, &repo_model.Repository{}, diff --git a/models/migrations/test/tests.go b/models/migrations/test/tests.go index 71fa88e6b8..0e37233471 100644 --- a/models/migrations/test/tests.go +++ b/models/migrations/test/tests.go @@ -25,7 +25,7 @@ import ( "code.gitea.io/gitea/modules/testlogger" "code.gitea.io/gitea/modules/util" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/xorm" ) @@ -38,11 +38,11 @@ func PrepareTestEnv(t *testing.T, skip int, syncModels ...any) (*xorm.Engine, fu ourSkip := 2 ourSkip += skip deferFn := testlogger.PrintCurrentTest(t, ourSkip) - assert.NoError(t, os.RemoveAll(setting.RepoRootPath)) - assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath)) + require.NoError(t, os.RemoveAll(setting.RepoRootPath)) + require.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath)) ownerDirs, err := os.ReadDir(setting.RepoRootPath) if err != nil { - assert.NoError(t, err, "unable to read the new repo root: %v\n", err) + require.NoError(t, err, "unable to read the new repo root: %v\n", err) } for _, ownerDir := range ownerDirs { if !ownerDir.Type().IsDir() { @@ -50,7 +50,7 @@ func PrepareTestEnv(t *testing.T, skip int, syncModels ...any) (*xorm.Engine, fu } repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name())) if err != nil { - assert.NoError(t, err, "unable to read the new repo root: %v\n", err) + require.NoError(t, err, "unable to read the new repo root: %v\n", err) } for _, repoDir := range repoDirs { _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755) @@ -66,7 +66,7 @@ func PrepareTestEnv(t *testing.T, skip int, syncModels ...any) (*xorm.Engine, fu } x, err := newXORMEngine() - assert.NoError(t, err) + require.NoError(t, err) if x != nil { oldDefer := deferFn deferFn = func() { diff --git a/models/migrations/v1_14/v177_test.go b/models/migrations/v1_14/v177_test.go index e6f5421c99..cf5e745d39 100644 --- a/models/migrations/v1_14/v177_test.go +++ b/models/migrations/v1_14/v177_test.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_DeleteOrphanedIssueLabels(t *testing.T) { @@ -47,7 +48,7 @@ func Test_DeleteOrphanedIssueLabels(t *testing.T) { // Load issue labels that exist in the database pre-migration if err := x.Find(&issueLabels); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } for _, issueLabel := range issueLabels { @@ -56,14 +57,14 @@ func Test_DeleteOrphanedIssueLabels(t *testing.T) { // Run the migration if err := DeleteOrphanedIssueLabels(x); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } // Load the remaining issue-labels issueLabels = issueLabels[:0] if err := x.Find(&issueLabels); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } for _, issueLabel := range issueLabels { diff --git a/models/migrations/v1_15/v181_test.go b/models/migrations/v1_15/v181_test.go index 459ffbdaab..ead26f5fcf 100644 --- a/models/migrations/v1_15/v181_test.go +++ b/models/migrations/v1_15/v181_test.go @@ -10,6 +10,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_AddPrimaryEmail2EmailAddress(t *testing.T) { @@ -28,7 +29,7 @@ func Test_AddPrimaryEmail2EmailAddress(t *testing.T) { defer deferable() err := AddPrimaryEmail2EmailAddress(x) - assert.NoError(t, err) + require.NoError(t, err) type EmailAddress struct { ID int64 `xorm:"pk autoincr"` @@ -41,12 +42,12 @@ func Test_AddPrimaryEmail2EmailAddress(t *testing.T) { users := make([]User, 0, 20) err = x.Find(&users) - assert.NoError(t, err) + require.NoError(t, err) for _, user := range users { var emailAddress EmailAddress has, err := x.Where("lower_email=?", strings.ToLower(user.Email)).Get(&emailAddress) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, has) assert.True(t, emailAddress.IsPrimary) assert.EqualValues(t, user.IsActive, emailAddress.IsActivated) diff --git a/models/migrations/v1_15/v182_test.go b/models/migrations/v1_15/v182_test.go index b492a1396b..eb21311339 100644 --- a/models/migrations/v1_15/v182_test.go +++ b/models/migrations/v1_15/v182_test.go @@ -9,6 +9,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_AddIssueResourceIndexTable(t *testing.T) { @@ -29,7 +30,7 @@ func Test_AddIssueResourceIndexTable(t *testing.T) { // Run the migration if err := AddIssueResourceIndexTable(x); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } @@ -43,12 +44,12 @@ func Test_AddIssueResourceIndexTable(t *testing.T) { for { indexes := make([]ResourceIndex, 0, batchSize) err := x.Table("issue_index").Limit(batchSize, start).Find(&indexes) - assert.NoError(t, err) + require.NoError(t, err) for _, idx := range indexes { var maxIndex int has, err := x.SQL("SELECT max(`index`) FROM issue WHERE repo_id = ?", idx.GroupID).Get(&maxIndex) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, has) assert.EqualValues(t, maxIndex, idx.MaxIndex) } diff --git a/models/migrations/v1_16/v189_test.go b/models/migrations/v1_16/v189_test.go index 3628b1d28e..88c6ebd2b1 100644 --- a/models/migrations/v1_16/v189_test.go +++ b/models/migrations/v1_16/v189_test.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // LoginSource represents an external way for authorizing users. @@ -45,7 +46,7 @@ func Test_UnwrapLDAPSourceCfg(t *testing.T) { // Run the migration if err := UnwrapLDAPSourceCfg(x); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } @@ -53,7 +54,7 @@ func Test_UnwrapLDAPSourceCfg(t *testing.T) { for start := 0; ; start += batchSize { sources := make([]*LoginSource, 0, batchSize) if err := x.Table("login_source").Limit(batchSize, start).Find(&sources); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } @@ -66,12 +67,12 @@ func Test_UnwrapLDAPSourceCfg(t *testing.T) { expected := map[string]any{} if err := json.Unmarshal([]byte(source.Cfg), &converted); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } if err := json.Unmarshal([]byte(source.Expected), &expected); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } diff --git a/models/migrations/v1_16/v193_test.go b/models/migrations/v1_16/v193_test.go index 67bd6ac7c6..1ead74f968 100644 --- a/models/migrations/v1_16/v193_test.go +++ b/models/migrations/v1_16/v193_test.go @@ -9,6 +9,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_AddRepoIDForAttachment(t *testing.T) { @@ -39,7 +40,7 @@ func Test_AddRepoIDForAttachment(t *testing.T) { // Run the migration if err := AddRepoIDForAttachment(x); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } @@ -54,26 +55,26 @@ func Test_AddRepoIDForAttachment(t *testing.T) { var issueAttachments []*NewAttachment err := x.Table("attachment").Where("issue_id > 0").Find(&issueAttachments) - assert.NoError(t, err) + require.NoError(t, err) for _, attach := range issueAttachments { assert.Greater(t, attach.RepoID, int64(0)) assert.Greater(t, attach.IssueID, int64(0)) var issue Issue has, err := x.ID(attach.IssueID).Get(&issue) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, has) assert.EqualValues(t, attach.RepoID, issue.RepoID) } var releaseAttachments []*NewAttachment err = x.Table("attachment").Where("release_id > 0").Find(&releaseAttachments) - assert.NoError(t, err) + require.NoError(t, err) for _, attach := range releaseAttachments { assert.Greater(t, attach.RepoID, int64(0)) assert.Greater(t, attach.ReleaseID, int64(0)) var release Release has, err := x.ID(attach.ReleaseID).Get(&release) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, has) assert.EqualValues(t, attach.RepoID, release.RepoID) } diff --git a/models/migrations/v1_16/v195_test.go b/models/migrations/v1_16/v195_test.go index 428a767157..9a62fc9649 100644 --- a/models/migrations/v1_16/v195_test.go +++ b/models/migrations/v1_16/v195_test.go @@ -9,6 +9,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_AddTableCommitStatusIndex(t *testing.T) { @@ -30,7 +31,7 @@ func Test_AddTableCommitStatusIndex(t *testing.T) { // Run the migration if err := AddTableCommitStatusIndex(x); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } @@ -46,12 +47,12 @@ func Test_AddTableCommitStatusIndex(t *testing.T) { for { indexes := make([]CommitStatusIndex, 0, batchSize) err := x.Table("commit_status_index").Limit(batchSize, start).Find(&indexes) - assert.NoError(t, err) + require.NoError(t, err) for _, idx := range indexes { var maxIndex int has, err := x.SQL("SELECT max(`index`) FROM commit_status WHERE repo_id = ? AND sha = ?", idx.RepoID, idx.SHA).Get(&maxIndex) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, has) assert.EqualValues(t, maxIndex, idx.MaxIndex) } diff --git a/models/migrations/v1_16/v210_test.go b/models/migrations/v1_16/v210_test.go index d5b244202f..7321350de2 100644 --- a/models/migrations/v1_16/v210_test.go +++ b/models/migrations/v1_16/v210_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/xorm/schemas" ) @@ -20,9 +21,9 @@ func TestParseU2FRegistration(t *testing.T) { const testRegRespHex = "0504b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9402a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c253082013c3081e4a003020102020a47901280001155957352300a06082a8648ce3d0403023017311530130603550403130c476e756262792050696c6f74301e170d3132303831343138323933325a170d3133303831343138323933325a3031312f302d0603550403132650696c6f74476e756262792d302e342e312d34373930313238303030313135353935373335323059301306072a8648ce3d020106082a8648ce3d030107034200048d617e65c9508e64bcc5673ac82a6799da3c1446682c258c463fffdf58dfd2fa3e6c378b53d795c4a4dffb4199edd7862f23abaf0203b4b8911ba0569994e101300a06082a8648ce3d0403020347003044022060cdb6061e9c22262d1aac1d96d8c70829b2366531dda268832cb836bcd30dfa0220631b1459f09e6330055722c8d89b7f48883b9089b88d60d1d9795902b30410df304502201471899bcc3987e62e8202c9b39c33c19033f7340352dba80fcab017db9230e402210082677d673d891933ade6f617e5dbde2e247e70423fd5ad7804a6d3d3961ef871" regResp, err := hex.DecodeString(testRegRespHex) - assert.NoError(t, err) + require.NoError(t, err) pubKey, keyHandle, err := parseU2FRegistration(regResp) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "04b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9", hex.EncodeToString(pubKey.Bytes())) assert.Equal(t, "2a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c25", hex.EncodeToString(keyHandle)) } @@ -71,19 +72,17 @@ func Test_RemigrateU2FCredentials(t *testing.T) { // Run the migration if err := RemigrateU2FCredentials(x); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } expected := []ExpectedWebauthnCredential{} - if err := x.Table("expected_webauthn_credential").Asc("id").Find(&expected); !assert.NoError(t, err) { - return - } + err := x.Table("expected_webauthn_credential").Asc("id").Find(&expected) + require.NoError(t, err) got := []ExpectedWebauthnCredential{} - if err := x.Table("webauthn_credential").Select("id, credential_id").Asc("id").Find(&got); !assert.NoError(t, err) { - return - } + err = x.Table("webauthn_credential").Select("id, credential_id").Asc("id").Find(&got) + require.NoError(t, err) assert.EqualValues(t, expected, got) } diff --git a/models/migrations/v1_17/v221_test.go b/models/migrations/v1_17/v221_test.go index 07978336d8..0f6db2a54f 100644 --- a/models/migrations/v1_17/v221_test.go +++ b/models/migrations/v1_17/v221_test.go @@ -10,6 +10,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_StoreWebauthnCredentialIDAsBytes(t *testing.T) { @@ -44,20 +45,16 @@ func Test_StoreWebauthnCredentialIDAsBytes(t *testing.T) { return } - if err := StoreWebauthnCredentialIDAsBytes(x); err != nil { - assert.NoError(t, err) - return - } + err := StoreWebauthnCredentialIDAsBytes(x) + require.NoError(t, err) expected := []ExpectedWebauthnCredential{} - if err := x.Table("expected_webauthn_credential").Asc("id").Find(&expected); !assert.NoError(t, err) { - return - } + err = x.Table("expected_webauthn_credential").Asc("id").Find(&expected) + require.NoError(t, err) got := []ConvertedWebauthnCredential{} - if err := x.Table("webauthn_credential").Select("id, credential_id_bytes").Asc("id").Find(&got); !assert.NoError(t, err) { - return - } + err = x.Table("webauthn_credential").Select("id, credential_id_bytes").Asc("id").Find(&got) + require.NoError(t, err) for i, e := range expected { credIDBytes, _ := base32.HexEncoding.DecodeString(e.CredentialID) diff --git a/models/migrations/v1_18/v229_test.go b/models/migrations/v1_18/v229_test.go index ebda17cce1..b20d0ff3a2 100644 --- a/models/migrations/v1_18/v229_test.go +++ b/models/migrations/v1_18/v229_test.go @@ -10,6 +10,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_UpdateOpenMilestoneCounts(t *testing.T) { @@ -23,19 +24,17 @@ func Test_UpdateOpenMilestoneCounts(t *testing.T) { } if err := UpdateOpenMilestoneCounts(x); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } expected := []ExpectedMilestone{} - if err := x.Table("expected_milestone").Asc("id").Find(&expected); !assert.NoError(t, err) { - return - } + err := x.Table("expected_milestone").Asc("id").Find(&expected) + require.NoError(t, err) got := []issues.Milestone{} - if err := x.Table("milestone").Asc("id").Find(&got); !assert.NoError(t, err) { - return - } + err = x.Table("milestone").Asc("id").Find(&got) + require.NoError(t, err) for i, e := range expected { got := got[i] diff --git a/models/migrations/v1_18/v230_test.go b/models/migrations/v1_18/v230_test.go index 178c7d6c9d..82b3b8f2b0 100644 --- a/models/migrations/v1_18/v230_test.go +++ b/models/migrations/v1_18/v230_test.go @@ -9,6 +9,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_AddConfidentialClientColumnToOAuth2ApplicationTable(t *testing.T) { @@ -25,7 +26,7 @@ func Test_AddConfidentialClientColumnToOAuth2ApplicationTable(t *testing.T) { } if err := AddConfidentialClientColumnToOAuth2ApplicationTable(x); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } @@ -36,9 +37,8 @@ func Test_AddConfidentialClientColumnToOAuth2ApplicationTable(t *testing.T) { } got := []ExpectedOAuth2Application{} - if err := x.Table("oauth2_application").Select("id, confidential_client").Find(&got); !assert.NoError(t, err) { - return - } + err := x.Table("oauth2_application").Select("id, confidential_client").Find(&got) + require.NoError(t, err) assert.NotEmpty(t, got) for _, e := range got { diff --git a/models/migrations/v1_19/v233_test.go b/models/migrations/v1_19/v233_test.go index d3f51a18bb..94e9bc3a11 100644 --- a/models/migrations/v1_19/v233_test.go +++ b/models/migrations/v1_19/v233_test.go @@ -13,6 +13,7 @@ import ( webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) { @@ -46,19 +47,17 @@ func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) { } if err := AddHeaderAuthorizationEncryptedColWebhook(x); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } expected := []ExpectedWebhook{} - if err := x.Table("expected_webhook").Asc("id").Find(&expected); !assert.NoError(t, err) { - return - } + err := x.Table("expected_webhook").Asc("id").Find(&expected) + require.NoError(t, err) got := []Webhook{} - if err := x.Table("webhook").Select("id, meta, header_authorization_encrypted").Asc("id").Find(&got); !assert.NoError(t, err) { - return - } + err = x.Table("webhook").Select("id, meta, header_authorization_encrypted").Asc("id").Find(&got) + require.NoError(t, err) for i, e := range expected { assert.Equal(t, e.Meta, got[i].Meta) @@ -68,20 +67,20 @@ func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) { } else { cipherhex := got[i].HeaderAuthorizationEncrypted cleartext, err := secret.DecryptSecret(setting.SecretKey, cipherhex) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, e.HeaderAuthorization, cleartext) } } // ensure that no hook_task has some remaining "access_token" hookTasks := []HookTask{} - if err := x.Table("hook_task").Select("id, payload_content").Asc("id").Find(&hookTasks); !assert.NoError(t, err) { - return - } + err = x.Table("hook_task").Select("id, payload_content").Asc("id").Find(&hookTasks) + require.NoError(t, err) + for _, h := range hookTasks { var m map[string]any err := json.Unmarshal([]byte(h.PayloadContent), &m) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, m["access_token"]) } } diff --git a/models/migrations/v1_20/v259_test.go b/models/migrations/v1_20/v259_test.go index 3a2543b40f..ae219ea814 100644 --- a/models/migrations/v1_20/v259_test.go +++ b/models/migrations/v1_20/v259_test.go @@ -11,6 +11,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type testCase struct { @@ -75,27 +76,27 @@ func Test_ConvertScopedAccessTokens(t *testing.T) { // verify that no fixtures were loaded count, err := x.Count(&AccessToken{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(0), count) for _, tc := range tests { _, err = x.Insert(&AccessToken{ Scope: string(tc.Old), }) - assert.NoError(t, err) + require.NoError(t, err) } // migrate the scopes err = ConvertScopedAccessTokens(x) - assert.NoError(t, err) + require.NoError(t, err) // migrate the scopes again (migration should be idempotent) err = ConvertScopedAccessTokens(x) - assert.NoError(t, err) + require.NoError(t, err) tokens := make([]AccessToken, 0) err = x.Find(&tokens) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, len(tests), len(tokens)) // sort the tokens (insertion order by auto-incrementing primary key) diff --git a/models/migrations/v1_22/v283_test.go b/models/migrations/v1_22/v283_test.go index ae6e21665b..5f6c04a881 100644 --- a/models/migrations/v1_22/v283_test.go +++ b/models/migrations/v1_22/v283_test.go @@ -8,7 +8,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_AddCombinedIndexToIssueUser(t *testing.T) { @@ -24,5 +24,5 @@ func Test_AddCombinedIndexToIssueUser(t *testing.T) { x, deferable := migration_tests.PrepareTestEnv(t, 0, new(IssueUser)) defer deferable() - assert.NoError(t, AddCombinedIndexToIssueUser(x)) + require.NoError(t, AddCombinedIndexToIssueUser(x)) } diff --git a/models/migrations/v1_22/v286_test.go b/models/migrations/v1_22/v286_test.go index 404d666d70..76b00e5b14 100644 --- a/models/migrations/v1_22/v286_test.go +++ b/models/migrations/v1_22/v286_test.go @@ -9,6 +9,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/xorm" ) @@ -81,7 +82,7 @@ func Test_RepositoryFormat(t *testing.T) { x, deferable := PrepareOldRepository(t) defer deferable() - assert.NoError(t, AdjustDBForSha256(x)) + require.NoError(t, AdjustDBForSha256(x)) type Repository struct { ID int64 `xorm:"pk autoincr"` @@ -92,27 +93,27 @@ func Test_RepositoryFormat(t *testing.T) { // check we have some records to migrate count, err := x.Count(new(Repository)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 4, count) repo.ObjectFormatName = "sha256" _, err = x.Insert(repo) - assert.NoError(t, err) + require.NoError(t, err) id := repo.ID count, err = x.Count(new(Repository)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 5, count) repo = new(Repository) ok, err := x.ID(2).Get(repo) - assert.NoError(t, err) - assert.EqualValues(t, true, ok) + require.NoError(t, err) + assert.True(t, ok) assert.EqualValues(t, "sha1", repo.ObjectFormatName) repo = new(Repository) ok, err = x.ID(id).Get(repo) - assert.NoError(t, err) - assert.EqualValues(t, true, ok) + require.NoError(t, err) + assert.True(t, ok) assert.EqualValues(t, "sha256", repo.ObjectFormatName) } diff --git a/models/migrations/v1_22/v290_test.go b/models/migrations/v1_22/v290_test.go index 0a1df56f4a..ced200f83f 100644 --- a/models/migrations/v1_22/v290_test.go +++ b/models/migrations/v1_22/v290_test.go @@ -12,6 +12,7 @@ import ( webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_AddPayloadVersionToHookTaskTable(t *testing.T) { @@ -40,14 +41,14 @@ func Test_AddPayloadVersionToHookTaskTable(t *testing.T) { return } - assert.NoError(t, AddPayloadVersionToHookTaskTable(x)) + require.NoError(t, AddPayloadVersionToHookTaskTable(x)) expected := []HookTaskMigrated{} - assert.NoError(t, x.Table("hook_task_migrated").Asc("id").Find(&expected)) + require.NoError(t, x.Table("hook_task_migrated").Asc("id").Find(&expected)) assert.Len(t, expected, 2) got := []HookTaskMigrated{} - assert.NoError(t, x.Table("hook_task").Asc("id").Find(&got)) + require.NoError(t, x.Table("hook_task").Asc("id").Find(&got)) for i, expected := range expected { expected, got := expected, got[i] diff --git a/models/migrations/v1_22/v293_test.go b/models/migrations/v1_22/v293_test.go index aa47e84ace..85bb46421b 100644 --- a/models/migrations/v1_22/v293_test.go +++ b/models/migrations/v1_22/v293_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/models/project" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_CheckProjectColumnsConsistency(t *testing.T) { @@ -21,24 +22,24 @@ func Test_CheckProjectColumnsConsistency(t *testing.T) { return } - assert.NoError(t, CheckProjectColumnsConsistency(x)) + require.NoError(t, CheckProjectColumnsConsistency(x)) // check if default column was added var defaultColumn project.Column has, err := x.Where("project_id=? AND `default` = ?", 1, true).Get(&defaultColumn) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, has) assert.Equal(t, int64(1), defaultColumn.ProjectID) assert.True(t, defaultColumn.Default) // check if multiple defaults, previous were removed and last will be kept expectDefaultColumn, err := project.GetColumn(db.DefaultContext, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), expectDefaultColumn.ProjectID) assert.False(t, expectDefaultColumn.Default) expectNonDefaultColumn, err := project.GetColumn(db.DefaultContext, 3) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), expectNonDefaultColumn.ProjectID) assert.True(t, expectNonDefaultColumn.Default) } diff --git a/models/migrations/v1_22/v294_test.go b/models/migrations/v1_22/v294_test.go index 4b20f0317a..c465d53738 100644 --- a/models/migrations/v1_22/v294_test.go +++ b/models/migrations/v1_22/v294_test.go @@ -10,6 +10,7 @@ import ( migration_tests "code.gitea.io/gitea/models/migrations/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/xorm/schemas" ) @@ -28,18 +29,18 @@ func Test_AddUniqueIndexForProjectIssue(t *testing.T) { } cnt, err := x.Table("project_issue").Where("project_id=1 AND issue_id=1").Count() - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 2, cnt) - assert.NoError(t, AddUniqueIndexForProjectIssue(x)) + require.NoError(t, AddUniqueIndexForProjectIssue(x)) cnt, err = x.Table("project_issue").Where("project_id=1 AND issue_id=1").Count() - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, cnt) tables, err := x.DBMetas() - assert.NoError(t, err) - assert.EqualValues(t, 1, len(tables)) + require.NoError(t, err) + assert.Len(t, tables, 1) found := false for _, index := range tables[0].Indexes { if index.Type == schemas.UniqueType { diff --git a/models/org_team_test.go b/models/org_team_test.go index e4b7b917e8..2819607e12 100644 --- a/models/org_team_test.go +++ b/models/org_team_test.go @@ -16,14 +16,15 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTeam_AddMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, userID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, AddTeamMember(db.DefaultContext, team, userID)) + require.NoError(t, AddTeamMember(db.DefaultContext, team, userID)) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: userID, TeamID: teamID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &user_model.User{ID: team.OrgID}) } @@ -33,11 +34,11 @@ func TestTeam_AddMember(t *testing.T) { } func TestTeam_RemoveMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, userID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, RemoveTeamMember(db.DefaultContext, team, userID)) + require.NoError(t, RemoveTeamMember(db.DefaultContext, team, userID)) unittest.AssertNotExistsBean(t, &organization.TeamUser{UID: userID, TeamID: teamID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}) } @@ -52,30 +53,30 @@ func TestTeam_RemoveMember(t *testing.T) { } func TestIsUsableTeamName(t *testing.T) { - assert.NoError(t, organization.IsUsableTeamName("usable")) + require.NoError(t, organization.IsUsableTeamName("usable")) assert.True(t, db.IsErrNameReserved(organization.IsUsableTeamName("new"))) } func TestNewTeam(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) const teamName = "newTeamName" team := &organization.Team{Name: teamName, OrgID: 3} - assert.NoError(t, NewTeam(db.DefaultContext, team)) + require.NoError(t, NewTeam(db.DefaultContext, team)) unittest.AssertExistsAndLoadBean(t, &organization.Team{Name: teamName}) unittest.CheckConsistencyFor(t, &organization.Team{}, &user_model.User{ID: team.OrgID}) } func TestUpdateTeam(t *testing.T) { // successful update - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) team.LowerName = "newname" team.Name = "newName" team.Description = strings.Repeat("A long description!", 100) team.AccessMode = perm.AccessModeAdmin - assert.NoError(t, UpdateTeam(db.DefaultContext, team, true, false)) + require.NoError(t, UpdateTeam(db.DefaultContext, team, true, false)) team = unittest.AssertExistsAndLoadBean(t, &organization.Team{Name: "newName"}) assert.True(t, strings.HasPrefix(team.Description, "A long description!")) @@ -88,7 +89,7 @@ func TestUpdateTeam(t *testing.T) { func TestUpdateTeam2(t *testing.T) { // update to already-existing team - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) team.LowerName = "owners" @@ -101,10 +102,10 @@ func TestUpdateTeam2(t *testing.T) { } func TestDeleteTeam(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) - assert.NoError(t, DeleteTeam(db.DefaultContext, team)) + require.NoError(t, DeleteTeam(db.DefaultContext, team)) unittest.AssertNotExistsBean(t, &organization.Team{ID: team.ID}) unittest.AssertNotExistsBean(t, &organization.TeamRepo{TeamID: team.ID}) unittest.AssertNotExistsBean(t, &organization.TeamUser{TeamID: team.ID}) @@ -113,16 +114,16 @@ func TestDeleteTeam(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) accessMode, err := access_model.AccessLevel(db.DefaultContext, user, repo) - assert.NoError(t, err) - assert.True(t, accessMode < perm.AccessModeWrite) + require.NoError(t, err) + assert.Less(t, accessMode, perm.AccessModeWrite) } func TestAddTeamMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, userID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, AddTeamMember(db.DefaultContext, team, userID)) + require.NoError(t, AddTeamMember(db.DefaultContext, team, userID)) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: userID, TeamID: teamID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &user_model.User{ID: team.OrgID}) } @@ -132,11 +133,11 @@ func TestAddTeamMember(t *testing.T) { } func TestRemoveTeamMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, userID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, RemoveTeamMember(db.DefaultContext, team, userID)) + require.NoError(t, RemoveTeamMember(db.DefaultContext, team, userID)) unittest.AssertNotExistsBean(t, &organization.TeamUser{UID: userID, TeamID: teamID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}) } @@ -151,19 +152,19 @@ func TestRemoveTeamMember(t *testing.T) { } func TestRepository_RecalculateAccesses3(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) team5 := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 5}) user29 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 29}) has, err := db.GetEngine(db.DefaultContext).Get(&access_model.Access{UserID: 29, RepoID: 23}) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, has) // adding user29 to team5 should add an explicit access row for repo 23 // even though repo 23 is public - assert.NoError(t, AddTeamMember(db.DefaultContext, team5, user29.ID)) + require.NoError(t, AddTeamMember(db.DefaultContext, team5, user29.ID)) has, err = db.GetEngine(db.DefaultContext).Get(&access_model.Access{UserID: 29, RepoID: 23}) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, has) } diff --git a/models/org_test.go b/models/org_test.go index d10a1dc218..bb5e524ec9 100644 --- a/models/org_test.go +++ b/models/org_test.go @@ -12,16 +12,17 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUser_RemoveMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) // remove a user that is a member unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{UID: 4, OrgID: 3}) prevNumMembers := org.NumMembers - assert.NoError(t, RemoveOrgUser(db.DefaultContext, org.ID, 4)) + require.NoError(t, RemoveOrgUser(db.DefaultContext, org.ID, 4)) unittest.AssertNotExistsBean(t, &organization.OrgUser{UID: 4, OrgID: 3}) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) assert.Equal(t, prevNumMembers-1, org.NumMembers) @@ -29,7 +30,7 @@ func TestUser_RemoveMember(t *testing.T) { // remove a user that is not a member unittest.AssertNotExistsBean(t, &organization.OrgUser{UID: 5, OrgID: 3}) prevNumMembers = org.NumMembers - assert.NoError(t, RemoveOrgUser(db.DefaultContext, org.ID, 5)) + require.NoError(t, RemoveOrgUser(db.DefaultContext, org.ID, 5)) unittest.AssertNotExistsBean(t, &organization.OrgUser{UID: 5, OrgID: 3}) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) assert.Equal(t, prevNumMembers, org.NumMembers) @@ -38,14 +39,14 @@ func TestUser_RemoveMember(t *testing.T) { } func TestRemoveOrgUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID, userID int64) { org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: orgID}) expectedNumMembers := org.NumMembers if unittest.BeanExists(t, &organization.OrgUser{OrgID: orgID, UID: userID}) { expectedNumMembers-- } - assert.NoError(t, RemoveOrgUser(db.DefaultContext, orgID, userID)) + require.NoError(t, RemoveOrgUser(db.DefaultContext, orgID, userID)) unittest.AssertNotExistsBean(t, &organization.OrgUser{OrgID: orgID, UID: userID}) org = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: orgID}) assert.EqualValues(t, expectedNumMembers, org.NumMembers) @@ -54,7 +55,7 @@ func TestRemoveOrgUser(t *testing.T) { testSuccess(3, 4) err := RemoveOrgUser(db.DefaultContext, 7, 5) - assert.Error(t, err) + require.Error(t, err) assert.True(t, organization.IsErrLastOrgOwner(err)) unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{OrgID: 7, UID: 5}) unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{}) diff --git a/models/organization/org_test.go b/models/organization/org_test.go index 23ef22e2fb..fa4c512189 100644 --- a/models/organization/org_test.go +++ b/models/organization/org_test.go @@ -14,10 +14,11 @@ import ( "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUser_IsOwnedBy(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) for _, testCase := range []struct { OrgID int64 UserID int64 @@ -32,13 +33,13 @@ func TestUser_IsOwnedBy(t *testing.T) { } { org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID}) isOwner, err := org.IsOwnedBy(db.DefaultContext, testCase.UserID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, testCase.ExpectedOwner, isOwner) } } func TestUser_IsOrgMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) for _, testCase := range []struct { OrgID int64 UserID int64 @@ -53,16 +54,16 @@ func TestUser_IsOrgMember(t *testing.T) { } { org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID}) isMember, err := org.IsOrgMember(db.DefaultContext, testCase.UserID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, testCase.ExpectedMember, isMember) } } func TestUser_GetTeam(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) team, err := org.GetTeam(db.DefaultContext, "team1") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, org.ID, team.OrgID) assert.Equal(t, "team1", team.LowerName) @@ -75,10 +76,10 @@ func TestUser_GetTeam(t *testing.T) { } func TestUser_GetOwnerTeam(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) team, err := org.GetOwnerTeam(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, org.ID, team.OrgID) nonOrg := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 2}) @@ -87,10 +88,10 @@ func TestUser_GetOwnerTeam(t *testing.T) { } func TestUser_GetTeams(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) teams, err := org.LoadTeams(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, teams, 5) { assert.Equal(t, int64(1), teams[0].ID) assert.Equal(t, int64(2), teams[1].ID) @@ -101,10 +102,10 @@ func TestUser_GetTeams(t *testing.T) { } func TestUser_GetMembers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) members, _, err := org.GetMembers(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, members, 3) { assert.Equal(t, int64(2), members[0].ID) assert.Equal(t, int64(28), members[1].ID) @@ -113,10 +114,10 @@ func TestUser_GetMembers(t *testing.T) { } func TestGetOrgByName(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org, err := organization.GetOrgByName(db.DefaultContext, "org3") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, org.ID) assert.Equal(t, "org3", org.Name) @@ -128,19 +129,19 @@ func TestGetOrgByName(t *testing.T) { } func TestCountOrganizations(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) expected, err := db.GetEngine(db.DefaultContext).Where("type=?", user_model.UserTypeOrganization).Count(&organization.Organization{}) - assert.NoError(t, err) + require.NoError(t, err) cnt, err := db.Count[organization.Organization](db.DefaultContext, organization.FindOrgOptions{IncludePrivate: true}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, cnt) } func TestIsOrganizationOwner(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64, expected bool) { isOwner, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, userID) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expected, isOwner) } test(3, 2, true) @@ -151,10 +152,10 @@ func TestIsOrganizationOwner(t *testing.T) { } func TestIsOrganizationMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64, expected bool) { isMember, err := organization.IsOrganizationMember(db.DefaultContext, orgID, userID) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expected, isMember) } test(3, 2, true) @@ -166,10 +167,10 @@ func TestIsOrganizationMember(t *testing.T) { } func TestIsPublicMembership(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64, expected bool) { isMember, err := organization.IsPublicMembership(db.DefaultContext, orgID, userID) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expected, isMember) } test(3, 2, true) @@ -181,13 +182,13 @@ func TestIsPublicMembership(t *testing.T) { } func TestFindOrgs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) orgs, err := db.Find[organization.Organization](db.DefaultContext, organization.FindOrgOptions{ UserID: 4, IncludePrivate: true, }) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, orgs, 1) { assert.EqualValues(t, 3, orgs[0].ID) } @@ -196,26 +197,26 @@ func TestFindOrgs(t *testing.T) { UserID: 4, IncludePrivate: false, }) - assert.NoError(t, err) - assert.Len(t, orgs, 0) + require.NoError(t, err) + assert.Empty(t, orgs) total, err := db.Count[organization.Organization](db.DefaultContext, organization.FindOrgOptions{ UserID: 4, IncludePrivate: true, }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, total) } func TestGetOrgUsersByOrgID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) orgUsers, err := organization.GetOrgUsersByOrgID(db.DefaultContext, &organization.FindOrgMembersOpts{ ListOptions: db.ListOptions{}, OrgID: 3, PublicOnly: false, }) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, orgUsers, 3) { assert.Equal(t, organization.OrgUser{ ID: orgUsers[0].ID, @@ -242,15 +243,15 @@ func TestGetOrgUsersByOrgID(t *testing.T) { OrgID: unittest.NonexistentID, PublicOnly: false, }) - assert.NoError(t, err) - assert.Len(t, orgUsers, 0) + require.NoError(t, err) + assert.Empty(t, orgUsers) } func TestChangeOrgUserStatus(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID, userID int64, public bool) { - assert.NoError(t, organization.ChangeOrgUserStatus(db.DefaultContext, orgID, userID, public)) + require.NoError(t, organization.ChangeOrgUserStatus(db.DefaultContext, orgID, userID, public)) orgUser := unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{OrgID: orgID, UID: userID}) assert.Equal(t, public, orgUser.IsPublic) } @@ -258,15 +259,15 @@ func TestChangeOrgUserStatus(t *testing.T) { testSuccess(3, 2, false) testSuccess(3, 2, false) testSuccess(3, 4, true) - assert.NoError(t, organization.ChangeOrgUserStatus(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID, true)) + require.NoError(t, organization.ChangeOrgUserStatus(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID, true)) } func TestUser_GetUserTeamIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) testSuccess := func(userID int64, expected []int64) { teamIDs, err := org.GetUserTeamIDs(db.DefaultContext, userID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, teamIDs) } testSuccess(2, []int64{1, 2, 14}) @@ -275,13 +276,13 @@ func TestUser_GetUserTeamIDs(t *testing.T) { } func TestAccessibleReposEnv_CountRepos(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) testSuccess := func(userID, expectedCount int64) { env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID) - assert.NoError(t, err) + require.NoError(t, err) count, err := env.CountRepos() - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expectedCount, count) } testSuccess(2, 3) @@ -289,13 +290,13 @@ func TestAccessibleReposEnv_CountRepos(t *testing.T) { } func TestAccessibleReposEnv_RepoIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) testSuccess := func(userID int64, expectedRepoIDs []int64) { env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID) - assert.NoError(t, err) + require.NoError(t, err) repoIDs, err := env.RepoIDs(1, 100) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expectedRepoIDs, repoIDs) } testSuccess(2, []int64{3, 5, 32}) @@ -303,13 +304,13 @@ func TestAccessibleReposEnv_RepoIDs(t *testing.T) { } func TestAccessibleReposEnv_Repos(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) testSuccess := func(userID int64, expectedRepoIDs []int64) { env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID) - assert.NoError(t, err) + require.NoError(t, err) repos, err := env.Repos(1, 100) - assert.NoError(t, err) + require.NoError(t, err) expectedRepos := make(repo_model.RepositoryList, len(expectedRepoIDs)) for i, repoID := range expectedRepoIDs { expectedRepos[i] = unittest.AssertExistsAndLoadBean(t, @@ -322,13 +323,13 @@ func TestAccessibleReposEnv_Repos(t *testing.T) { } func TestAccessibleReposEnv_MirrorRepos(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) testSuccess := func(userID int64, expectedRepoIDs []int64) { env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID) - assert.NoError(t, err) + require.NoError(t, err) repos, err := env.MirrorRepos() - assert.NoError(t, err) + require.NoError(t, err) expectedRepos := make(repo_model.RepositoryList, len(expectedRepoIDs)) for i, repoID := range expectedRepoIDs { expectedRepos[i] = unittest.AssertExistsAndLoadBean(t, @@ -341,7 +342,7 @@ func TestAccessibleReposEnv_MirrorRepos(t *testing.T) { } func TestHasOrgVisibleTypePublic(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) @@ -352,7 +353,7 @@ func TestHasOrgVisibleTypePublic(t *testing.T) { } unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization}) - assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner)) + require.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner)) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) @@ -364,7 +365,7 @@ func TestHasOrgVisibleTypePublic(t *testing.T) { } func TestHasOrgVisibleTypeLimited(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) @@ -375,7 +376,7 @@ func TestHasOrgVisibleTypeLimited(t *testing.T) { } unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization}) - assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner)) + require.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner)) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) @@ -387,7 +388,7 @@ func TestHasOrgVisibleTypeLimited(t *testing.T) { } func TestHasOrgVisibleTypePrivate(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) @@ -398,7 +399,7 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) { } unittest.AssertNotExistsBean(t, &user_model.User{Name: org.Name, Type: user_model.UserTypeOrganization}) - assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner)) + require.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner)) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) @@ -410,10 +411,10 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) { } func TestGetUsersWhoCanCreateOrgRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) users, err := organization.GetUsersWhoCanCreateOrgRepo(db.DefaultContext, 3) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, users, 2) var ids []int64 for i := range users { @@ -422,27 +423,27 @@ func TestGetUsersWhoCanCreateOrgRepo(t *testing.T) { assert.ElementsMatch(t, ids, []int64{2, 28}) users, err = organization.GetUsersWhoCanCreateOrgRepo(db.DefaultContext, 7) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, users, 1) assert.NotNil(t, users[5]) } func TestUser_RemoveOrgRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: org.ID}) // remove a repo that does belong to org unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{RepoID: repo.ID, OrgID: org.ID}) - assert.NoError(t, organization.RemoveOrgRepo(db.DefaultContext, org.ID, repo.ID)) + require.NoError(t, organization.RemoveOrgRepo(db.DefaultContext, org.ID, repo.ID)) unittest.AssertNotExistsBean(t, &organization.TeamRepo{RepoID: repo.ID, OrgID: org.ID}) unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID}) // repo should still exist // remove a repo that does not belong to org - assert.NoError(t, organization.RemoveOrgRepo(db.DefaultContext, org.ID, repo.ID)) + require.NoError(t, organization.RemoveOrgRepo(db.DefaultContext, org.ID, repo.ID)) unittest.AssertNotExistsBean(t, &organization.TeamRepo{RepoID: repo.ID, OrgID: org.ID}) - assert.NoError(t, organization.RemoveOrgRepo(db.DefaultContext, org.ID, unittest.NonexistentID)) + require.NoError(t, organization.RemoveOrgRepo(db.DefaultContext, org.ID, unittest.NonexistentID)) unittest.CheckConsistencyFor(t, &user_model.User{ID: org.ID}, @@ -452,7 +453,7 @@ func TestUser_RemoveOrgRepo(t *testing.T) { func TestCreateOrganization(t *testing.T) { // successful creation of org - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) const newOrgName = "neworg" @@ -461,7 +462,7 @@ func TestCreateOrganization(t *testing.T) { } unittest.AssertNotExistsBean(t, &user_model.User{Name: newOrgName, Type: user_model.UserTypeOrganization}) - assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner)) + require.NoError(t, organization.CreateOrganization(db.DefaultContext, org, owner)) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization}) ownerTeam := unittest.AssertExistsAndLoadBean(t, @@ -472,7 +473,7 @@ func TestCreateOrganization(t *testing.T) { func TestCreateOrganization2(t *testing.T) { // unauthorized creation of org - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) const newOrgName = "neworg" @@ -482,7 +483,7 @@ func TestCreateOrganization2(t *testing.T) { unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization}) err := organization.CreateOrganization(db.DefaultContext, org, owner) - assert.Error(t, err) + require.Error(t, err) assert.True(t, organization.IsErrUserNotAllowedCreateOrg(err)) unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization}) unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{}) @@ -490,24 +491,24 @@ func TestCreateOrganization2(t *testing.T) { func TestCreateOrganization3(t *testing.T) { // create org with same name as existent org - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) org := &organization.Organization{Name: "org3"} // should already exist unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: org.Name}) // sanity check err := organization.CreateOrganization(db.DefaultContext, org, owner) - assert.Error(t, err) + require.Error(t, err) assert.True(t, user_model.IsErrUserAlreadyExist(err)) unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{}) } func TestCreateOrganization4(t *testing.T) { // create org with unusable name - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) err := organization.CreateOrganization(db.DefaultContext, &organization.Organization{Name: "assets"}, owner) - assert.Error(t, err) + require.Error(t, err) assert.True(t, db.IsErrNameReserved(err)) unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{}) } diff --git a/models/organization/org_user_test.go b/models/organization/org_user_test.go index 7924517f31..07d07ce3b8 100644 --- a/models/organization/org_user_test.go +++ b/models/organization/org_user_test.go @@ -14,10 +14,11 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUserIsPublicMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { uid int64 @@ -38,14 +39,14 @@ func TestUserIsPublicMember(t *testing.T) { func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) { user, err := user_model.GetUserByID(db.DefaultContext, uid) - assert.NoError(t, err) + require.NoError(t, err) is, err := organization.IsPublicMembership(db.DefaultContext, orgID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, is) } func TestIsUserOrgOwner(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { uid int64 @@ -66,14 +67,14 @@ func TestIsUserOrgOwner(t *testing.T) { func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) { user, err := user_model.GetUserByID(db.DefaultContext, uid) - assert.NoError(t, err) + require.NoError(t, err) is, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, is) } func TestUserListIsPublicMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { orgid int64 expected map[int64]bool @@ -93,14 +94,14 @@ func TestUserListIsPublicMember(t *testing.T) { func testUserListIsPublicMember(t *testing.T, orgID int64, expected map[int64]bool) { org, err := organization.GetOrgByID(db.DefaultContext, orgID) - assert.NoError(t, err) + require.NoError(t, err) _, membersIsPublic, err := org.GetMembers(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, membersIsPublic) } func TestUserListIsUserOrgOwner(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) tt := []struct { orgid int64 expected map[int64]bool @@ -120,21 +121,21 @@ func TestUserListIsUserOrgOwner(t *testing.T) { func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bool) { org, err := organization.GetOrgByID(db.DefaultContext, orgID) - assert.NoError(t, err) + require.NoError(t, err) members, _, err := org.GetMembers(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, organization.IsUserOrgOwner(db.DefaultContext, members, orgID)) } func TestAddOrgUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID, userID int64, isPublic bool) { org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: orgID}) expectedNumMembers := org.NumMembers if !unittest.BeanExists(t, &organization.OrgUser{OrgID: orgID, UID: userID}) { expectedNumMembers++ } - assert.NoError(t, organization.AddOrgUser(db.DefaultContext, orgID, userID)) + require.NoError(t, organization.AddOrgUser(db.DefaultContext, orgID, userID)) ou := &organization.OrgUser{OrgID: orgID, UID: userID} unittest.AssertExistsAndLoadBean(t, ou) assert.Equal(t, isPublic, ou.IsPublic) diff --git a/models/organization/team_invite_test.go b/models/organization/team_invite_test.go index 45db8494e8..cbabf79b49 100644 --- a/models/organization/team_invite_test.go +++ b/models/organization/team_invite_test.go @@ -12,10 +12,11 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTeamInvite(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) @@ -24,7 +25,7 @@ func TestTeamInvite(t *testing.T) { // user 2 already added to team 2, should result in error _, err := organization.CreateTeamInvite(db.DefaultContext, user2, team, user2.Email) - assert.Error(t, err) + require.Error(t, err) }) t.Run("CreateAndRemove", func(t *testing.T) { @@ -32,17 +33,17 @@ func TestTeamInvite(t *testing.T) { invite, err := organization.CreateTeamInvite(db.DefaultContext, user1, team, "org3@example.com") assert.NotNil(t, invite) - assert.NoError(t, err) + require.NoError(t, err) // Shouldn't allow duplicate invite _, err = organization.CreateTeamInvite(db.DefaultContext, user1, team, "org3@example.com") - assert.Error(t, err) + require.Error(t, err) // should remove invite - assert.NoError(t, organization.RemoveInviteByID(db.DefaultContext, invite.ID, invite.TeamID)) + require.NoError(t, organization.RemoveInviteByID(db.DefaultContext, invite.ID, invite.TeamID)) // invite should not exist _, err = organization.GetInviteByToken(db.DefaultContext, invite.Token) - assert.Error(t, err) + require.Error(t, err) }) } diff --git a/models/organization/team_test.go b/models/organization/team_test.go index 23a6affe24..c14c1f181d 100644 --- a/models/organization/team_test.go +++ b/models/organization/team_test.go @@ -11,10 +11,11 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTeam_IsOwnerTeam(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) assert.True(t, team.IsOwnerTeam()) @@ -24,7 +25,7 @@ func TestTeam_IsOwnerTeam(t *testing.T) { } func TestTeam_IsMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) assert.True(t, team.IsMember(db.DefaultContext, 2)) @@ -38,11 +39,11 @@ func TestTeam_IsMember(t *testing.T) { } func TestTeam_GetRepositories(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, team.LoadRepositories(db.DefaultContext)) + require.NoError(t, team.LoadRepositories(db.DefaultContext)) assert.Len(t, team.Repos, team.NumRepos) for _, repo := range team.Repos { unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repo.ID}) @@ -53,11 +54,11 @@ func TestTeam_GetRepositories(t *testing.T) { } func TestTeam_GetMembers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, team.LoadMembers(db.DefaultContext)) + require.NoError(t, team.LoadMembers(db.DefaultContext)) assert.Len(t, team.Members, team.NumMembers) for _, member := range team.Members { unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID}) @@ -68,11 +69,11 @@ func TestTeam_GetMembers(t *testing.T) { } func TestGetTeam(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(orgID int64, name string) { team, err := organization.GetTeam(db.DefaultContext, orgID, name) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, orgID, team.OrgID) assert.Equal(t, name, team.Name) } @@ -80,17 +81,17 @@ func TestGetTeam(t *testing.T) { testSuccess(3, "team1") _, err := organization.GetTeam(db.DefaultContext, 3, "nonexistent") - assert.Error(t, err) + require.Error(t, err) _, err = organization.GetTeam(db.DefaultContext, unittest.NonexistentID, "Owners") - assert.Error(t, err) + require.Error(t, err) } func TestGetTeamByID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID int64) { team, err := organization.GetTeamByID(db.DefaultContext, teamID) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, teamID, team.ID) } testSuccess(1) @@ -99,14 +100,14 @@ func TestGetTeamByID(t *testing.T) { testSuccess(4) _, err := organization.GetTeamByID(db.DefaultContext, unittest.NonexistentID) - assert.Error(t, err) + require.Error(t, err) } func TestIsTeamMember(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, teamID, userID int64, expected bool) { isMember, err := organization.IsTeamMember(db.DefaultContext, orgID, teamID, userID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, isMember) } @@ -122,14 +123,14 @@ func TestIsTeamMember(t *testing.T) { } func TestGetTeamMembers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) members, err := organization.GetTeamMembers(db.DefaultContext, &organization.SearchMembersOptions{ TeamID: teamID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, members, team.NumMembers) for _, member := range members { unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID}) @@ -140,10 +141,10 @@ func TestGetTeamMembers(t *testing.T) { } func TestGetUserTeams(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(userID int64) { teams, _, err := organization.SearchTeam(db.DefaultContext, &organization.SearchTeamOptions{UserID: userID}) - assert.NoError(t, err) + require.NoError(t, err) for _, team := range teams { unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{TeamID: team.ID, UID: userID}) } @@ -154,10 +155,10 @@ func TestGetUserTeams(t *testing.T) { } func TestGetUserOrgTeams(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(orgID, userID int64) { teams, err := organization.GetUserOrgTeams(db.DefaultContext, orgID, userID) - assert.NoError(t, err) + require.NoError(t, err) for _, team := range teams { assert.EqualValues(t, orgID, team.OrgID) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{TeamID: team.ID, UID: userID}) @@ -169,7 +170,7 @@ func TestGetUserOrgTeams(t *testing.T) { } func TestHasTeamRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(teamID, repoID int64, expected bool) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) @@ -185,11 +186,11 @@ func TestHasTeamRepo(t *testing.T) { } func TestUsersInTeamsCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(teamIDs, userIDs []int64, expected int64) { count, err := organization.UsersInTeamsCount(db.DefaultContext, teamIDs, userIDs) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, count) } diff --git a/models/packages/package_test.go b/models/packages/package_test.go index 7f03151e77..8ab7d31e00 100644 --- a/models/packages/package_test.go +++ b/models/packages/package_test.go @@ -16,6 +16,7 @@ import ( _ "code.gitea.io/gitea/models/activities" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -23,7 +24,7 @@ func TestMain(m *testing.M) { } func TestHasOwnerPackages(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -32,12 +33,12 @@ func TestHasOwnerPackages(t *testing.T) { LowerName: "package", }) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) // A package without package versions gets automatically cleaned up and should return false has, err := packages_model.HasOwnerPackages(db.DefaultContext, owner.ID) assert.False(t, has) - assert.NoError(t, err) + require.NoError(t, err) pv, err := packages_model.GetOrInsertVersion(db.DefaultContext, &packages_model.PackageVersion{ PackageID: p.ID, @@ -45,12 +46,12 @@ func TestHasOwnerPackages(t *testing.T) { IsInternal: true, }) assert.NotNil(t, pv) - assert.NoError(t, err) + require.NoError(t, err) // A package with an internal package version gets automatically cleaned up and should return false has, err = packages_model.HasOwnerPackages(db.DefaultContext, owner.ID) assert.False(t, has) - assert.NoError(t, err) + require.NoError(t, err) pv, err = packages_model.GetOrInsertVersion(db.DefaultContext, &packages_model.PackageVersion{ PackageID: p.ID, @@ -58,10 +59,10 @@ func TestHasOwnerPackages(t *testing.T) { IsInternal: false, }) assert.NotNil(t, pv) - assert.NoError(t, err) + require.NoError(t, err) // A package with a normal package version should return true has, err = packages_model.HasOwnerPackages(db.DefaultContext, owner.ID) assert.True(t, has) - assert.NoError(t, err) + require.NoError(t, err) } diff --git a/models/perm/access/access_test.go b/models/perm/access/access_test.go index 79b131fe89..556f51311c 100644 --- a/models/perm/access/access_test.go +++ b/models/perm/access/access_test.go @@ -14,10 +14,11 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAccessLevel(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) @@ -36,39 +37,39 @@ func TestAccessLevel(t *testing.T) { repo24 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 24}) level, err := access_model.AccessLevel(db.DefaultContext, user2, repo1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, perm_model.AccessModeOwner, level) level, err = access_model.AccessLevel(db.DefaultContext, user2, repo3) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, perm_model.AccessModeOwner, level) level, err = access_model.AccessLevel(db.DefaultContext, user5, repo1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, perm_model.AccessModeRead, level) level, err = access_model.AccessLevel(db.DefaultContext, user5, repo3) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, perm_model.AccessModeNone, level) // restricted user has no access to a public repo level, err = access_model.AccessLevel(db.DefaultContext, user29, repo1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, perm_model.AccessModeNone, level) // ... unless he's a collaborator level, err = access_model.AccessLevel(db.DefaultContext, user29, repo4) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, perm_model.AccessModeWrite, level) // ... or a team member level, err = access_model.AccessLevel(db.DefaultContext, user29, repo24) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, perm_model.AccessModeRead, level) } func TestHasAccess(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) @@ -80,47 +81,47 @@ func TestHasAccess(t *testing.T) { assert.True(t, repo2.IsPrivate) has, err := access_model.HasAccess(db.DefaultContext, user1.ID, repo1) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, has) _, err = access_model.HasAccess(db.DefaultContext, user1.ID, repo2) - assert.NoError(t, err) + require.NoError(t, err) _, err = access_model.HasAccess(db.DefaultContext, user2.ID, repo1) - assert.NoError(t, err) + require.NoError(t, err) _, err = access_model.HasAccess(db.DefaultContext, user2.ID, repo2) - assert.NoError(t, err) + require.NoError(t, err) } func TestRepository_RecalculateAccesses(t *testing.T) { // test with organization repo - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) - assert.NoError(t, repo1.LoadOwner(db.DefaultContext)) + require.NoError(t, repo1.LoadOwner(db.DefaultContext)) _, err := db.GetEngine(db.DefaultContext).Delete(&repo_model.Collaboration{UserID: 2, RepoID: 3}) - assert.NoError(t, err) - assert.NoError(t, access_model.RecalculateAccesses(db.DefaultContext, repo1)) + require.NoError(t, err) + require.NoError(t, access_model.RecalculateAccesses(db.DefaultContext, repo1)) access := &access_model.Access{UserID: 2, RepoID: 3} has, err := db.GetEngine(db.DefaultContext).Get(access) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, has) assert.Equal(t, perm_model.AccessModeOwner, access.Mode) } func TestRepository_RecalculateAccesses2(t *testing.T) { // test with non-organization repo - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) - assert.NoError(t, repo1.LoadOwner(db.DefaultContext)) + require.NoError(t, repo1.LoadOwner(db.DefaultContext)) _, err := db.GetEngine(db.DefaultContext).Delete(&repo_model.Collaboration{UserID: 4, RepoID: 4}) - assert.NoError(t, err) - assert.NoError(t, access_model.RecalculateAccesses(db.DefaultContext, repo1)) + require.NoError(t, err) + require.NoError(t, access_model.RecalculateAccesses(db.DefaultContext, repo1)) has, err := db.GetEngine(db.DefaultContext).Get(&access_model.Access{UserID: 4, RepoID: 4}) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, has) } diff --git a/models/project/column_test.go b/models/project/column_test.go index 911649fb72..b02a5b540f 100644 --- a/models/project/column_test.go +++ b/models/project/column_test.go @@ -12,64 +12,65 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetDefaultColumn(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) projectWithoutDefault, err := GetProjectByID(db.DefaultContext, 5) - assert.NoError(t, err) + require.NoError(t, err) // check if default column was added column, err := projectWithoutDefault.GetDefaultColumn(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(5), column.ProjectID) assert.Equal(t, "Uncategorized", column.Title) projectWithMultipleDefaults, err := GetProjectByID(db.DefaultContext, 6) - assert.NoError(t, err) + require.NoError(t, err) // check if multiple defaults were removed column, err = projectWithMultipleDefaults.GetDefaultColumn(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(6), column.ProjectID) assert.Equal(t, int64(9), column.ID) // set 8 as default column - assert.NoError(t, SetDefaultColumn(db.DefaultContext, column.ProjectID, 8)) + require.NoError(t, SetDefaultColumn(db.DefaultContext, column.ProjectID, 8)) // then 9 will become a non-default column column, err = GetColumn(db.DefaultContext, 9) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(6), column.ProjectID) assert.False(t, column.Default) } func Test_moveIssuesToAnotherColumn(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) column1 := unittest.AssertExistsAndLoadBean(t, &Column{ID: 1, ProjectID: 1}) issues, err := column1.GetIssues(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, issues, 1) assert.EqualValues(t, 1, issues[0].ID) column2 := unittest.AssertExistsAndLoadBean(t, &Column{ID: 2, ProjectID: 1}) issues, err = column2.GetIssues(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, issues, 1) assert.EqualValues(t, 3, issues[0].ID) err = column1.moveIssuesToAnotherColumn(db.DefaultContext, column2) - assert.NoError(t, err) + require.NoError(t, err) issues, err = column1.GetIssues(db.DefaultContext) - assert.NoError(t, err) - assert.Len(t, issues, 0) + require.NoError(t, err) + assert.Empty(t, issues) issues, err = column2.GetIssues(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, issues, 2) assert.EqualValues(t, 3, issues[0].ID) assert.EqualValues(t, 0, issues[0].Sorting) @@ -78,11 +79,11 @@ func Test_moveIssuesToAnotherColumn(t *testing.T) { } func Test_MoveColumnsOnProject(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) project1 := unittest.AssertExistsAndLoadBean(t, &Project{ID: 1}) columns, err := project1.GetColumns(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, columns, 3) assert.EqualValues(t, 0, columns[0].Sorting) // even if there is no default sorting, the code should also work assert.EqualValues(t, 0, columns[1].Sorting) @@ -93,10 +94,10 @@ func Test_MoveColumnsOnProject(t *testing.T) { 1: columns[2].ID, 2: columns[0].ID, }) - assert.NoError(t, err) + require.NoError(t, err) columnsAfter, err := project1.GetColumns(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, columnsAfter, 3) assert.EqualValues(t, columns[1].ID, columnsAfter[0].ID) assert.EqualValues(t, columns[2].ID, columnsAfter[1].ID) @@ -104,11 +105,11 @@ func Test_MoveColumnsOnProject(t *testing.T) { } func Test_NewColumn(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) project1 := unittest.AssertExistsAndLoadBean(t, &Project{ID: 1}) columns, err := project1.GetColumns(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, columns, 3) for i := 0; i < maxProjectColumns-3; i++ { @@ -116,12 +117,12 @@ func Test_NewColumn(t *testing.T) { Title: fmt.Sprintf("column-%d", i+4), ProjectID: project1.ID, }) - assert.NoError(t, err) + require.NoError(t, err) } err = NewColumn(db.DefaultContext, &Column{ Title: "column-21", ProjectID: project1.ID, }) - assert.Error(t, err) + require.Error(t, err) assert.True(t, strings.Contains(err.Error(), "maximum number of columns reached")) } diff --git a/models/project/project_test.go b/models/project/project_test.go index dd421b4659..8c660b929a 100644 --- a/models/project/project_test.go +++ b/models/project/project_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIsProjectTypeValid(t *testing.T) { @@ -32,23 +33,23 @@ func TestIsProjectTypeValid(t *testing.T) { } func TestGetProjects(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) projects, err := db.Find[Project](db.DefaultContext, SearchOptions{RepoID: 1}) - assert.NoError(t, err) + require.NoError(t, err) // 1 value for this repo exists in the fixtures assert.Len(t, projects, 1) projects, err = db.Find[Project](db.DefaultContext, SearchOptions{RepoID: 3}) - assert.NoError(t, err) + require.NoError(t, err) // 1 value for this repo exists in the fixtures assert.Len(t, projects, 1) } func TestProject(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) project := &Project{ Type: TypeRepository, @@ -60,31 +61,31 @@ func TestProject(t *testing.T) { CreatorID: 2, } - assert.NoError(t, NewProject(db.DefaultContext, project)) + require.NoError(t, NewProject(db.DefaultContext, project)) _, err := GetProjectByID(db.DefaultContext, project.ID) - assert.NoError(t, err) + require.NoError(t, err) // Update project project.Title = "Updated title" - assert.NoError(t, UpdateProject(db.DefaultContext, project)) + require.NoError(t, UpdateProject(db.DefaultContext, project)) projectFromDB, err := GetProjectByID(db.DefaultContext, project.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, project.Title, projectFromDB.Title) - assert.NoError(t, ChangeProjectStatus(db.DefaultContext, project, true)) + require.NoError(t, ChangeProjectStatus(db.DefaultContext, project, true)) // Retrieve from DB afresh to check if it is truly closed projectFromDB, err = GetProjectByID(db.DefaultContext, project.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, projectFromDB.IsClosed) } func TestProjectsSort(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) tests := []struct { sortType string @@ -112,7 +113,7 @@ func TestProjectsSort(t *testing.T) { projects, count, err := db.FindAndCount[Project](db.DefaultContext, SearchOptions{ OrderBy: GetSearchOrderByBySortType(tt.sortType), }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, int64(6), count) if assert.Len(t, projects, 6) { for i := range projects { diff --git a/models/repo/archive_download_count_test.go b/models/repo/archive_download_count_test.go index 53bdf9a1e0..ffc6cdf6df 100644 --- a/models/repo/archive_download_count_test.go +++ b/models/repo/archive_download_count_test.go @@ -16,7 +16,7 @@ import ( ) func TestRepoArchiveDownloadCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) release, err := repo_model.GetReleaseByID(db.DefaultContext, 1) require.NoError(t, err) diff --git a/models/repo/attachment_test.go b/models/repo/attachment_test.go index c059ffd39a..23945ba1d3 100644 --- a/models/repo/attachment_test.go +++ b/models/repo/attachment_test.go @@ -11,62 +11,63 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIncreaseDownloadCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(0), attachment.DownloadCount) // increase download count err = attachment.IncreaseDownloadCount(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) attachment, err = repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), attachment.DownloadCount) } func TestGetByCommentOrIssueID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // count of attachments from issue ID attachments, err := repo_model.GetAttachmentsByIssueID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, attachments, 1) attachments, err = repo_model.GetAttachmentsByCommentID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, attachments, 2) } func TestDeleteAttachments(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) count, err := repo_model.DeleteAttachmentsByIssue(db.DefaultContext, 4, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 2, count) count, err = repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 2, count) err = repo_model.DeleteAttachment(db.DefaultContext, &repo_model.Attachment{ID: 8}, false) - assert.NoError(t, err) + require.NoError(t, err) attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a18") - assert.Error(t, err) + require.Error(t, err) assert.True(t, repo_model.IsErrAttachmentNotExist(err)) assert.Nil(t, attachment) } func TestGetAttachmentByID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) attach, err := repo_model.GetAttachmentByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID) } @@ -79,23 +80,23 @@ func TestAttachment_DownloadURL(t *testing.T) { } func TestUpdateAttachment(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) attach, err := repo_model.GetAttachmentByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID) attach.Name = "new_name" - assert.NoError(t, repo_model.UpdateAttachment(db.DefaultContext, attach)) + require.NoError(t, repo_model.UpdateAttachment(db.DefaultContext, attach)) unittest.AssertExistsAndLoadBean(t, &repo_model.Attachment{Name: "new_name"}) } func TestGetAttachmentsByUUIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) attachList, err := repo_model.GetAttachmentsByUUIDs(db.DefaultContext, []string{"a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", "not-existing-uuid"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, attachList, 2) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attachList[0].UUID) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", attachList[1].UUID) diff --git a/models/repo/collaboration_test.go b/models/repo/collaboration_test.go index 0bfe60801c..5adedfe442 100644 --- a/models/repo/collaboration_test.go +++ b/models/repo/collaboration_test.go @@ -14,16 +14,17 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_GetCollaborators(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID int64) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) collaborators, err := repo_model.GetCollaborators(db.DefaultContext, repo.ID, db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) expectedLen, err := db.GetEngine(db.DefaultContext).Count(&repo_model.Collaboration{RepoID: repoID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, collaborators, int(expectedLen)) for _, collaborator := range collaborators { assert.EqualValues(t, collaborator.User.ID, collaborator.Collaboration.UserID) @@ -39,23 +40,23 @@ func TestRepository_GetCollaborators(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 22}) collaborators1, err := repo_model.GetCollaborators(db.DefaultContext, repo.ID, db.ListOptions{PageSize: 1, Page: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, collaborators1, 1) collaborators2, err := repo_model.GetCollaborators(db.DefaultContext, repo.ID, db.ListOptions{PageSize: 1, Page: 2}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, collaborators2, 1) assert.NotEqualValues(t, collaborators1[0].ID, collaborators2[0].ID) } func TestRepository_IsCollaborator(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) test := func(repoID, userID int64, expected bool) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) actual, err := repo_model.IsCollaborator(db.DefaultContext, repo.ID, userID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, actual) } test(3, 2, true) @@ -65,10 +66,10 @@ func TestRepository_IsCollaborator(t *testing.T) { } func TestRepository_ChangeCollaborationAccessMode(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessModeAdmin)) + require.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessModeAdmin)) collaboration := unittest.AssertExistsAndLoadBean(t, &repo_model.Collaboration{RepoID: repo.ID, UserID: 4}) assert.EqualValues(t, perm.AccessModeAdmin, collaboration.Mode) @@ -76,109 +77,109 @@ func TestRepository_ChangeCollaborationAccessMode(t *testing.T) { access := unittest.AssertExistsAndLoadBean(t, &access_model.Access{UserID: 4, RepoID: repo.ID}) assert.EqualValues(t, perm.AccessModeAdmin, access.Mode) - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessModeAdmin)) + require.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessModeAdmin)) - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, unittest.NonexistentID, perm.AccessModeAdmin)) + require.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, unittest.NonexistentID, perm.AccessModeAdmin)) // Disvard invalid input. - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessMode(unittest.NonexistentID))) + require.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, 4, perm.AccessMode(unittest.NonexistentID))) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID}) } func TestRepository_CountCollaborators(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) count, err := db.Count[repo_model.Collaboration](db.DefaultContext, repo_model.FindCollaborationOptions{ RepoID: repo1.ID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 2, count) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 22}) count, err = db.Count[repo_model.Collaboration](db.DefaultContext, repo_model.FindCollaborationOptions{ RepoID: repo2.ID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 2, count) // Non-existent repository. count, err = db.Count[repo_model.Collaboration](db.DefaultContext, repo_model.FindCollaborationOptions{ RepoID: unittest.NonexistentID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, count) } func TestRepository_IsOwnerMemberCollaborator(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) // Organisation owner. actual, err := repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, actual) // Team member. actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 4) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, actual) // Normal user. actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, actual) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) // Collaborator. actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo2, 4) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, actual) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 15}) // Repository owner. actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo3, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, actual) } func TestRepo_GetCollaboration(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) // Existing collaboration. collab, err := repo_model.GetCollaboration(db.DefaultContext, repo.ID, 4) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, collab) assert.EqualValues(t, 4, collab.UserID) assert.EqualValues(t, 4, collab.RepoID) // Non-existing collaboration. collab, err = repo_model.GetCollaboration(db.DefaultContext, repo.ID, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, collab) } func TestGetCollaboratorWithUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user16 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 16}) user15 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 15}) user18 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 18}) collabs, err := repo_model.GetCollaboratorWithUser(db.DefaultContext, user16.ID, user15.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, collabs, 2) assert.EqualValues(t, 5, collabs[0]) assert.EqualValues(t, 7, collabs[1]) collabs, err = repo_model.GetCollaboratorWithUser(db.DefaultContext, user16.ID, user18.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, collabs, 2) assert.EqualValues(t, 6, collabs[0]) assert.EqualValues(t, 8, collabs[1]) diff --git a/models/repo/fork_test.go b/models/repo/fork_test.go index e8dca204cc..dd12429cc4 100644 --- a/models/repo/fork_test.go +++ b/models/repo/fork_test.go @@ -11,23 +11,24 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetUserFork(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // User13 has repo 11 forked from repo10 repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 10) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, repo) repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, repo) repo, err = repo_model.GetRepositoryByID(db.DefaultContext, 9) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, repo) repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, repo) } diff --git a/models/repo/pushmirror_test.go b/models/repo/pushmirror_test.go index e19749d93a..ebaa6e53ba 100644 --- a/models/repo/pushmirror_test.go +++ b/models/repo/pushmirror_test.go @@ -13,10 +13,11 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPushMirrorsIterate(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) now := timeutil.TimeStampNow() diff --git a/models/repo/redirect_test.go b/models/repo/redirect_test.go index 24cf7e89fb..2016784aed 100644 --- a/models/repo/redirect_test.go +++ b/models/repo/redirect_test.go @@ -11,13 +11,14 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLookupRedirect(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repoID, err := repo_model.LookupRedirect(db.DefaultContext, 2, "oldrepo1") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, repoID) _, err = repo_model.LookupRedirect(db.DefaultContext, unittest.NonexistentID, "doesnotexist") @@ -26,10 +27,10 @@ func TestLookupRedirect(t *testing.T) { func TestNewRedirect(t *testing.T) { // redirect to a completely new name - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - assert.NoError(t, repo_model.NewRedirect(db.DefaultContext, repo.OwnerID, repo.ID, repo.Name, "newreponame")) + require.NoError(t, repo_model.NewRedirect(db.DefaultContext, repo.OwnerID, repo.ID, repo.Name, "newreponame")) unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{ OwnerID: repo.OwnerID, @@ -45,10 +46,10 @@ func TestNewRedirect(t *testing.T) { func TestNewRedirect2(t *testing.T) { // redirect to previously used name - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - assert.NoError(t, repo_model.NewRedirect(db.DefaultContext, repo.OwnerID, repo.ID, repo.Name, "oldrepo1")) + require.NoError(t, repo_model.NewRedirect(db.DefaultContext, repo.OwnerID, repo.ID, repo.Name, "oldrepo1")) unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{ OwnerID: repo.OwnerID, @@ -64,10 +65,10 @@ func TestNewRedirect2(t *testing.T) { func TestNewRedirect3(t *testing.T) { // redirect for a previously-unredirected repo - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - assert.NoError(t, repo_model.NewRedirect(db.DefaultContext, repo.OwnerID, repo.ID, repo.Name, "newreponame")) + require.NoError(t, repo_model.NewRedirect(db.DefaultContext, repo.OwnerID, repo.ID, repo.Name, "newreponame")) unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{ OwnerID: repo.OwnerID, diff --git a/models/repo/release_test.go b/models/repo/release_test.go index 3643bff7f1..4e61a2805d 100644 --- a/models/repo/release_test.go +++ b/models/repo/release_test.go @@ -9,11 +9,11 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMigrate_InsertReleases(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) a := &Attachment{ UUID: "a0eebc91-9c0c-4ef7-bb6e-6bb9bd380a12", @@ -23,5 +23,5 @@ func TestMigrate_InsertReleases(t *testing.T) { } err := InsertReleases(db.DefaultContext, r) - assert.NoError(t, err) + require.NoError(t, err) } diff --git a/models/repo/repo_flags_test.go b/models/repo/repo_flags_test.go index 0e4f5c1ba9..bccefcf72b 100644 --- a/models/repo/repo_flags_test.go +++ b/models/repo/repo_flags_test.go @@ -11,10 +11,11 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepositoryFlags(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}) // ******************** @@ -23,7 +24,7 @@ func TestRepositoryFlags(t *testing.T) { // Unless we add flags, the repo has none flags, err := repo.ListFlags(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, flags) // If the repo has no flags, it is not flagged @@ -36,12 +37,12 @@ func TestRepositoryFlags(t *testing.T) { // Trying to retrieve a non-existent flag indicates not found has, _, err = repo.GetFlag(db.DefaultContext, "foo") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, has) // Deleting a non-existent flag fails deleted, err := repo.DeleteFlag(db.DefaultContext, "no-such-flag") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(0), deleted) // ******************** @@ -50,15 +51,15 @@ func TestRepositoryFlags(t *testing.T) { // Adding a flag works err = repo.AddFlag(db.DefaultContext, "foo") - assert.NoError(t, err) + require.NoError(t, err) // Adding it again fails err = repo.AddFlag(db.DefaultContext, "foo") - assert.Error(t, err) + require.Error(t, err) // Listing flags includes the one we added flags, err = repo.ListFlags(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, flags, 1) assert.Equal(t, "foo", flags[0].Name) @@ -72,22 +73,22 @@ func TestRepositoryFlags(t *testing.T) { // Added flag can be retrieved _, flag, err := repo.GetFlag(db.DefaultContext, "foo") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "foo", flag.Name) // Deleting a flag works deleted, err = repo.DeleteFlag(db.DefaultContext, "foo") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), deleted) // The list is now empty flags, err = repo.ListFlags(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, flags) // Replacing an empty list works err = repo.ReplaceAllFlags(db.DefaultContext, []string{"bar"}) - assert.NoError(t, err) + require.NoError(t, err) // The repo is now flagged with "bar" has = repo.HasFlag(db.DefaultContext, "bar") @@ -95,18 +96,18 @@ func TestRepositoryFlags(t *testing.T) { // Replacing a tag set with another works err = repo.ReplaceAllFlags(db.DefaultContext, []string{"baz", "quux"}) - assert.NoError(t, err) + require.NoError(t, err) // The repo now has two tags flags, err = repo.ListFlags(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, flags, 2) assert.Equal(t, "baz", flags[0].Name) assert.Equal(t, "quux", flags[1].Name) // Replacing flags with an empty set deletes all flags err = repo.ReplaceAllFlags(db.DefaultContext, []string{}) - assert.NoError(t, err) + require.NoError(t, err) // The repo is now unflagged flagged = repo.IsFlagged(db.DefaultContext) diff --git a/models/repo/repo_list_test.go b/models/repo/repo_list_test.go index 6b1bb39b85..b31aa1780f 100644 --- a/models/repo/repo_list_test.go +++ b/models/repo/repo_list_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/optional" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func getTestCases() []struct { @@ -181,7 +182,7 @@ func getTestCases() []struct { } func TestSearchRepository(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // test search public repository on explore page repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{ @@ -193,7 +194,7 @@ func TestSearchRepository(t *testing.T) { Collaborate: optional.Some(false), }) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, repos, 1) { assert.Equal(t, "test_repo_12", repos[0].Name) } @@ -208,7 +209,7 @@ func TestSearchRepository(t *testing.T) { Collaborate: optional.Some(false), }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), count) assert.Len(t, repos, 2) @@ -223,7 +224,7 @@ func TestSearchRepository(t *testing.T) { Collaborate: optional.Some(false), }) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, repos, 1) { assert.Equal(t, "test_repo_13", repos[0].Name) } @@ -239,14 +240,14 @@ func TestSearchRepository(t *testing.T) { Collaborate: optional.Some(false), }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(3), count) assert.Len(t, repos, 3) // Test non existing owner repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{OwnerID: unittest.NonexistentID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, repos) assert.Equal(t, int64(0), count) @@ -261,7 +262,7 @@ func TestSearchRepository(t *testing.T) { IncludeDescription: true, }) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, repos, 1) { assert.Equal(t, "test_repo_14", repos[0].Name) } @@ -278,7 +279,7 @@ func TestSearchRepository(t *testing.T) { IncludeDescription: false, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, repos) assert.Equal(t, int64(0), count) @@ -288,7 +289,7 @@ func TestSearchRepository(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(testCase.count), count) page := testCase.opts.Page @@ -355,7 +356,7 @@ func TestSearchRepository(t *testing.T) { } func TestCountRepository(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testCases := getTestCases() @@ -363,14 +364,14 @@ func TestCountRepository(t *testing.T) { t.Run(testCase.name, func(t *testing.T) { count, err := repo_model.CountRepository(db.DefaultContext, testCase.opts) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(testCase.count), count) }) } } func TestSearchRepositoryByTopicName(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testCases := []struct { name string @@ -397,7 +398,7 @@ func TestSearchRepositoryByTopicName(t *testing.T) { for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { _, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(testCase.count), count) }) } diff --git a/models/repo/repo_test.go b/models/repo/repo_test.go index a279478177..56b84798d7 100644 --- a/models/repo/repo_test.go +++ b/models/repo/repo_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var ( @@ -27,58 +28,58 @@ var ( ) func TestGetRepositoryCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ctx := db.DefaultContext count, err1 := repo_model.CountRepositories(ctx, countRepospts) privateCount, err2 := repo_model.CountRepositories(ctx, countReposptsPrivate) publicCount, err3 := repo_model.CountRepositories(ctx, countReposptsPublic) - assert.NoError(t, err1) - assert.NoError(t, err2) - assert.NoError(t, err3) + require.NoError(t, err1) + require.NoError(t, err2) + require.NoError(t, err3) assert.Equal(t, int64(3), count) assert.Equal(t, privateCount+publicCount, count) } func TestGetPublicRepositoryCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) count, err := repo_model.CountRepositories(db.DefaultContext, countReposptsPublic) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), count) } func TestGetPrivateRepositoryCount(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) count, err := repo_model.CountRepositories(db.DefaultContext, countReposptsPrivate) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), count) } func TestRepoAPIURL(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}) assert.Equal(t, "https://try.gitea.io/api/v1/repos/user12/repo10", repo.APIURL()) } func TestWatchRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) const repoID = 3 const userID = 2 - assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, userID, repoID, true)) + require.NoError(t, repo_model.WatchRepo(db.DefaultContext, userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &repo_model.Watch{RepoID: repoID, UserID: userID}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}) - assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, userID, repoID, false)) + require.NoError(t, repo_model.WatchRepo(db.DefaultContext, userID, repoID, false)) unittest.AssertNotExistsBean(t, &repo_model.Watch{RepoID: repoID, UserID: userID}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}) } func TestMetas(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := &repo_model.Repository{Name: "testRepo"} repo.Owner = &user_model.User{Name: "testOwner"} @@ -119,7 +120,7 @@ func TestMetas(t *testing.T) { testSuccess(markup.IssueNameStyleRegexp) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 3) - assert.NoError(t, err) + require.NoError(t, err) metas = repo.ComposeMetas(db.DefaultContext) assert.Contains(t, metas, "org") @@ -129,13 +130,13 @@ func TestMetas(t *testing.T) { } func TestGetRepositoryByURL(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) t.Run("InvalidPath", func(t *testing.T) { repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, "something") assert.Nil(t, repo) - assert.Error(t, err) + require.Error(t, err) }) t.Run("ValidHttpURL", func(t *testing.T) { @@ -143,10 +144,10 @@ func TestGetRepositoryByURL(t *testing.T) { repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, url) assert.NotNil(t, repo) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, repo.ID, int64(2)) - assert.Equal(t, repo.OwnerID, int64(2)) + assert.Equal(t, int64(2), repo.ID) + assert.Equal(t, int64(2), repo.OwnerID) } test(t, "https://try.gitea.io/user2/repo2") @@ -158,10 +159,10 @@ func TestGetRepositoryByURL(t *testing.T) { repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, url) assert.NotNil(t, repo) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, repo.ID, int64(2)) - assert.Equal(t, repo.OwnerID, int64(2)) + assert.Equal(t, int64(2), repo.ID) + assert.Equal(t, int64(2), repo.OwnerID) } test(t, "git+ssh://sshuser@try.gitea.io/user2/repo2") @@ -176,10 +177,10 @@ func TestGetRepositoryByURL(t *testing.T) { repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, url) assert.NotNil(t, repo) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, repo.ID, int64(2)) - assert.Equal(t, repo.OwnerID, int64(2)) + assert.Equal(t, int64(2), repo.ID) + assert.Equal(t, int64(2), repo.OwnerID) } test(t, "sshuser@try.gitea.io:user2/repo2") diff --git a/models/repo/repo_unit_test.go b/models/repo/repo_unit_test.go index 27a34fd0eb..deee1a7472 100644 --- a/models/repo/repo_unit_test.go +++ b/models/repo/repo_unit_test.go @@ -32,8 +32,8 @@ func TestActionsConfig(t *testing.T) { } func TestRepoUnitAccessMode(t *testing.T) { - assert.Equal(t, UnitAccessModeNone.ToAccessMode(perm.AccessModeAdmin), perm.AccessModeNone) - assert.Equal(t, UnitAccessModeRead.ToAccessMode(perm.AccessModeAdmin), perm.AccessModeRead) - assert.Equal(t, UnitAccessModeWrite.ToAccessMode(perm.AccessModeAdmin), perm.AccessModeWrite) - assert.Equal(t, UnitAccessModeUnset.ToAccessMode(perm.AccessModeRead), perm.AccessModeRead) + assert.Equal(t, perm.AccessModeNone, UnitAccessModeNone.ToAccessMode(perm.AccessModeAdmin)) + assert.Equal(t, perm.AccessModeRead, UnitAccessModeRead.ToAccessMode(perm.AccessModeAdmin)) + assert.Equal(t, perm.AccessModeWrite, UnitAccessModeWrite.ToAccessMode(perm.AccessModeAdmin)) + assert.Equal(t, perm.AccessModeRead, UnitAccessModeUnset.ToAccessMode(perm.AccessModeRead)) } diff --git a/models/repo/star_test.go b/models/repo/star_test.go index 62eac4e29a..73b362c68c 100644 --- a/models/repo/star_test.go +++ b/models/repo/star_test.go @@ -11,33 +11,34 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestStarRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) const userID = 2 const repoID = 1 unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) + require.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) + require.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, false)) + require.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, false)) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) } func TestIsStaring(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, repo_model.IsStaring(db.DefaultContext, 2, 4)) assert.False(t, repo_model.IsStaring(db.DefaultContext, 3, 4)) } func TestRepository_GetStargazers(t *testing.T) { // repo with stargazers - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, gazers, 1) { assert.Equal(t, int64(2), gazers[0].ID) } @@ -45,27 +46,27 @@ func TestRepository_GetStargazers(t *testing.T) { func TestRepository_GetStargazers2(t *testing.T) { // repo with stargazers - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) - assert.NoError(t, err) - assert.Len(t, gazers, 0) + require.NoError(t, err) + assert.Empty(t, gazers) } func TestClearRepoStars(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) const userID = 2 const repoID = 1 unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) + require.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, true)) unittest.AssertExistsAndLoadBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, false)) + require.NoError(t, repo_model.StarRepo(db.DefaultContext, userID, repoID, false)) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) - assert.NoError(t, repo_model.ClearRepoStars(db.DefaultContext, repoID)) + require.NoError(t, repo_model.ClearRepoStars(db.DefaultContext, repoID)) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) - assert.NoError(t, err) - assert.Len(t, gazers, 0) + require.NoError(t, err) + assert.Empty(t, gazers) } diff --git a/models/repo/topic_test.go b/models/repo/topic_test.go index 2b609e6d66..45cee524b6 100644 --- a/models/repo/topic_test.go +++ b/models/repo/topic_test.go @@ -11,58 +11,59 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAddTopic(t *testing.T) { totalNrOfTopics := 6 repo1NrOfTopics := 3 - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) topics, _, err := repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, topics, totalNrOfTopics) topics, total, err := repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{ ListOptions: db.ListOptions{Page: 1, PageSize: 2}, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, topics, 2) assert.EqualValues(t, 6, total) topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{ RepoID: 1, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, topics, repo1NrOfTopics) - assert.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang")) + require.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang")) repo2NrOfTopics := 1 topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, topics, totalNrOfTopics) topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{ RepoID: 2, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, topics, repo2NrOfTopics) - assert.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang", "gitea")) + require.NoError(t, repo_model.SaveTopics(db.DefaultContext, 2, "golang", "gitea")) repo2NrOfTopics = 2 totalNrOfTopics++ topic, err := repo_model.GetTopicByName(db.DefaultContext, "gitea") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, topic.RepoCount) topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, topics, totalNrOfTopics) topics, _, err = repo_model.FindTopics(db.DefaultContext, &repo_model.FindTopicOptions{ RepoID: 2, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, topics, repo2NrOfTopics) } diff --git a/models/repo/user_repo_test.go b/models/repo/user_repo_test.go index 0433ff83d8..c784a5565d 100644 --- a/models/repo/user_repo_test.go +++ b/models/repo/user_repo_test.go @@ -12,84 +12,85 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepoAssignees(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) users, err := repo_model.GetRepoAssignees(db.DefaultContext, repo2) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, users, 1) - assert.Equal(t, users[0].ID, int64(2)) + assert.Equal(t, int64(2), users[0].ID) repo21 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 21}) users, err = repo_model.GetRepoAssignees(db.DefaultContext, repo21) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, users, 3) { assert.ElementsMatch(t, []int64{15, 16, 18}, []int64{users[0].ID, users[1].ID, users[2].ID}) } // do not return deactivated users - assert.NoError(t, user_model.UpdateUserCols(db.DefaultContext, &user_model.User{ID: 15, IsActive: false}, "is_active")) + require.NoError(t, user_model.UpdateUserCols(db.DefaultContext, &user_model.User{ID: 15, IsActive: false}, "is_active")) users, err = repo_model.GetRepoAssignees(db.DefaultContext, repo21) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, users, 2) { assert.NotContains(t, []int64{users[0].ID, users[1].ID}, 15) } } func TestRepoGetReviewers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // test public repo repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) ctx := db.DefaultContext reviewers, err := repo_model.GetReviewers(ctx, repo1, 2, 2) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, reviewers, 3) { assert.ElementsMatch(t, []int64{1, 4, 11}, []int64{reviewers[0].ID, reviewers[1].ID, reviewers[2].ID}) } // should include doer if doer is not PR poster. reviewers, err = repo_model.GetReviewers(ctx, repo1, 11, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, reviewers, 3) // should not include PR poster, if PR poster would be otherwise eligible reviewers, err = repo_model.GetReviewers(ctx, repo1, 11, 4) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, reviewers, 2) // test private user repo repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) reviewers, err = repo_model.GetReviewers(ctx, repo2, 2, 4) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, reviewers, 1) - assert.EqualValues(t, reviewers[0].ID, 2) + assert.EqualValues(t, 2, reviewers[0].ID) // test private org repo repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) reviewers, err = repo_model.GetReviewers(ctx, repo3, 2, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, reviewers, 2) reviewers, err = repo_model.GetReviewers(ctx, repo3, 2, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, reviewers, 1) } func GetWatchedRepoIDsOwnedBy(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 9}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) repoIDs, err := repo_model.GetWatchedRepoIDsOwnedBy(db.DefaultContext, user1.ID, user2.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, repoIDs, 1) assert.EqualValues(t, 1, repoIDs[0]) } diff --git a/models/repo/watch_test.go b/models/repo/watch_test.go index 4dd9234f3b..dbf15050cf 100644 --- a/models/repo/watch_test.go +++ b/models/repo/watch_test.go @@ -12,10 +12,11 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIsWatching(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, repo_model.IsWatching(db.DefaultContext, 1, 1)) assert.True(t, repo_model.IsWatching(db.DefaultContext, 4, 1)) @@ -27,11 +28,11 @@ func TestIsWatching(t *testing.T) { } func TestGetWatchers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) watches, err := repo_model.GetWatchers(db.DefaultContext, repo.ID) - assert.NoError(t, err) + require.NoError(t, err) // One watchers are inactive, thus minus 1 assert.Len(t, watches, repo.NumWatches-1) for _, watch := range watches { @@ -39,16 +40,16 @@ func TestGetWatchers(t *testing.T) { } watches, err = repo_model.GetWatchers(db.DefaultContext, unittest.NonexistentID) - assert.NoError(t, err) - assert.Len(t, watches, 0) + require.NoError(t, err) + assert.Empty(t, watches) } func TestRepository_GetWatchers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) watchers, err := repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) for _, watcher := range watchers { unittest.AssertExistsAndLoadBean(t, &repo_model.Watch{UserID: watcher.ID, RepoID: repo.ID}) @@ -56,16 +57,16 @@ func TestRepository_GetWatchers(t *testing.T) { repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 9}) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) - assert.NoError(t, err) - assert.Len(t, watchers, 0) + require.NoError(t, err) + assert.Empty(t, watchers) } func TestWatchIfAuto(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) watchers, err := repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, watchers, repo.NumWatches) setting.Service.AutoWatchOnChanges = false @@ -73,79 +74,79 @@ func TestWatchIfAuto(t *testing.T) { prevCount := repo.NumWatches // Must not add watch - assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true)) + require.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true)) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, watchers, prevCount) // Should not add watch - assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 10, 1, true)) + require.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 10, 1, true)) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, watchers, prevCount) setting.Service.AutoWatchOnChanges = true // Must not add watch - assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true)) + require.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 8, 1, true)) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, watchers, prevCount) // Should not add watch - assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, false)) + require.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, false)) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, watchers, prevCount) // Should add watch - assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true)) + require.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true)) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, watchers, prevCount+1) // Should remove watch, inhibit from adding auto - assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, 12, 1, false)) + require.NoError(t, repo_model.WatchRepo(db.DefaultContext, 12, 1, false)) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, watchers, prevCount) // Must not add watch - assert.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true)) + require.NoError(t, repo_model.WatchIfAuto(db.DefaultContext, 12, 1, true)) watchers, err = repo_model.GetRepoWatchers(db.DefaultContext, repo.ID, db.ListOptions{Page: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, watchers, prevCount) } func TestWatchRepoMode(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) unittest.AssertCount(t, &repo_model.Watch{UserID: 12, RepoID: 1}, 0) - assert.NoError(t, repo_model.WatchRepoMode(db.DefaultContext, 12, 1, repo_model.WatchModeAuto)) + require.NoError(t, repo_model.WatchRepoMode(db.DefaultContext, 12, 1, repo_model.WatchModeAuto)) unittest.AssertCount(t, &repo_model.Watch{UserID: 12, RepoID: 1}, 1) unittest.AssertCount(t, &repo_model.Watch{UserID: 12, RepoID: 1, Mode: repo_model.WatchModeAuto}, 1) - assert.NoError(t, repo_model.WatchRepoMode(db.DefaultContext, 12, 1, repo_model.WatchModeNormal)) + require.NoError(t, repo_model.WatchRepoMode(db.DefaultContext, 12, 1, repo_model.WatchModeNormal)) unittest.AssertCount(t, &repo_model.Watch{UserID: 12, RepoID: 1}, 1) unittest.AssertCount(t, &repo_model.Watch{UserID: 12, RepoID: 1, Mode: repo_model.WatchModeNormal}, 1) - assert.NoError(t, repo_model.WatchRepoMode(db.DefaultContext, 12, 1, repo_model.WatchModeDont)) + require.NoError(t, repo_model.WatchRepoMode(db.DefaultContext, 12, 1, repo_model.WatchModeDont)) unittest.AssertCount(t, &repo_model.Watch{UserID: 12, RepoID: 1}, 1) unittest.AssertCount(t, &repo_model.Watch{UserID: 12, RepoID: 1, Mode: repo_model.WatchModeDont}, 1) - assert.NoError(t, repo_model.WatchRepoMode(db.DefaultContext, 12, 1, repo_model.WatchModeNone)) + require.NoError(t, repo_model.WatchRepoMode(db.DefaultContext, 12, 1, repo_model.WatchModeNone)) unittest.AssertCount(t, &repo_model.Watch{UserID: 12, RepoID: 1}, 0) } func TestUnwatchRepos(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) unittest.AssertExistsAndLoadBean(t, &repo_model.Watch{UserID: 4, RepoID: 1}) unittest.AssertExistsAndLoadBean(t, &repo_model.Watch{UserID: 4, RepoID: 2}) err := repo_model.UnwatchRepos(db.DefaultContext, 4, []int64{1, 2}) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertNotExistsBean(t, &repo_model.Watch{UserID: 4, RepoID: 1}) unittest.AssertNotExistsBean(t, &repo_model.Watch{UserID: 4, RepoID: 2}) diff --git a/models/repo/wiki_test.go b/models/repo/wiki_test.go index 629986f741..28495a4b7d 100644 --- a/models/repo/wiki_test.go +++ b/models/repo/wiki_test.go @@ -12,10 +12,11 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_WikiCloneLink(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) cloneLink := repo.WikiCloneLink() @@ -24,13 +25,13 @@ func TestRepository_WikiCloneLink(t *testing.T) { } func TestWikiPath(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) expected := filepath.Join(setting.RepoRootPath, "user2/repo1.wiki.git") assert.Equal(t, expected, repo_model.WikiPath("user2", "repo1")) } func TestRepository_WikiPath(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) expected := filepath.Join(setting.RepoRootPath, "user2/repo1.wiki.git") assert.Equal(t, expected, repo.WikiPath()) diff --git a/models/repo_test.go b/models/repo_test.go index 2a8a4a743e..958725fe53 100644 --- a/models/repo_test.go +++ b/models/repo_test.go @@ -9,16 +9,16 @@ import ( "code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/unittest" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCheckRepoStats(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) - assert.NoError(t, CheckRepoStats(db.DefaultContext)) + require.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, CheckRepoStats(db.DefaultContext)) } func TestDoctorUserStarNum(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) - assert.NoError(t, DoctorUserStarNum(db.DefaultContext)) + require.NoError(t, DoctorUserStarNum(db.DefaultContext)) } diff --git a/models/repo_transfer_test.go b/models/repo_transfer_test.go index 7ef29fae1f..6b6d5a8098 100644 --- a/models/repo_transfer_test.go +++ b/models/repo_transfer_test.go @@ -11,16 +11,17 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetPendingTransferIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) reciepient := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) pendingTransfer := unittest.AssertExistsAndLoadBean(t, &RepoTransfer{RecipientID: reciepient.ID, DoerID: doer.ID}) pendingTransferIDs, err := GetPendingTransferIDs(db.DefaultContext, reciepient.ID, doer.ID) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, pendingTransferIDs, 1) { assert.EqualValues(t, pendingTransfer.ID, pendingTransferIDs[0]) } diff --git a/models/system/notice_test.go b/models/system/notice_test.go index 599b2fb65c..bfb7862fd7 100644 --- a/models/system/notice_test.go +++ b/models/system/notice_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNotice_TrStr(t *testing.T) { @@ -22,48 +23,48 @@ func TestNotice_TrStr(t *testing.T) { } func TestCreateNotice(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) noticeBean := &system.Notice{ Type: system.NoticeRepository, Description: "test description", } unittest.AssertNotExistsBean(t, noticeBean) - assert.NoError(t, system.CreateNotice(db.DefaultContext, noticeBean.Type, noticeBean.Description)) + require.NoError(t, system.CreateNotice(db.DefaultContext, noticeBean.Type, noticeBean.Description)) unittest.AssertExistsAndLoadBean(t, noticeBean) } func TestCreateRepositoryNotice(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) noticeBean := &system.Notice{ Type: system.NoticeRepository, Description: "test description", } unittest.AssertNotExistsBean(t, noticeBean) - assert.NoError(t, system.CreateRepositoryNotice(noticeBean.Description)) + require.NoError(t, system.CreateRepositoryNotice(noticeBean.Description)) unittest.AssertExistsAndLoadBean(t, noticeBean) } // TODO TestRemoveAllWithNotice func TestCountNotices(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) assert.Equal(t, int64(3), system.CountNotices(db.DefaultContext)) } func TestNotices(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) notices, err := system.Notices(db.DefaultContext, 1, 2) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, notices, 2) { assert.Equal(t, int64(3), notices[0].ID) assert.Equal(t, int64(2), notices[1].ID) } notices, err = system.Notices(db.DefaultContext, 2, 2) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, notices, 1) { assert.Equal(t, int64(1), notices[0].ID) } @@ -71,12 +72,12 @@ func TestNotices(t *testing.T) { func TestDeleteNotices(t *testing.T) { // delete a non-empty range - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3}) - assert.NoError(t, system.DeleteNotices(db.DefaultContext, 1, 2)) + require.NoError(t, system.DeleteNotices(db.DefaultContext, 1, 2)) unittest.AssertNotExistsBean(t, &system.Notice{ID: 1}) unittest.AssertNotExistsBean(t, &system.Notice{ID: 2}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3}) @@ -84,25 +85,25 @@ func TestDeleteNotices(t *testing.T) { func TestDeleteNotices2(t *testing.T) { // delete an empty range - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3}) - assert.NoError(t, system.DeleteNotices(db.DefaultContext, 3, 2)) + require.NoError(t, system.DeleteNotices(db.DefaultContext, 3, 2)) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3}) } func TestDeleteNoticesByIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 1}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 3}) err := db.DeleteByIDs[system.Notice](db.DefaultContext, 1, 3) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertNotExistsBean(t, &system.Notice{ID: 1}) unittest.AssertExistsAndLoadBean(t, &system.Notice{ID: 2}) unittest.AssertNotExistsBean(t, &system.Notice{ID: 3}) diff --git a/models/system/setting_test.go b/models/system/setting_test.go index 8f04412fb4..7a7fa02b01 100644 --- a/models/system/setting_test.go +++ b/models/system/setting_test.go @@ -11,41 +11,42 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSettings(t *testing.T) { keyName := "test.key" - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) - assert.NoError(t, db.TruncateBeans(db.DefaultContext, &system.Setting{})) + require.NoError(t, db.TruncateBeans(db.DefaultContext, &system.Setting{})) rev, settings, err := system.GetAllSettings(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, rev) assert.Len(t, settings, 1) // there is only one "revision" key err = system.SetSettings(db.DefaultContext, map[string]string{keyName: "true"}) - assert.NoError(t, err) + require.NoError(t, err) rev, settings, err = system.GetAllSettings(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 2, rev) assert.Len(t, settings, 2) assert.EqualValues(t, "true", settings[keyName]) err = system.SetSettings(db.DefaultContext, map[string]string{keyName: "false"}) - assert.NoError(t, err) + require.NoError(t, err) rev, settings, err = system.GetAllSettings(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 3, rev) assert.Len(t, settings, 2) assert.EqualValues(t, "false", settings[keyName]) // setting the same value should not trigger DuplicateKey error, and the "version" should be increased err = system.SetSettings(db.DefaultContext, map[string]string{keyName: "false"}) - assert.NoError(t, err) + require.NoError(t, err) rev, settings, err = system.GetAllSettings(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, settings, 2) assert.EqualValues(t, 4, rev) } diff --git a/models/unit/unit_test.go b/models/unit/unit_test.go index 7bf6326145..a73967742f 100644 --- a/models/unit/unit_test.go +++ b/models/unit/unit_test.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLoadUnitConfig(t *testing.T) { @@ -27,7 +28,7 @@ func TestLoadUnitConfig(t *testing.T) { setting.Repository.DisabledRepoUnits = []string{"repo.issues"} setting.Repository.DefaultRepoUnits = []string{"repo.code", "repo.releases", "repo.issues", "repo.pulls"} setting.Repository.DefaultForkRepoUnits = []string{"repo.releases"} - assert.NoError(t, LoadUnitConfig()) + require.NoError(t, LoadUnitConfig()) assert.Equal(t, []Type{TypeIssues}, DisabledRepoUnitsGet()) assert.Equal(t, []Type{TypeCode, TypeReleases, TypePullRequests}, DefaultRepoUnits) assert.Equal(t, []Type{TypeReleases}, DefaultForkRepoUnits) @@ -47,7 +48,7 @@ func TestLoadUnitConfig(t *testing.T) { setting.Repository.DisabledRepoUnits = []string{"repo.issues", "invalid.1"} setting.Repository.DefaultRepoUnits = []string{"repo.code", "invalid.2", "repo.releases", "repo.issues", "repo.pulls"} setting.Repository.DefaultForkRepoUnits = []string{"invalid.3", "repo.releases"} - assert.NoError(t, LoadUnitConfig()) + require.NoError(t, LoadUnitConfig()) assert.Equal(t, []Type{TypeIssues}, DisabledRepoUnitsGet()) assert.Equal(t, []Type{TypeCode, TypeReleases, TypePullRequests}, DefaultRepoUnits) assert.Equal(t, []Type{TypeReleases}, DefaultForkRepoUnits) @@ -67,7 +68,7 @@ func TestLoadUnitConfig(t *testing.T) { setting.Repository.DisabledRepoUnits = []string{"repo.issues", "repo.issues"} setting.Repository.DefaultRepoUnits = []string{"repo.code", "repo.releases", "repo.issues", "repo.pulls", "repo.code"} setting.Repository.DefaultForkRepoUnits = []string{"repo.releases", "repo.releases"} - assert.NoError(t, LoadUnitConfig()) + require.NoError(t, LoadUnitConfig()) assert.Equal(t, []Type{TypeIssues}, DisabledRepoUnitsGet()) assert.Equal(t, []Type{TypeCode, TypeReleases, TypePullRequests}, DefaultRepoUnits) assert.Equal(t, []Type{TypeReleases}, DefaultForkRepoUnits) @@ -87,7 +88,7 @@ func TestLoadUnitConfig(t *testing.T) { setting.Repository.DisabledRepoUnits = []string{"repo.issues", "repo.issues"} setting.Repository.DefaultRepoUnits = []string{} setting.Repository.DefaultForkRepoUnits = []string{"repo.releases", "repo.releases"} - assert.NoError(t, LoadUnitConfig()) + require.NoError(t, LoadUnitConfig()) assert.Equal(t, []Type{TypeIssues}, DisabledRepoUnitsGet()) assert.ElementsMatch(t, []Type{TypeCode, TypePullRequests, TypeReleases, TypeWiki, TypePackages, TypeProjects, TypeActions}, DefaultRepoUnits) assert.Equal(t, []Type{TypeReleases}, DefaultForkRepoUnits) diff --git a/models/unittest/consistency.go b/models/unittest/consistency.go index 71839001be..4e26de7503 100644 --- a/models/unittest/consistency.go +++ b/models/unittest/consistency.go @@ -7,10 +7,12 @@ import ( "reflect" "strconv" "strings" + "testing" "code.gitea.io/gitea/models/db" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/builder" ) @@ -21,10 +23,10 @@ const ( modelsCommentTypeComment = 0 ) -var consistencyCheckMap = make(map[string]func(t assert.TestingT, bean any)) +var consistencyCheckMap = make(map[string]func(t *testing.T, bean any)) // CheckConsistencyFor test that all matching database entries are consistent -func CheckConsistencyFor(t assert.TestingT, beansToCheck ...any) { +func CheckConsistencyFor(t *testing.T, beansToCheck ...any) { for _, bean := range beansToCheck { sliceType := reflect.SliceOf(reflect.TypeOf(bean)) sliceValue := reflect.MakeSlice(sliceType, 0, 10) @@ -32,7 +34,7 @@ func CheckConsistencyFor(t assert.TestingT, beansToCheck ...any) { ptrToSliceValue := reflect.New(sliceType) ptrToSliceValue.Elem().Set(sliceValue) - assert.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface())) + require.NoError(t, db.GetEngine(db.DefaultContext).Table(bean).Find(ptrToSliceValue.Interface())) sliceValue = ptrToSliceValue.Elem() for i := 0; i < sliceValue.Len(); i++ { @@ -42,9 +44,9 @@ func CheckConsistencyFor(t assert.TestingT, beansToCheck ...any) { } } -func checkForConsistency(t assert.TestingT, bean any) { +func checkForConsistency(t *testing.T, bean any) { tb, err := db.TableInfo(bean) - assert.NoError(t, err) + require.NoError(t, err) f := consistencyCheckMap[tb.Name] if f == nil { assert.FailNow(t, "unknown bean type: %#v", bean) @@ -62,7 +64,7 @@ func init() { return i } - checkForUserConsistency := func(t assert.TestingT, bean any) { + checkForUserConsistency := func(t *testing.T, bean any) { user := reflectionWrap(bean) AssertCountByCond(t, "repository", builder.Eq{"owner_id": user.int("ID")}, user.int("NumRepos")) AssertCountByCond(t, "star", builder.Eq{"uid": user.int("ID")}, user.int("NumStars")) @@ -76,7 +78,7 @@ func init() { } } - checkForRepoConsistency := func(t assert.TestingT, bean any) { + checkForRepoConsistency := func(t *testing.T, bean any) { repo := reflectionWrap(bean) assert.Equal(t, repo.str("LowerName"), strings.ToLower(repo.str("Name")), "repo: %+v", repo) AssertCountByCond(t, "star", builder.Eq{"repo_id": repo.int("ID")}, repo.int("NumStars")) @@ -112,7 +114,7 @@ func init() { "Unexpected number of closed milestones for repo id: %d", repo.int("ID")) } - checkForIssueConsistency := func(t assert.TestingT, bean any) { + checkForIssueConsistency := func(t *testing.T, bean any) { issue := reflectionWrap(bean) typeComment := modelsCommentTypeComment actual := GetCountByCond(t, "comment", builder.Eq{"`type`": typeComment, "issue_id": issue.int("ID")}) @@ -123,14 +125,14 @@ func init() { } } - checkForPullRequestConsistency := func(t assert.TestingT, bean any) { + checkForPullRequestConsistency := func(t *testing.T, bean any) { pr := reflectionWrap(bean) issueRow := AssertExistsAndLoadMap(t, "issue", builder.Eq{"id": pr.int("IssueID")}) assert.True(t, parseBool(issueRow["is_pull"])) assert.EqualValues(t, parseInt(issueRow["index"]), pr.int("Index"), "Unexpected index for pull request id: %d", pr.int("ID")) } - checkForMilestoneConsistency := func(t assert.TestingT, bean any) { + checkForMilestoneConsistency := func(t *testing.T, bean any) { milestone := reflectionWrap(bean) AssertCountByCond(t, "issue", builder.Eq{"milestone_id": milestone.int("ID")}, milestone.int("NumIssues")) @@ -144,12 +146,12 @@ func init() { assert.Equal(t, completeness, milestone.int("Completeness")) } - checkForLabelConsistency := func(t assert.TestingT, bean any) { + checkForLabelConsistency := func(t *testing.T, bean any) { label := reflectionWrap(bean) issueLabels, err := db.GetEngine(db.DefaultContext).Table("issue_label"). Where(builder.Eq{"label_id": label.int("ID")}). Query() - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, issueLabels, label.int("NumIssues"), "Unexpected number of issue for label id: %d", label.int("ID")) @@ -165,13 +167,13 @@ func init() { assert.EqualValues(t, expected, label.int("NumClosedIssues"), "Unexpected number of closed issues for label id: %d", label.int("ID")) } - checkForTeamConsistency := func(t assert.TestingT, bean any) { + checkForTeamConsistency := func(t *testing.T, bean any) { team := reflectionWrap(bean) AssertCountByCond(t, "team_user", builder.Eq{"team_id": team.int("ID")}, team.int("NumMembers")) AssertCountByCond(t, "team_repo", builder.Eq{"team_id": team.int("ID")}, team.int("NumRepos")) } - checkForActionConsistency := func(t assert.TestingT, bean any) { + checkForActionConsistency := func(t *testing.T, bean any) { action := reflectionWrap(bean) if action.int("RepoID") != 1700 { // dangling intentional repoRow := AssertExistsAndLoadMap(t, "repository", builder.Eq{"id": action.int("RepoID")}) diff --git a/models/unittest/mock_http.go b/models/unittest/mock_http.go index e2c181408b..aea2489d2a 100644 --- a/models/unittest/mock_http.go +++ b/models/unittest/mock_http.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/modules/log" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // Mocks HTTP responses of a third-party service (such as GitHub, GitLab…) @@ -39,7 +40,7 @@ func NewMockWebServer(t *testing.T, liveServerBaseURL, testDataDir string, liveM liveURL := fmt.Sprintf("%s%s", liveServerBaseURL, path) request, err := http.NewRequest(r.Method, liveURL, nil) - assert.NoError(t, err, "constructing an HTTP request to %s failed", liveURL) + require.NoError(t, err, "constructing an HTTP request to %s failed", liveURL) for headerName, headerValues := range r.Header { // do not pass on the encoding: let the Transport of the HTTP client handle that for us if strings.ToLower(headerName) != "accept-encoding" { @@ -50,11 +51,11 @@ func NewMockWebServer(t *testing.T, liveServerBaseURL, testDataDir string, liveM } response, err := http.DefaultClient.Do(request) - assert.NoError(t, err, "HTTP request to %s failed: %s", liveURL) + require.NoError(t, err, "HTTP request to %s failed: %s", liveURL) assert.Less(t, response.StatusCode, 400, "unexpected status code for %s", liveURL) fixture, err := os.Create(fixturePath) - assert.NoError(t, err, "failed to open the fixture file %s for writing", fixturePath) + require.NoError(t, err, "failed to open the fixture file %s for writing", fixturePath) defer fixture.Close() fixtureWriter := bufio.NewWriter(fixture) @@ -62,24 +63,24 @@ func NewMockWebServer(t *testing.T, liveServerBaseURL, testDataDir string, liveM for _, headerValue := range headerValues { if !slices.Contains(ignoredHeaders, strings.ToLower(headerName)) { _, err := fixtureWriter.WriteString(fmt.Sprintf("%s: %s\n", headerName, headerValue)) - assert.NoError(t, err, "writing the header of the HTTP response to the fixture file failed") + require.NoError(t, err, "writing the header of the HTTP response to the fixture file failed") } } } _, err = fixtureWriter.WriteString("\n") - assert.NoError(t, err, "writing the header of the HTTP response to the fixture file failed") + require.NoError(t, err, "writing the header of the HTTP response to the fixture file failed") fixtureWriter.Flush() log.Info("Mock HTTP Server: writing response to %s", fixturePath) _, err = io.Copy(fixture, response.Body) - assert.NoError(t, err, "writing the body of the HTTP response to %s failed", liveURL) + require.NoError(t, err, "writing the body of the HTTP response to %s failed", liveURL) err = fixture.Sync() - assert.NoError(t, err, "writing the body of the HTTP response to the fixture file failed") + require.NoError(t, err, "writing the body of the HTTP response to the fixture file failed") } fixture, err := os.ReadFile(fixturePath) - assert.NoError(t, err, "missing mock HTTP response: "+fixturePath) + require.NoError(t, err, "missing mock HTTP response: "+fixturePath) w.WriteHeader(http.StatusOK) @@ -95,7 +96,7 @@ func NewMockWebServer(t *testing.T, liveServerBaseURL, testDataDir string, liveM // we reached the end of the headers (empty line), so what follows is the body responseBody := strings.Join(lines[idx+1:], "\n") _, err := w.Write([]byte(responseBody)) - assert.NoError(t, err, "writing the body of the HTTP response failed") + require.NoError(t, err, "writing the body of the HTTP response failed") break } } diff --git a/models/unittest/testdb.go b/models/unittest/testdb.go index af5c31f157..94a3253644 100644 --- a/models/unittest/testdb.go +++ b/models/unittest/testdb.go @@ -22,7 +22,7 @@ import ( "code.gitea.io/gitea/modules/storage" "code.gitea.io/gitea/modules/util" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/xorm" "xorm.io/xorm/names" ) @@ -243,18 +243,18 @@ func PrepareTestDatabase() error { // 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)) + require.NoError(t, PrepareTestDatabase()) + require.NoError(t, util.RemoveAll(setting.RepoRootPath)) metaPath := filepath.Join(giteaRoot, "tests", "gitea-repositories-meta") - assert.NoError(t, CopyDir(metaPath, setting.RepoRootPath)) + require.NoError(t, CopyDir(metaPath, setting.RepoRootPath)) ownerDirs, err := os.ReadDir(setting.RepoRootPath) - assert.NoError(t, err) + require.NoError(t, err) for _, ownerDir := range ownerDirs { if !ownerDir.Type().IsDir() { continue } repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name())) - assert.NoError(t, err) + require.NoError(t, err) for _, repoDir := range repoDirs { _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "pack"), 0o755) _ = os.MkdirAll(filepath.Join(setting.RepoRootPath, ownerDir.Name(), repoDir.Name(), "objects", "info"), 0o755) diff --git a/models/unittest/unit_tests.go b/models/unittest/unit_tests.go index 00c7dd8453..157c676d09 100644 --- a/models/unittest/unit_tests.go +++ b/models/unittest/unit_tests.go @@ -5,6 +5,7 @@ package unittest import ( "math" + "testing" "code.gitea.io/gitea/models/db" @@ -58,16 +59,16 @@ func LoadBeanIfExists(bean any, conditions ...any) (bool, error) { } // BeanExists for testing, check if a bean exists -func BeanExists(t assert.TestingT, bean any, conditions ...any) bool { +func BeanExists(t testing.TB, bean any, conditions ...any) bool { exists, err := LoadBeanIfExists(bean, conditions...) - assert.NoError(t, err) + require.NoError(t, err) return exists } // AssertExistsAndLoadBean assert that a bean exists and load it from the test database -func AssertExistsAndLoadBean[T any](t assert.TestingT, bean T, conditions ...any) T { +func AssertExistsAndLoadBean[T any](t testing.TB, bean T, conditions ...any) T { exists, err := LoadBeanIfExists(bean, conditions...) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exists, "Expected to find %+v (of type %T, with conditions %+v), but did not", bean, bean, conditions) @@ -75,11 +76,11 @@ func AssertExistsAndLoadBean[T any](t assert.TestingT, bean T, conditions ...any } // AssertExistsAndLoadMap assert that a row exists and load it from the test database -func AssertExistsAndLoadMap(t assert.TestingT, table string, conditions ...any) map[string]string { +func AssertExistsAndLoadMap(t testing.TB, table string, conditions ...any) map[string]string { e := db.GetEngine(db.DefaultContext).Table(table) res, err := whereOrderConditions(e, conditions).Query() - assert.NoError(t, err) - assert.True(t, len(res) == 1, + require.NoError(t, err) + assert.Len(t, res, 1, "Expected to find one row in %s (with conditions %+v), but found %d", table, conditions, len(res), ) @@ -95,7 +96,7 @@ func AssertExistsAndLoadMap(t assert.TestingT, table string, conditions ...any) } // GetCount get the count of a bean -func GetCount(t assert.TestingT, bean any, conditions ...any) int { +func GetCount(t testing.TB, bean any, conditions ...any) int { e := db.GetEngine(db.DefaultContext) for _, condition := range conditions { switch cond := condition.(type) { @@ -106,29 +107,29 @@ func GetCount(t assert.TestingT, bean any, conditions ...any) int { } } count, err := e.Count(bean) - assert.NoError(t, err) + require.NoError(t, err) return int(count) } // AssertNotExistsBean assert that a bean does not exist in the test database -func AssertNotExistsBean(t assert.TestingT, bean any, conditions ...any) { +func AssertNotExistsBean(t testing.TB, bean any, conditions ...any) { exists, err := LoadBeanIfExists(bean, conditions...) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exists) } // AssertExistsIf asserts that a bean exists or does not exist, depending on // what is expected. -func AssertExistsIf(t assert.TestingT, expected bool, bean any, conditions ...any) { +func AssertExistsIf(t testing.TB, expected bool, bean any, conditions ...any) { exists, err := LoadBeanIfExists(bean, conditions...) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, exists) } // AssertSuccessfulInsert assert that beans is successfully inserted -func AssertSuccessfulInsert(t assert.TestingT, beans ...any) { +func AssertSuccessfulInsert(t testing.TB, beans ...any) { err := db.Insert(db.DefaultContext, beans...) - assert.NoError(t, err) + require.NoError(t, err) } // AssertSuccessfulDelete assert that beans is successfully deleted @@ -138,26 +139,26 @@ func AssertSuccessfulDelete(t require.TestingT, beans ...any) { } // AssertCount assert the count of a bean -func AssertCount(t assert.TestingT, bean, expected any) bool { +func AssertCount(t testing.TB, bean, expected any) bool { return assert.EqualValues(t, expected, GetCount(t, bean)) } // AssertInt64InRange assert value is in range [low, high] -func AssertInt64InRange(t assert.TestingT, low, high, value int64) { +func AssertInt64InRange(t testing.TB, low, high, value int64) { assert.True(t, value >= low && value <= high, "Expected value in range [%d, %d], found %d", low, high, value) } // GetCountByCond get the count of database entries matching bean -func GetCountByCond(t assert.TestingT, tableName string, cond builder.Cond) int64 { +func GetCountByCond(t testing.TB, tableName string, cond builder.Cond) int64 { e := db.GetEngine(db.DefaultContext) count, err := e.Table(tableName).Where(cond).Count() - assert.NoError(t, err) + require.NoError(t, err) return count } // AssertCountByCond test the count of database entries matching bean -func AssertCountByCond(t assert.TestingT, tableName string, cond builder.Cond, expected int) bool { +func AssertCountByCond(t testing.TB, tableName string, cond builder.Cond, expected int) bool { return assert.EqualValues(t, expected, GetCountByCond(t, tableName, cond), "Failed consistency test, the counted bean (of table %s) was %+v", tableName, cond) } diff --git a/models/user/block_test.go b/models/user/block_test.go index 629c0c975a..a795ef345e 100644 --- a/models/user/block_test.go +++ b/models/user/block_test.go @@ -11,10 +11,11 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIsBlocked(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, user_model.IsBlocked(db.DefaultContext, 4, 1)) // Simple test cases to ensure the function can also respond with false. @@ -23,7 +24,7 @@ func TestIsBlocked(t *testing.T) { } func TestIsBlockedMultiple(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, user_model.IsBlockedMultiple(db.DefaultContext, []int64{4}, 1)) assert.True(t, user_model.IsBlockedMultiple(db.DefaultContext, []int64{4, 3, 4, 5}, 1)) @@ -33,20 +34,20 @@ func TestIsBlockedMultiple(t *testing.T) { } func TestUnblockUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, user_model.IsBlocked(db.DefaultContext, 4, 1)) - assert.NoError(t, user_model.UnblockUser(db.DefaultContext, 4, 1)) + require.NoError(t, user_model.UnblockUser(db.DefaultContext, 4, 1)) // Simple test cases to ensure the function can also respond with false. assert.False(t, user_model.IsBlocked(db.DefaultContext, 4, 1)) } func TestListBlockedUsers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) blockedUsers, err := user_model.ListBlockedUsers(db.DefaultContext, 4, db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, blockedUsers, 1) { assert.EqualValues(t, 1, blockedUsers[0].ID) // The function returns the created Unix of the block, not that of the user. @@ -55,23 +56,23 @@ func TestListBlockedUsers(t *testing.T) { } func TestListBlockedByUsersID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) blockedByUserIDs, err := user_model.ListBlockedByUsersID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, blockedByUserIDs, 1) { assert.EqualValues(t, 4, blockedByUserIDs[0]) } } func TestCountBlockedUsers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) count, err := user_model.CountBlockedUsers(db.DefaultContext, 4) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, count) count, err = user_model.CountBlockedUsers(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, count) } diff --git a/models/user/email_address_test.go b/models/user/email_address_test.go index 94680b6bd5..b918f21018 100644 --- a/models/user/email_address_test.go +++ b/models/user/email_address_test.go @@ -13,10 +13,11 @@ import ( "code.gitea.io/gitea/modules/optional" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetEmailAddresses(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) emails, _ := user_model.GetEmailAddresses(db.DefaultContext, int64(1)) if assert.Len(t, emails, 3) { @@ -33,7 +34,7 @@ func TestGetEmailAddresses(t *testing.T) { } func TestIsEmailUsed(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) isExist, _ := user_model.IsEmailUsed(db.DefaultContext, "") assert.True(t, isExist) @@ -44,14 +45,14 @@ func TestIsEmailUsed(t *testing.T) { } func TestActivate(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) email := &user_model.EmailAddress{ ID: int64(1), UID: int64(1), Email: "user11@example.com", } - assert.NoError(t, user_model.ActivateEmail(db.DefaultContext, email)) + require.NoError(t, user_model.ActivateEmail(db.DefaultContext, email)) emails, _ := user_model.GetEmailAddresses(db.DefaultContext, int64(1)) assert.Len(t, emails, 3) @@ -63,7 +64,7 @@ func TestActivate(t *testing.T) { } func TestListEmails(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // Must find all users and their emails opts := &user_model.SearchEmailOptions{ @@ -72,9 +73,8 @@ func TestListEmails(t *testing.T) { }, } emails, count, err := user_model.SearchEmails(db.DefaultContext, opts) - assert.NoError(t, err) - assert.NotEqual(t, int64(0), count) - assert.True(t, count > 5) + require.NoError(t, err) + assert.Greater(t, count, int64(5)) contains := func(match func(s *user_model.SearchEmailResult) bool) bool { for _, v := range emails { @@ -92,13 +92,13 @@ func TestListEmails(t *testing.T) { // Must find no records opts = &user_model.SearchEmailOptions{Keyword: "NOTFOUND"} emails, count, err = user_model.SearchEmails(db.DefaultContext, opts) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(0), count) // Must find users 'user2', 'user28', etc. opts = &user_model.SearchEmailOptions{Keyword: "user2"} emails, count, err = user_model.SearchEmails(db.DefaultContext, opts) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, int64(0), count) assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 2 })) assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.UID == 27 })) @@ -106,14 +106,14 @@ func TestListEmails(t *testing.T) { // Must find only primary addresses (i.e. from the `user` table) opts = &user_model.SearchEmailOptions{IsPrimary: optional.Some(true)} emails, _, err = user_model.SearchEmails(db.DefaultContext, opts) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return s.IsPrimary })) assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return !s.IsPrimary })) // Must find only inactive addresses (i.e. not validated) opts = &user_model.SearchEmailOptions{IsActivated: optional.Some(false)} emails, _, err = user_model.SearchEmails(db.DefaultContext, opts) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, contains(func(s *user_model.SearchEmailResult) bool { return !s.IsActivated })) assert.False(t, contains(func(s *user_model.SearchEmailResult) bool { return s.IsActivated })) @@ -125,7 +125,7 @@ func TestListEmails(t *testing.T) { }, } emails, count, err = user_model.SearchEmails(db.DefaultContext, opts) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, emails, 5) assert.Greater(t, count, int64(len(emails))) } @@ -188,7 +188,7 @@ func TestEmailAddressValidate(t *testing.T) { } func TestGetActivatedEmailAddresses(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testCases := []struct { UID int64 @@ -215,7 +215,7 @@ func TestGetActivatedEmailAddresses(t *testing.T) { for _, testCase := range testCases { t.Run(fmt.Sprintf("User %d", testCase.UID), func(t *testing.T) { emails, err := user_model.GetActivatedEmailAddresses(db.DefaultContext, testCase.UID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, testCase.expected, emails) }) } diff --git a/models/user/follow_test.go b/models/user/follow_test.go index c327d935ae..8c56164ee3 100644 --- a/models/user/follow_test.go +++ b/models/user/follow_test.go @@ -11,10 +11,11 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIsFollowing(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) assert.True(t, user_model.IsFollowing(db.DefaultContext, 4, 2)) assert.False(t, user_model.IsFollowing(db.DefaultContext, 2, 4)) assert.False(t, user_model.IsFollowing(db.DefaultContext, 5, unittest.NonexistentID)) diff --git a/models/user/openid_test.go b/models/user/openid_test.go index 27e6edd1e0..c2857aac98 100644 --- a/models/user/openid_test.go +++ b/models/user/openid_test.go @@ -11,13 +11,16 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetUserOpenIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(1)) - if assert.NoError(t, err) && assert.Len(t, oids, 2) { + require.NoError(t, err) + + if assert.Len(t, oids, 2) { assert.Equal(t, "https://user1.domain1.tld/", oids[0].URI) assert.False(t, oids[0].Show) assert.Equal(t, "http://user1.domain2.tld/", oids[1].URI) @@ -25,39 +28,40 @@ func TestGetUserOpenIDs(t *testing.T) { } oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) - if assert.NoError(t, err) && assert.Len(t, oids, 1) { + require.NoError(t, err) + + if assert.Len(t, oids, 1) { assert.Equal(t, "https://domain1.tld/user2/", oids[0].URI) assert.True(t, oids[0].Show) } } func TestToggleUserOpenIDVisibility(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) oids, err := user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) - if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { + require.NoError(t, err) + + if !assert.Len(t, oids, 1) { return } assert.True(t, oids[0].Show) err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) - if !assert.NoError(t, err) || !assert.Len(t, oids, 1) { + require.NoError(t, err) + + if !assert.Len(t, oids, 1) { return } assert.False(t, oids[0].Show) err = user_model.ToggleUserOpenIDVisibility(db.DefaultContext, oids[0].ID) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) oids, err = user_model.GetUserOpenIDs(db.DefaultContext, int64(2)) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + if assert.Len(t, oids, 1) { assert.True(t, oids[0].Show) } diff --git a/models/user/redirect_test.go b/models/user/redirect_test.go index 484c5a663f..35fd29aa5d 100644 --- a/models/user/redirect_test.go +++ b/models/user/redirect_test.go @@ -11,13 +11,14 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLookupUserRedirect(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) userID, err := user_model.LookupUserRedirect(db.DefaultContext, "olduser1") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, userID) _, err = user_model.LookupUserRedirect(db.DefaultContext, "doesnotexist") diff --git a/models/user/setting_test.go b/models/user/setting_test.go index c56fe93075..0b05c54ee6 100644 --- a/models/user/setting_test.go +++ b/models/user/setting_test.go @@ -11,50 +11,51 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSettings(t *testing.T) { keyName := "test_user_setting" - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) newSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Gitea User Setting Test"} // create setting err := user_model.SetUserSetting(db.DefaultContext, newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) - assert.NoError(t, err) + require.NoError(t, err) // test about saving unchanged values err = user_model.SetUserSetting(db.DefaultContext, newSetting.UserID, newSetting.SettingKey, newSetting.SettingValue) - assert.NoError(t, err) + require.NoError(t, err) // get specific setting settings, err := user_model.GetSettings(db.DefaultContext, 99, []string{keyName}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, settings, 1) assert.EqualValues(t, newSetting.SettingValue, settings[keyName].SettingValue) settingValue, err := user_model.GetUserSetting(db.DefaultContext, 99, keyName) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, newSetting.SettingValue, settingValue) settingValue, err = user_model.GetUserSetting(db.DefaultContext, 99, "no_such") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "", settingValue) // updated setting updatedSetting := &user_model.Setting{UserID: 99, SettingKey: keyName, SettingValue: "Updated"} err = user_model.SetUserSetting(db.DefaultContext, updatedSetting.UserID, updatedSetting.SettingKey, updatedSetting.SettingValue) - assert.NoError(t, err) + require.NoError(t, err) // get all settings settings, err = user_model.GetUserAllSettings(db.DefaultContext, 99) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, settings, 1) assert.EqualValues(t, updatedSetting.SettingValue, settings[updatedSetting.SettingKey].SettingValue) // delete setting err = user_model.DeleteUserSetting(db.DefaultContext, 99, keyName) - assert.NoError(t, err) + require.NoError(t, err) settings, err = user_model.GetUserAllSettings(db.DefaultContext, 99) - assert.NoError(t, err) - assert.Len(t, settings, 0) + require.NoError(t, err) + assert.Empty(t, settings) } diff --git a/models/user/user_test.go b/models/user/user_test.go index 5bd1f21b5c..1d49402c19 100644 --- a/models/user/user_test.go +++ b/models/user/user_test.go @@ -25,13 +25,14 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestOAuth2Application_LoadUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) app := unittest.AssertExistsAndLoadBean(t, &auth.OAuth2Application{ID: 1}) user, err := user_model.GetUserByID(db.DefaultContext, app.UID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, user) } @@ -70,7 +71,7 @@ func TestGetUserFromMap(t *testing.T) { func TestGetUserByName(t *testing.T) { defer tests.AddFixtures("models/user/fixtures/")() - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) { _, err := user_model.GetUserByName(db.DefaultContext, "") @@ -82,23 +83,23 @@ func TestGetUserByName(t *testing.T) { } { user, err := user_model.GetUserByName(db.DefaultContext, "USER2") - assert.NoError(t, err) - assert.Equal(t, user.Name, "user2") + require.NoError(t, err) + assert.Equal(t, "user2", user.Name) } { user, err := user_model.GetUserByName(db.DefaultContext, "org3") - assert.NoError(t, err) - assert.Equal(t, user.Name, "org3") + require.NoError(t, err) + assert.Equal(t, "org3", user.Name) } { user, err := user_model.GetUserByName(db.DefaultContext, "remote01") - assert.NoError(t, err) - assert.Equal(t, user.Name, "remote01") + require.NoError(t, err) + assert.Equal(t, "remote01", user.Name) } } func TestGetUserEmailsByNames(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // ignore none active user email assert.ElementsMatch(t, []string{"user8@example.com"}, user_model.GetUserEmailsByNames(db.DefaultContext, []string{"user8", "user9"})) @@ -108,7 +109,7 @@ func TestGetUserEmailsByNames(t *testing.T) { } func TestCanCreateOrganization(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) assert.True(t, admin.CanCreateOrganization()) @@ -127,10 +128,10 @@ func TestCanCreateOrganization(t *testing.T) { func TestGetAllUsers(t *testing.T) { defer tests.AddFixtures("models/user/fixtures/")() - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) users, err := user_model.GetAllUsers(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) found := make(map[user_model.UserType]bool, 0) for _, user := range users { @@ -152,10 +153,10 @@ func TestAPActorID(t *testing.T) { func TestSearchUsers(t *testing.T) { defer tests.AddFixtures("models/user/fixtures/")() - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(opts *user_model.SearchUserOptions, expectedUserOrOrgIDs []int64) { users, _, err := user_model.SearchUsers(db.DefaultContext, opts) - assert.NoError(t, err) + require.NoError(t, err) cassText := fmt.Sprintf("ids: %v, opts: %v", expectedUserOrOrgIDs, opts) if assert.Len(t, users, len(expectedUserOrOrgIDs), "case: %s", cassText) { for i, expectedID := range expectedUserOrOrgIDs { @@ -221,7 +222,7 @@ func TestSearchUsers(t *testing.T) { } func TestEmailNotificationPreferences(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) for _, test := range []struct { expected string @@ -281,21 +282,21 @@ func BenchmarkHashPassword(b *testing.B) { func TestNewGitSig(t *testing.T) { users := make([]*user_model.User, 0, 20) err := db.GetEngine(db.DefaultContext).Find(&users) - assert.NoError(t, err) + require.NoError(t, err) for _, user := range users { sig := user.NewGitSig() assert.NotContains(t, sig.Name, "<") assert.NotContains(t, sig.Name, ">") assert.NotContains(t, sig.Name, "\n") - assert.NotEqual(t, len(strings.TrimSpace(sig.Name)), 0) + assert.NotEmpty(t, strings.TrimSpace(sig.Name)) } } func TestDisplayName(t *testing.T) { users := make([]*user_model.User, 0, 20) err := db.GetEngine(db.DefaultContext).Find(&users) - assert.NoError(t, err) + require.NoError(t, err) for _, user := range users { displayName := user.DisplayName() @@ -303,7 +304,7 @@ func TestDisplayName(t *testing.T) { if len(strings.TrimSpace(user.FullName)) == 0 { assert.Equal(t, user.Name, displayName) } - assert.NotEqual(t, len(strings.TrimSpace(displayName)), 0) + assert.NotEmpty(t, strings.TrimSpace(displayName)) } } @@ -318,12 +319,12 @@ func TestCreateUserInvalidEmail(t *testing.T) { } err := user_model.CreateUser(db.DefaultContext, user) - assert.Error(t, err) + require.Error(t, err) assert.True(t, user_model.IsErrEmailCharIsNotSupported(err)) } func TestCreateUserEmailAlreadyUsed(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -332,12 +333,12 @@ func TestCreateUserEmailAlreadyUsed(t *testing.T) { user.LowerName = strings.ToLower(user.Name) user.ID = 0 err := user_model.CreateUser(db.DefaultContext, user) - assert.Error(t, err) + require.Error(t, err) assert.True(t, user_model.IsErrEmailAlreadyUsed(err)) } func TestCreateUserCustomTimestamps(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -349,16 +350,16 @@ func TestCreateUserCustomTimestamps(t *testing.T) { user.Email = "unique@example.com" user.CreatedUnix = creationTimestamp err := user_model.CreateUser(db.DefaultContext, user) - assert.NoError(t, err) + require.NoError(t, err) fetched, err := user_model.GetUserByID(context.Background(), user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, creationTimestamp, fetched.CreatedUnix) assert.Equal(t, creationTimestamp, fetched.UpdatedUnix) } func TestCreateUserWithoutCustomTimestamps(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -374,12 +375,12 @@ func TestCreateUserWithoutCustomTimestamps(t *testing.T) { user.CreatedUnix = 0 user.UpdatedUnix = 0 err := user_model.CreateUser(db.DefaultContext, user) - assert.NoError(t, err) + require.NoError(t, err) timestampEnd := time.Now().Unix() fetched, err := user_model.GetUserByID(context.Background(), user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.LessOrEqual(t, timestampStart, fetched.CreatedUnix) assert.LessOrEqual(t, fetched.CreatedUnix, timestampEnd) @@ -389,44 +390,44 @@ func TestCreateUserWithoutCustomTimestamps(t *testing.T) { } func TestGetUserIDsByNames(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // ignore non existing IDs, err := user_model.GetUserIDsByNames(db.DefaultContext, []string{"user1", "user2", "none_existing_user"}, true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []int64{1, 2}, IDs) // ignore non existing IDs, err = user_model.GetUserIDsByNames(db.DefaultContext, []string{"user1", "do_not_exist"}, false) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, []int64(nil), IDs) } func TestGetMaileableUsersByIDs(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) results, err := user_model.GetMaileableUsersByIDs(db.DefaultContext, []int64{1, 4}, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, results, 1) if len(results) > 1 { - assert.Equal(t, results[0].ID, 1) + assert.Equal(t, 1, results[0].ID) } results, err = user_model.GetMaileableUsersByIDs(db.DefaultContext, []int64{1, 4}, true) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, results, 2) if len(results) > 2 { - assert.Equal(t, results[0].ID, 1) - assert.Equal(t, results[1].ID, 4) + assert.Equal(t, 1, results[0].ID) + assert.Equal(t, 4, results[1].ID) } } func TestNewUserRedirect(t *testing.T) { // redirect to a completely new name - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "newusername")) + require.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "newusername")) unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{ LowerName: user.LowerName, @@ -440,10 +441,10 @@ func TestNewUserRedirect(t *testing.T) { func TestNewUserRedirect2(t *testing.T) { // redirect to previously used name - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "olduser1")) + require.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "olduser1")) unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{ LowerName: user.LowerName, @@ -457,10 +458,10 @@ func TestNewUserRedirect2(t *testing.T) { func TestNewUserRedirect3(t *testing.T) { // redirect for a previously-unredirected user - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "newusername")) + require.NoError(t, user_model.NewUserRedirect(db.DefaultContext, user.ID, user.Name, "newusername")) unittest.AssertExistsAndLoadBean(t, &user_model.Redirect{ LowerName: user.LowerName, @@ -469,7 +470,7 @@ func TestNewUserRedirect3(t *testing.T) { } func TestGetUserByOpenID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) _, err := user_model.GetUserByOpenID(db.DefaultContext, "https://unknown") if assert.Error(t, err) { @@ -477,31 +478,31 @@ func TestGetUserByOpenID(t *testing.T) { } user, err := user_model.GetUserByOpenID(db.DefaultContext, "https://user1.domain1.tld") - if assert.NoError(t, err) { - assert.Equal(t, int64(1), user.ID) - } + require.NoError(t, err) + + assert.Equal(t, int64(1), user.ID) user, err = user_model.GetUserByOpenID(db.DefaultContext, "https://domain1.tld/user2/") - if assert.NoError(t, err) { - assert.Equal(t, int64(2), user.ID) - } + require.NoError(t, err) + + assert.Equal(t, int64(2), user.ID) } func TestFollowUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(followerID, followedID int64) { - assert.NoError(t, user_model.FollowUser(db.DefaultContext, followerID, followedID)) + require.NoError(t, user_model.FollowUser(db.DefaultContext, followerID, followedID)) unittest.AssertExistsAndLoadBean(t, &user_model.Follow{UserID: followerID, FollowID: followedID}) } testSuccess(4, 2) testSuccess(5, 2) - assert.NoError(t, user_model.FollowUser(db.DefaultContext, 2, 2)) + require.NoError(t, user_model.FollowUser(db.DefaultContext, 2, 2)) // Blocked user. - assert.ErrorIs(t, user_model.ErrBlockedByUser, user_model.FollowUser(db.DefaultContext, 1, 4)) - assert.ErrorIs(t, user_model.ErrBlockedByUser, user_model.FollowUser(db.DefaultContext, 4, 1)) + require.ErrorIs(t, user_model.ErrBlockedByUser, user_model.FollowUser(db.DefaultContext, 1, 4)) + require.ErrorIs(t, user_model.ErrBlockedByUser, user_model.FollowUser(db.DefaultContext, 4, 1)) unittest.AssertNotExistsBean(t, &user_model.Follow{UserID: 1, FollowID: 4}) unittest.AssertNotExistsBean(t, &user_model.Follow{UserID: 4, FollowID: 1}) @@ -509,10 +510,10 @@ func TestFollowUser(t *testing.T) { } func TestUnfollowUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(followerID, followedID int64) { - assert.NoError(t, user_model.UnfollowUser(db.DefaultContext, followerID, followedID)) + require.NoError(t, user_model.UnfollowUser(db.DefaultContext, followerID, followedID)) unittest.AssertNotExistsBean(t, &user_model.Follow{UserID: followerID, FollowID: followedID}) } testSuccess(4, 2) @@ -523,7 +524,7 @@ func TestUnfollowUser(t *testing.T) { } func TestIsUserVisibleToViewer(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) // admin, public user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) // normal, public @@ -576,10 +577,10 @@ func TestIsUserVisibleToViewer(t *testing.T) { } func TestGetAllAdmins(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) admins, err := user_model.GetAllAdmins(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, admins, 1) assert.Equal(t, int64(1), admins[0].ID) @@ -624,12 +625,12 @@ func Test_NormalizeUserFromEmail(t *testing.T) { } for _, testCase := range testCases { normalizedName, err := user_model.NormalizeUserName(testCase.Input) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, testCase.Expected, normalizedName) if testCase.IsNormalizedValid { - assert.NoError(t, user_model.IsUsableUsername(normalizedName)) + require.NoError(t, user_model.IsUsableUsername(normalizedName)) } else { - assert.Error(t, user_model.IsUsableUsername(normalizedName)) + require.Error(t, user_model.IsUsableUsername(normalizedName)) } } } @@ -666,7 +667,7 @@ func TestEmailTo(t *testing.T) { } func TestDisabledUserFeatures(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testValues := container.SetOf(setting.UserFeatureDeletion, setting.UserFeatureManageSSHKeys, @@ -680,11 +681,11 @@ func TestDisabledUserFeatures(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - assert.Len(t, setting.Admin.UserDisabledFeatures.Values(), 0) + assert.Empty(t, setting.Admin.UserDisabledFeatures.Values()) // no features should be disabled with a plain login type assert.LessOrEqual(t, user.LoginType, auth.Plain) - assert.Len(t, user_model.DisabledFeaturesWithLoginType(user).Values(), 0) + assert.Empty(t, user_model.DisabledFeaturesWithLoginType(user).Values()) for _, f := range testValues.Values() { assert.False(t, user_model.IsFeatureDisabledWithLoginType(user, f)) } diff --git a/models/webhook/webhook_test.go b/models/webhook/webhook_test.go index b4f6ffa189..848440b84a 100644 --- a/models/webhook/webhook_test.go +++ b/models/webhook/webhook_test.go @@ -16,6 +16,7 @@ import ( webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestHookContentType_Name(t *testing.T) { @@ -30,10 +31,10 @@ func TestIsValidHookContentType(t *testing.T) { } func TestWebhook_History(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) webhook := unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 1}) tasks, err := webhook.History(db.DefaultContext, 0) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, tasks, 3) { assert.Equal(t, int64(3), tasks[0].ID) assert.Equal(t, int64(2), tasks[1].ID) @@ -42,12 +43,12 @@ func TestWebhook_History(t *testing.T) { webhook = unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 2}) tasks, err = webhook.History(db.DefaultContext, 0) - assert.NoError(t, err) - assert.Len(t, tasks, 0) + require.NoError(t, err) + assert.Empty(t, tasks) } func TestWebhook_UpdateEvent(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) webhook := unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 1}) hookEvent := &webhook_module.HookEvent{ PushOnly: true, @@ -60,10 +61,10 @@ func TestWebhook_UpdateEvent(t *testing.T) { }, } webhook.HookEvent = hookEvent - assert.NoError(t, webhook.UpdateEvent()) + require.NoError(t, webhook.UpdateEvent()) assert.NotEmpty(t, webhook.Events) actualHookEvent := &webhook_module.HookEvent{} - assert.NoError(t, json.Unmarshal([]byte(webhook.Events), actualHookEvent)) + require.NoError(t, json.Unmarshal([]byte(webhook.Events), actualHookEvent)) assert.Equal(t, *hookEvent, *actualHookEvent) } @@ -96,39 +97,39 @@ func TestCreateWebhook(t *testing.T) { Events: `{"push_only":false,"send_everything":false,"choose_events":false,"events":{"create":false,"push":true,"pull_request":true}}`, } unittest.AssertNotExistsBean(t, hook) - assert.NoError(t, CreateWebhook(db.DefaultContext, hook)) + require.NoError(t, CreateWebhook(db.DefaultContext, hook)) unittest.AssertExistsAndLoadBean(t, hook) } func TestGetWebhookByRepoID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hook, err := GetWebhookByRepoID(db.DefaultContext, 1, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(1), hook.ID) _, err = GetWebhookByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID) - assert.Error(t, err) + require.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } func TestGetWebhookByOwnerID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hook, err := GetWebhookByOwnerID(db.DefaultContext, 3, 3) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(3), hook.ID) _, err = GetWebhookByOwnerID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID) - assert.Error(t, err) + require.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } func TestGetActiveWebhooksByRepoID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) activateWebhook(t, 1) hooks, err := db.Find[Webhook](db.DefaultContext, ListWebhookOptions{RepoID: 1, IsActive: optional.Some(true)}) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, hooks, 1) { assert.Equal(t, int64(1), hooks[0].ID) assert.True(t, hooks[0].IsActive) @@ -136,9 +137,9 @@ func TestGetActiveWebhooksByRepoID(t *testing.T) { } func TestGetWebhooksByRepoID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hooks, err := db.Find[Webhook](db.DefaultContext, ListWebhookOptions{RepoID: 1}) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, hooks, 2) { assert.Equal(t, int64(1), hooks[0].ID) assert.Equal(t, int64(2), hooks[1].ID) @@ -146,12 +147,12 @@ func TestGetWebhooksByRepoID(t *testing.T) { } func TestGetActiveWebhooksByOwnerID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) activateWebhook(t, 3) hooks, err := db.Find[Webhook](db.DefaultContext, ListWebhookOptions{OwnerID: 3, IsActive: optional.Some(true)}) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, hooks, 1) { assert.Equal(t, int64(3), hooks[0].ID) assert.True(t, hooks[0].IsActive) @@ -162,16 +163,16 @@ func activateWebhook(t *testing.T, hookID int64) { t.Helper() updated, err := db.GetEngine(db.DefaultContext).ID(hookID).Cols("is_active").Update(Webhook{IsActive: true}) assert.Equal(t, int64(1), updated) - assert.NoError(t, err) + require.NoError(t, err) } func TestGetWebhooksByOwnerID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) activateWebhook(t, 3) hooks, err := db.Find[Webhook](db.DefaultContext, ListWebhookOptions{OwnerID: 3}) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, hooks, 1) { assert.Equal(t, int64(3), hooks[0].ID) assert.True(t, hooks[0].IsActive) @@ -179,41 +180,41 @@ func TestGetWebhooksByOwnerID(t *testing.T) { } func TestUpdateWebhook(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hook := unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 2}) hook.IsActive = true hook.ContentType = ContentTypeForm unittest.AssertNotExistsBean(t, hook) - assert.NoError(t, UpdateWebhook(db.DefaultContext, hook)) + require.NoError(t, UpdateWebhook(db.DefaultContext, hook)) unittest.AssertExistsAndLoadBean(t, hook) } func TestDeleteWebhookByRepoID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 2, RepoID: 1}) - assert.NoError(t, DeleteWebhookByRepoID(db.DefaultContext, 1, 2)) + require.NoError(t, DeleteWebhookByRepoID(db.DefaultContext, 1, 2)) unittest.AssertNotExistsBean(t, &Webhook{ID: 2, RepoID: 1}) err := DeleteWebhookByRepoID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID) - assert.Error(t, err) + require.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } func TestDeleteWebhookByOwnerID(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) unittest.AssertExistsAndLoadBean(t, &Webhook{ID: 3, OwnerID: 3}) - assert.NoError(t, DeleteWebhookByOwnerID(db.DefaultContext, 3, 3)) + require.NoError(t, DeleteWebhookByOwnerID(db.DefaultContext, 3, 3)) unittest.AssertNotExistsBean(t, &Webhook{ID: 3, OwnerID: 3}) err := DeleteWebhookByOwnerID(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID) - assert.Error(t, err) + require.Error(t, err) assert.True(t, IsErrWebhookNotExist(err)) } func TestHookTasks(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hookTasks, err := HookTasks(db.DefaultContext, 1, 1) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, hookTasks, 3) { assert.Equal(t, int64(3), hookTasks[0].ID) assert.Equal(t, int64(2), hookTasks[1].ID) @@ -221,35 +222,35 @@ func TestHookTasks(t *testing.T) { } hookTasks, err = HookTasks(db.DefaultContext, unittest.NonexistentID, 1) - assert.NoError(t, err) - assert.Len(t, hookTasks, 0) + require.NoError(t, err) + assert.Empty(t, hookTasks) } func TestCreateHookTask(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ HookID: 3, PayloadVersion: 2, } unittest.AssertNotExistsBean(t, hookTask) _, err := CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, hookTask) } func TestUpdateHookTask(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hook := unittest.AssertExistsAndLoadBean(t, &HookTask{ID: 1}) hook.PayloadContent = "new payload content" hook.IsDelivered = true unittest.AssertNotExistsBean(t, hook) - assert.NoError(t, UpdateHookTask(db.DefaultContext, hook)) + require.NoError(t, UpdateHookTask(db.DefaultContext, hook)) unittest.AssertExistsAndLoadBean(t, hook) } func TestCleanupHookTaskTable_PerWebhook_DeletesDelivered(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ HookID: 3, IsDelivered: true, @@ -258,15 +259,15 @@ func TestCleanupHookTaskTable_PerWebhook_DeletesDelivered(t *testing.T) { } unittest.AssertNotExistsBean(t, hookTask) _, err := CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, hookTask) - assert.NoError(t, CleanupHookTaskTable(context.Background(), PerWebhook, 168*time.Hour, 0)) + require.NoError(t, CleanupHookTaskTable(context.Background(), PerWebhook, 168*time.Hour, 0)) unittest.AssertNotExistsBean(t, hookTask) } func TestCleanupHookTaskTable_PerWebhook_LeavesUndelivered(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ HookID: 4, IsDelivered: false, @@ -274,15 +275,15 @@ func TestCleanupHookTaskTable_PerWebhook_LeavesUndelivered(t *testing.T) { } unittest.AssertNotExistsBean(t, hookTask) _, err := CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, hookTask) - assert.NoError(t, CleanupHookTaskTable(context.Background(), PerWebhook, 168*time.Hour, 0)) + require.NoError(t, CleanupHookTaskTable(context.Background(), PerWebhook, 168*time.Hour, 0)) unittest.AssertExistsAndLoadBean(t, hookTask) } func TestCleanupHookTaskTable_PerWebhook_LeavesMostRecentTask(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ HookID: 4, IsDelivered: true, @@ -291,15 +292,15 @@ func TestCleanupHookTaskTable_PerWebhook_LeavesMostRecentTask(t *testing.T) { } unittest.AssertNotExistsBean(t, hookTask) _, err := CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, hookTask) - assert.NoError(t, CleanupHookTaskTable(context.Background(), PerWebhook, 168*time.Hour, 1)) + require.NoError(t, CleanupHookTaskTable(context.Background(), PerWebhook, 168*time.Hour, 1)) unittest.AssertExistsAndLoadBean(t, hookTask) } func TestCleanupHookTaskTable_OlderThan_DeletesDelivered(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ HookID: 3, IsDelivered: true, @@ -308,15 +309,15 @@ func TestCleanupHookTaskTable_OlderThan_DeletesDelivered(t *testing.T) { } unittest.AssertNotExistsBean(t, hookTask) _, err := CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, hookTask) - assert.NoError(t, CleanupHookTaskTable(context.Background(), OlderThan, 168*time.Hour, 0)) + require.NoError(t, CleanupHookTaskTable(context.Background(), OlderThan, 168*time.Hour, 0)) unittest.AssertNotExistsBean(t, hookTask) } func TestCleanupHookTaskTable_OlderThan_LeavesUndelivered(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ HookID: 4, IsDelivered: false, @@ -324,15 +325,15 @@ func TestCleanupHookTaskTable_OlderThan_LeavesUndelivered(t *testing.T) { } unittest.AssertNotExistsBean(t, hookTask) _, err := CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, hookTask) - assert.NoError(t, CleanupHookTaskTable(context.Background(), OlderThan, 168*time.Hour, 0)) + require.NoError(t, CleanupHookTaskTable(context.Background(), OlderThan, 168*time.Hour, 0)) unittest.AssertExistsAndLoadBean(t, hookTask) } func TestCleanupHookTaskTable_OlderThan_LeavesTaskEarlierThanAgeToDelete(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) hookTask := &HookTask{ HookID: 4, IsDelivered: true, @@ -341,9 +342,9 @@ func TestCleanupHookTaskTable_OlderThan_LeavesTaskEarlierThanAgeToDelete(t *test } unittest.AssertNotExistsBean(t, hookTask) _, err := CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, hookTask) - assert.NoError(t, CleanupHookTaskTable(context.Background(), OlderThan, 168*time.Hour, 0)) + require.NoError(t, CleanupHookTaskTable(context.Background(), OlderThan, 168*time.Hour, 0)) unittest.AssertExistsAndLoadBean(t, hookTask) } |