diff --git a/.golangci.yml b/.golangci.yml index 3f1667aece..640fbb938f 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -20,6 +20,7 @@ linters: - staticcheck - stylecheck - tenv + - testifylint - typecheck - unconvert - unused @@ -28,10 +29,6 @@ linters: run: timeout: 10m - skip-dirs: - - node_modules - - public - - web_src output: sort-results: true @@ -101,6 +98,9 @@ linters-settings: desc: do not use the ini package, use gitea's config system instead - pkg: github.com/minio/sha256-simd desc: use crypto/sha256 instead, see https://codeberg.org/forgejo/forgejo/pulls/1528 + testifylint: + disable: + - go-require issues: max-issues-per-linter: 0 diff --git a/build/codeformat/formatimports_test.go b/build/codeformat/formatimports_test.go index c66181d351..1abc9f8ab7 100644 --- a/build/codeformat/formatimports_test.go +++ b/build/codeformat/formatimports_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestFormatImportsSimple(t *testing.T) { @@ -29,7 +30,7 @@ import ( ) ` - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(formatted)) } @@ -92,7 +93,7 @@ import ( ) ` - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(formatted)) } @@ -120,5 +121,5 @@ import ( "image/gif" ) `)) - assert.ErrorIs(t, err, errInvalidCommentBetweenImports) + require.ErrorIs(t, err, errInvalidCommentBetweenImports) } diff --git a/cmd/admin_auth_ldap_test.go b/cmd/admin_auth_ldap_test.go index 7791f3a9cc..d5385d09e8 100644 --- a/cmd/admin_auth_ldap_test.go +++ b/cmd/admin_auth_ldap_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/services/auth/source/ldap" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/urfave/cli/v2" ) @@ -234,7 +235,7 @@ func TestAddLdapBindDn(t *testing.T) { if c.errMsg != "" { assert.EqualError(t, err, c.errMsg, "case %d: error should match", n) } else { - assert.NoError(t, err, "case %d: should have no errors", n) + require.NoError(t, err, "case %d: should have no errors", n) assert.Equal(t, c.source, createdAuthSource, "case %d: wrong authSource", n) } } @@ -465,7 +466,7 @@ func TestAddLdapSimpleAuth(t *testing.T) { if c.errMsg != "" { assert.EqualError(t, err, c.errMsg, "case %d: error should match", n) } else { - assert.NoError(t, err, "case %d: should have no errors", n) + require.NoError(t, err, "case %d: should have no errors", n) assert.Equal(t, c.authSource, createdAuthSource, "case %d: wrong authSource", n) } } @@ -928,7 +929,7 @@ func TestUpdateLdapBindDn(t *testing.T) { if c.errMsg != "" { assert.EqualError(t, err, c.errMsg, "case %d: error should match", n) } else { - assert.NoError(t, err, "case %d: should have no errors", n) + require.NoError(t, err, "case %d: should have no errors", n) assert.Equal(t, c.authSource, updatedAuthSource, "case %d: wrong authSource", n) } } @@ -1318,7 +1319,7 @@ func TestUpdateLdapSimpleAuth(t *testing.T) { if c.errMsg != "" { assert.EqualError(t, err, c.errMsg, "case %d: error should match", n) } else { - assert.NoError(t, err, "case %d: should have no errors", n) + require.NoError(t, err, "case %d: should have no errors", n) assert.Equal(t, c.authSource, updatedAuthSource, "case %d: wrong authSource", n) } } diff --git a/cmd/doctor_test.go b/cmd/doctor_test.go index 3e1ff299c5..e6daae18b9 100644 --- a/cmd/doctor_test.go +++ b/cmd/doctor_test.go @@ -10,7 +10,7 @@ import ( "code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/services/doctor" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/urfave/cli/v2" ) @@ -25,9 +25,9 @@ func TestDoctorRun(t *testing.T) { app := cli.NewApp() app.Commands = []*cli.Command{cmdDoctorCheck} err := app.Run([]string{"./gitea", "check", "--run", "test-check"}) - assert.NoError(t, err) + require.NoError(t, err) err = app.Run([]string{"./gitea", "check", "--run", "no-such"}) - assert.ErrorContains(t, err, `unknown checks: "no-such"`) + require.ErrorContains(t, err, `unknown checks: "no-such"`) err = app.Run([]string{"./gitea", "check", "--run", "test-check,no-such"}) - assert.ErrorContains(t, err, `unknown checks: "no-such"`) + require.ErrorContains(t, err, `unknown checks: "no-such"`) } diff --git a/cmd/dump_test.go b/cmd/dump_test.go index d33619bab8..459386318f 100644 --- a/cmd/dump_test.go +++ b/cmd/dump_test.go @@ -10,6 +10,7 @@ import ( "github.com/mholt/archiver/v3" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type mockArchiver struct { @@ -35,20 +36,20 @@ func TestAddRecursiveExclude(t *testing.T) { archiver := &mockArchiver{} err := addRecursiveExclude(archiver, "", dir, []string{}, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, archiver.addedFiles) }) t.Run("Single file", func(t *testing.T) { dir := t.TempDir() err := os.WriteFile(dir+"/example", nil, 0o666) - assert.NoError(t, err) + require.NoError(t, err) t.Run("No exclude", func(t *testing.T) { archiver := &mockArchiver{} err = addRecursiveExclude(archiver, "", dir, nil, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, archiver.addedFiles, 1) assert.Contains(t, archiver.addedFiles, "example") }) @@ -57,7 +58,7 @@ func TestAddRecursiveExclude(t *testing.T) { archiver := &mockArchiver{} err = addRecursiveExclude(archiver, "", dir, []string{dir + "/example"}, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, archiver.addedFiles) }) }) @@ -65,17 +66,17 @@ func TestAddRecursiveExclude(t *testing.T) { t.Run("File inside directory", func(t *testing.T) { dir := t.TempDir() err := os.MkdirAll(dir+"/deep/nested/folder", 0o750) - assert.NoError(t, err) + require.NoError(t, err) err = os.WriteFile(dir+"/deep/nested/folder/example", nil, 0o666) - assert.NoError(t, err) + require.NoError(t, err) err = os.WriteFile(dir+"/deep/nested/folder/another-file", nil, 0o666) - assert.NoError(t, err) + require.NoError(t, err) t.Run("No exclude", func(t *testing.T) { archiver := &mockArchiver{} err = addRecursiveExclude(archiver, "", dir, nil, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, archiver.addedFiles, 5) assert.Contains(t, archiver.addedFiles, "deep") assert.Contains(t, archiver.addedFiles, "deep/nested") @@ -88,7 +89,7 @@ func TestAddRecursiveExclude(t *testing.T) { archiver := &mockArchiver{} err = addRecursiveExclude(archiver, "", dir, []string{dir + "/deep"}, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, archiver.addedFiles) }) @@ -96,7 +97,7 @@ func TestAddRecursiveExclude(t *testing.T) { archiver := &mockArchiver{} err = addRecursiveExclude(archiver, "", dir, []string{dir + "/deep/nested/folder"}, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, archiver.addedFiles, 2) assert.Contains(t, archiver.addedFiles, "deep") assert.Contains(t, archiver.addedFiles, "deep/nested") @@ -106,7 +107,7 @@ func TestAddRecursiveExclude(t *testing.T) { archiver := &mockArchiver{} err = addRecursiveExclude(archiver, "", dir, []string{dir + "/deep/nested/folder/example"}, false) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, archiver.addedFiles, 4) assert.Contains(t, archiver.addedFiles, "deep") assert.Contains(t, archiver.addedFiles, "deep/nested") diff --git a/cmd/forgejo/actions_test.go b/cmd/forgejo/actions_test.go index 9a9edb7eb2..897af98315 100644 --- a/cmd/forgejo/actions_test.go +++ b/cmd/forgejo/actions_test.go @@ -79,9 +79,9 @@ func TestActions_getLabels(t *testing.T) { assert.Nil(t, result.labels) } if c.hasError { - assert.NotNil(t, result.err) + require.Error(t, result.err) } else { - assert.Nil(t, result.err) + assert.NoError(t, result.err) } }) } diff --git a/cmd/hook_test.go b/cmd/hook_test.go index 36149eb91f..890b236c7d 100644 --- a/cmd/hook_test.go +++ b/cmd/hook_test.go @@ -48,66 +48,66 @@ func TestPktLine(t *testing.T) { s := strings.NewReader("0000") r := bufio.NewReader(s) result, err := readPktLine(ctx, r, pktLineTypeFlush) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, pktLineTypeFlush, result.Type) s = strings.NewReader("0006a\n") r = bufio.NewReader(s) result, err = readPktLine(ctx, r, pktLineTypeData) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, pktLineTypeData, result.Type) assert.Equal(t, []byte("a\n"), result.Data) s = strings.NewReader("0004") r = bufio.NewReader(s) result, err = readPktLine(ctx, r, pktLineTypeData) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, result) data := strings.Repeat("x", 65516) r = bufio.NewReader(strings.NewReader("fff0" + data)) result, err = readPktLine(ctx, r, pktLineTypeData) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, pktLineTypeData, result.Type) assert.Equal(t, []byte(data), result.Data) r = bufio.NewReader(strings.NewReader("fff1a")) result, err = readPktLine(ctx, r, pktLineTypeData) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, result) }) t.Run("Write", func(t *testing.T) { w := bytes.NewBuffer([]byte{}) err := writeFlushPktLine(ctx, w) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("0000"), w.Bytes()) w.Reset() err = writeDataPktLine(ctx, w, []byte("a\nb")) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("0007a\nb"), w.Bytes()) w.Reset() data := bytes.Repeat([]byte{0x05}, 288) err = writeDataPktLine(ctx, w, data) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, append([]byte("0124"), data...), w.Bytes()) w.Reset() err = writeDataPktLine(ctx, w, nil) - assert.Error(t, err) + require.Error(t, err) assert.Empty(t, w.Bytes()) w.Reset() data = bytes.Repeat([]byte{0x64}, 65516) err = writeDataPktLine(ctx, w, data) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, append([]byte("fff0"), data...), w.Bytes()) w.Reset() err = writeDataPktLine(ctx, w, bytes.Repeat([]byte{0x64}, 65516+1)) - assert.Error(t, err) + require.Error(t, err) assert.Empty(t, w.Bytes()) }) } @@ -174,23 +174,23 @@ func TestRunHookUpdate(t *testing.T) { err := app.Run([]string{"./forgejo", "update", "refs/pull/1/head", "0a51ae26bc73c47e2f754560c40904cf14ed51a9", "0000000000000000000000000000000000000000"}) out := finish() - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, out, "The deletion of refs/pull/1/head is skipped as it's an internal reference.") }) t.Run("Update of internal reference", func(t *testing.T) { err := app.Run([]string{"./forgejo", "update", "refs/pull/1/head", "0a51ae26bc73c47e2f754560c40904cf14ed51a9", "0000000000000000000000000000000000000001"}) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("Removal of branch", func(t *testing.T) { err := app.Run([]string{"./forgejo", "update", "refs/head/main", "0a51ae26bc73c47e2f754560c40904cf14ed51a9", "0000000000000000000000000000000000000000"}) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("Not enough arguments", func(t *testing.T) { err := app.Run([]string{"./forgejo", "update"}) - assert.NoError(t, err) + require.NoError(t, err) }) } diff --git a/cmd/main_test.go b/cmd/main_test.go index a916c61f85..432f2b993c 100644 --- a/cmd/main_test.go +++ b/cmd/main_test.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/urfave/cli/v2" ) @@ -141,7 +142,7 @@ func TestCliCmd(t *testing.T) { } args := strings.Split(c.cmd, " ") // for test only, "split" is good enough r, err := runTestApp(app, args...) - assert.NoError(t, err, c.cmd) + require.NoError(t, err, c.cmd) assert.NotEmpty(t, c.exp, c.cmd) assert.Contains(t, r.Stdout, c.exp, c.cmd) } @@ -150,28 +151,28 @@ func TestCliCmd(t *testing.T) { func TestCliCmdError(t *testing.T) { app := newTestApp(func(ctx *cli.Context) error { return fmt.Errorf("normal error") }) r, err := runTestApp(app, "./gitea", "test-cmd") - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, 1, r.ExitCode) assert.Equal(t, "", r.Stdout) assert.Equal(t, "Command error: normal error\n", r.Stderr) app = newTestApp(func(ctx *cli.Context) error { return cli.Exit("exit error", 2) }) r, err = runTestApp(app, "./gitea", "test-cmd") - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, 2, r.ExitCode) assert.Equal(t, "", r.Stdout) assert.Equal(t, "exit error\n", r.Stderr) app = newTestApp(func(ctx *cli.Context) error { return nil }) r, err = runTestApp(app, "./gitea", "test-cmd", "--no-such") - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, 1, r.ExitCode) assert.Equal(t, "Incorrect Usage: flag provided but not defined: -no-such\n\n", r.Stdout) assert.Equal(t, "", r.Stderr) // the cli package's strange behavior, the error message is not in stderr .... app = newTestApp(func(ctx *cli.Context) error { return nil }) r, err = runTestApp(app, "./gitea", "test-cmd") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, -1, r.ExitCode) // the cli.OsExiter is not called assert.Equal(t, "", r.Stdout) assert.Equal(t, "", r.Stderr) diff --git a/cmd/migrate_storage_test.go b/cmd/migrate_storage_test.go index fa7067f97b..800a15e215 100644 --- a/cmd/migrate_storage_test.go +++ b/cmd/migrate_storage_test.go @@ -41,13 +41,13 @@ func createLocalStorage(t *testing.T) (storage.ObjectStorage, string) { } func TestMigratePackages(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) creator := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) content := "package main\n\nfunc main() {\nfmt.Println(\"hi\")\n}\n" buf, err := packages_module.CreateHashedBufferFromReaderWithSize(strings.NewReader(content), 1024) - assert.NoError(t, err) + require.NoError(t, err) defer buf.Close() v, f, err := packages_service.CreatePackageAndAddFile(db.DefaultContext, &packages_service.PackageCreationInfo{ @@ -68,7 +68,7 @@ func TestMigratePackages(t *testing.T) { Data: buf, IsLead: true, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, v) assert.NotNil(t, f) @@ -77,17 +77,17 @@ func TestMigratePackages(t *testing.T) { dstStorage, p := createLocalStorage(t) err = migratePackages(ctx, dstStorage) - assert.NoError(t, err) + require.NoError(t, err) entries, err := os.ReadDir(p) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, entries, 2) assert.EqualValues(t, "01", entries[0].Name()) assert.EqualValues(t, "tmp", entries[1].Name()) } func TestMigrateActionsArtifacts(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) srcStorage, _ := createLocalStorage(t) defer test.MockVariableValue(&storage.ActionsArtifacts, srcStorage)() @@ -118,17 +118,17 @@ func TestMigrateActionsArtifacts(t *testing.T) { dstStorage, _ := createLocalStorage(t) - assert.NoError(t, migrateActionsArtifacts(db.DefaultContext, dstStorage)) + require.NoError(t, migrateActionsArtifacts(db.DefaultContext, dstStorage)) object, err := dstStorage.Open(exists) - assert.NoError(t, err) + require.NoError(t, err) buf, err := io.ReadAll(object) require.NoError(t, err) assert.Equal(t, exists, string(buf)) _, err = dstStorage.Stat(expired) - assert.Error(t, err) + require.Error(t, err) _, err = dstStorage.Stat(notFound) - assert.Error(t, err) + require.Error(t, err) } 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) } diff --git a/modules/actions/workflows_test.go b/modules/actions/workflows_test.go index dca0c2924c..0042f59441 100644 --- a/modules/actions/workflows_test.go +++ b/modules/actions/workflows_test.go @@ -11,6 +11,7 @@ import ( webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDetectMatched(t *testing.T) { @@ -137,7 +138,7 @@ func TestDetectMatched(t *testing.T) { for _, tc := range testCases { t.Run(tc.desc, func(t *testing.T) { evts, err := GetEventsFromContent([]byte(tc.yamlOn)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, evts, 1) assert.Equal(t, tc.expected, detectMatched(nil, tc.commit, tc.triggedEvent, tc.payload, evts[0])) }) diff --git a/modules/activitypub/client_test.go b/modules/activitypub/client_test.go index 7f84634941..dede579662 100644 --- a/modules/activitypub/client_test.go +++ b/modules/activitypub/client_test.go @@ -20,6 +20,7 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" _ "github.com/mattn/go-sqlite3" ) @@ -27,8 +28,8 @@ import ( func TestCurrentTime(t *testing.T) { date := CurrentTime() _, err := time.Parse(http.TimeFormat, date) - assert.NoError(t, err) - assert.Equal(t, date[len(date)-3:], "GMT") + require.NoError(t, err) + assert.Equal(t, "GMT", date[len(date)-3:]) } /* ToDo: Set Up tests for http get requests @@ -64,22 +65,22 @@ Set up a user called "me" for all tests */ func TestNewClientReturnsClient(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) pubID := "myGpgId" c, err := NewClient(db.DefaultContext, user, pubID) log.Debug("Client: %v\nError: %v", c, err) - assert.NoError(t, err) + require.NoError(t, err) } /* TODO: bring this test to work or delete func TestActivityPubSignedGet(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1, Name: "me"}) pubID := "myGpgId" c, err := NewClient(db.DefaultContext, user, pubID) - assert.NoError(t, err) + require.NoError(t, err) expected := "TestActivityPubSignedGet" @@ -88,45 +89,45 @@ func TestActivityPubSignedGet(t *testing.T) { assert.Contains(t, r.Header.Get("Signature"), pubID) assert.Equal(t, r.Header.Get("Content-Type"), ActivityStreamsContentType) body, err := io.ReadAll(r.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(body)) fmt.Fprint(w, expected) })) defer srv.Close() r, err := c.Get(srv.URL) - assert.NoError(t, err) + require.NoError(t, err) defer r.Body.Close() body, err := io.ReadAll(r.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(body)) } */ func TestActivityPubSignedPost(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) pubID := "https://example.com/pubID" c, err := NewClient(db.DefaultContext, user, pubID) - assert.NoError(t, err) + require.NoError(t, err) expected := "BODY" srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Regexp(t, regexp.MustCompile("^"+setting.Federation.DigestAlgorithm), r.Header.Get("Digest")) assert.Contains(t, r.Header.Get("Signature"), pubID) - assert.Equal(t, r.Header.Get("Content-Type"), ActivityStreamsContentType) + assert.Equal(t, ActivityStreamsContentType, r.Header.Get("Content-Type")) body, err := io.ReadAll(r.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(body)) fmt.Fprint(w, expected) })) defer srv.Close() r, err := c.Post([]byte(expected), srv.URL) - assert.NoError(t, err) + require.NoError(t, err) defer r.Body.Close() body, err := io.ReadAll(r.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(body)) } diff --git a/modules/activitypub/user_settings_test.go b/modules/activitypub/user_settings_test.go index 2d77906521..7ead81c129 100644 --- a/modules/activitypub/user_settings_test.go +++ b/modules/activitypub/user_settings_test.go @@ -13,17 +13,18 @@ import ( _ "code.gitea.io/gitea/models" // https://discourse.gitea.io/t/testfixtures-could-not-clean-table-access-no-such-table-access/4137/4 "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUserSettings(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) pub, priv, err := GetKeyPair(db.DefaultContext, user1) - assert.NoError(t, err) + require.NoError(t, err) pub1, err := GetPublicKey(db.DefaultContext, user1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, pub, pub1) priv1, err := GetPrivateKey(db.DefaultContext, user1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, priv, priv1) } diff --git a/modules/assetfs/layered_test.go b/modules/assetfs/layered_test.go index b82111e745..58876d9be2 100644 --- a/modules/assetfs/layered_test.go +++ b/modules/assetfs/layered_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLayered(t *testing.T) { @@ -19,10 +20,10 @@ func TestLayered(t *testing.T) { dir2 := filepath.Join(dir, "l2") mkdir := func(elems ...string) { - assert.NoError(t, os.MkdirAll(filepath.Join(elems...), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(elems...), 0o755)) } write := func(content string, elems ...string) { - assert.NoError(t, os.WriteFile(filepath.Join(elems...), []byte(content), 0o644)) + require.NoError(t, os.WriteFile(filepath.Join(elems...), []byte(content), 0o644)) } // d1 & f1: only in "l1"; d2 & f2: only in "l2" @@ -49,18 +50,18 @@ func TestLayered(t *testing.T) { assets := Layered(Local("l1", dir1), Local("l2", dir2)) f, err := assets.Open("f1") - assert.NoError(t, err) + require.NoError(t, err) bs, err := io.ReadAll(f) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "f1", string(bs)) _ = f.Close() assertRead := func(expected string, expectedErr error, elems ...string) { bs, err := assets.ReadFile(elems...) if err != nil { - assert.ErrorAs(t, err, &expectedErr) + require.ErrorIs(t, err, expectedErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(bs)) } } @@ -75,27 +76,27 @@ func TestLayered(t *testing.T) { assertRead("", fs.ErrNotExist, "no-such") files, err := assets.ListFiles(".", true) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, []string{"f1", "f2", "fa"}, files) files, err = assets.ListFiles(".", false) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, []string{"d1", "d2", "da"}, files) files, err = assets.ListFiles(".") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, []string{"d1", "d2", "da", "f1", "f2", "fa"}, files) files, err = assets.ListAllFiles(".", true) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, []string{"d1/f", "d2/f", "da/f", "f1", "f2", "fa"}, files) files, err = assets.ListAllFiles(".", false) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, []string{"d1", "d2", "da", "da/sub1", "da/sub2"}, files) files, err = assets.ListAllFiles(".") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, []string{ "d1", "d1/f", "d2", "d2/f", diff --git a/modules/auth/pam/pam_test.go b/modules/auth/pam/pam_test.go index c277d59c41..e9b844e955 100644 --- a/modules/auth/pam/pam_test.go +++ b/modules/auth/pam/pam_test.go @@ -9,11 +9,12 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPamAuth(t *testing.T) { result, err := Auth("gitea", "user1", "false-pwd") - assert.Error(t, err) + require.Error(t, err) assert.EqualError(t, err, "Authentication failure") assert.Len(t, result, 0) } diff --git a/modules/auth/password/hash/dummy_test.go b/modules/auth/password/hash/dummy_test.go index f3b36df625..35d1249999 100644 --- a/modules/auth/password/hash/dummy_test.go +++ b/modules/auth/password/hash/dummy_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDummyHasher(t *testing.T) { @@ -18,7 +19,7 @@ func TestDummyHasher(t *testing.T) { password, salt := "password", "ZogKvWdyEx" hash, err := dummy.Hash(password, salt) - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, hash, salt+":"+password) assert.True(t, dummy.VerifyPassword(password, hash, salt)) diff --git a/modules/auth/password/hash/hash_test.go b/modules/auth/password/hash/hash_test.go index 7aa051733f..03d08a8a36 100644 --- a/modules/auth/password/hash/hash_test.go +++ b/modules/auth/password/hash/hash_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type testSaltHasher string @@ -29,7 +30,7 @@ func Test_registerHasher(t *testing.T) { }) }) - assert.Error(t, Register("Test_registerHasher", func(config string) testSaltHasher { + require.Error(t, Register("Test_registerHasher", func(config string) testSaltHasher { return testSaltHasher(config) })) @@ -76,10 +77,10 @@ func TestHashing(t *testing.T) { t.Run(algorithmName, func(t *testing.T) { output, err := Parse(algorithmName).Hash(password, salt) if shouldPass { - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, output, "output for %s was empty", algorithmName) } else { - assert.Error(t, err) + require.Error(t, err) } assert.Equal(t, Parse(algorithmName).VerifyPassword(password, output, salt), shouldPass) diff --git a/modules/auth/password/password_test.go b/modules/auth/password/password_test.go index 6c35dc86bd..1fe3fb5ce1 100644 --- a/modules/auth/password/password_test.go +++ b/modules/auth/password/password_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestComplexity_IsComplexEnough(t *testing.T) { @@ -52,7 +53,7 @@ func TestComplexity_Generate(t *testing.T) { testComplextity(modes) for i := 0; i < maxCount; i++ { pwd, err := Generate(pwdLen) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pwd, pwdLen) assert.True(t, IsComplexEnough(pwd), "Failed complexities with modes %+v for generated: %s", modes, pwd) } diff --git a/modules/auth/password/pwn/pwn_test.go b/modules/auth/password/pwn/pwn_test.go index b3e7734c3f..e5108150ae 100644 --- a/modules/auth/password/pwn/pwn_test.go +++ b/modules/auth/password/pwn/pwn_test.go @@ -10,6 +10,7 @@ import ( "github.com/h2non/gock" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var client = New(WithHTTP(&http.Client{ @@ -20,31 +21,31 @@ func TestPassword(t *testing.T) { defer gock.Off() count, err := client.CheckPassword("", false) - assert.ErrorIs(t, err, ErrEmptyPassword, "blank input should return ErrEmptyPassword") + require.ErrorIs(t, err, ErrEmptyPassword, "blank input should return ErrEmptyPassword") assert.Equal(t, -1, count) gock.New("https://api.pwnedpasswords.com").Get("/range/5c1d8").Times(1).Reply(200).BodyString("EAF2F254732680E8AC339B84F3266ECCBB5:1\r\nFC446EB88938834178CB9322C1EE273C2A7:2") count, err = client.CheckPassword("pwned", false) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 1, count) gock.New("https://api.pwnedpasswords.com").Get("/range/ba189").Times(1).Reply(200).BodyString("FD4CB34F0378BCB15D23F6FFD28F0775C9E:3\r\nFDF342FCD8C3611DAE4D76E8A992A3E4169:4") count, err = client.CheckPassword("notpwned", false) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0, count) gock.New("https://api.pwnedpasswords.com").Get("/range/a1733").Times(1).Reply(200).BodyString("C4CE0F1F0062B27B9E2F41AF0C08218017C:1\r\nFC446EB88938834178CB9322C1EE273C2A7:2\r\nFE81480327C992FE62065A827429DD1318B:0") count, err = client.CheckPassword("paddedpwned", true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 1, count) gock.New("https://api.pwnedpasswords.com").Get("/range/5617b").Times(1).Reply(200).BodyString("FD4CB34F0378BCB15D23F6FFD28F0775C9E:3\r\nFDF342FCD8C3611DAE4D76E8A992A3E4169:4\r\nFE81480327C992FE62065A827429DD1318B:0") count, err = client.CheckPassword("paddednotpwned", true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0, count) gock.New("https://api.pwnedpasswords.com").Get("/range/79082").Times(1).Reply(200).BodyString("FDF342FCD8C3611DAE4D76E8A992A3E4169:4\r\nFE81480327C992FE62065A827429DD1318B:0\r\nAFEF386F56EB0B4BE314E07696E5E6E6536:0") count, err = client.CheckPassword("paddednotpwnedzero", true) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0, count) } diff --git a/modules/avatar/avatar_test.go b/modules/avatar/avatar_test.go index a721c77868..824a38e15b 100644 --- a/modules/avatar/avatar_test.go +++ b/modules/avatar/avatar_test.go @@ -13,19 +13,20 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_RandomImageSize(t *testing.T) { _, err := RandomImageSize(0, []byte("gitea@local")) - assert.Error(t, err) + require.Error(t, err) _, err = RandomImageSize(64, []byte("gitea@local")) - assert.NoError(t, err) + require.NoError(t, err) } func Test_RandomImage(t *testing.T) { _, err := RandomImage([]byte("gitea@local")) - assert.NoError(t, err) + require.NoError(t, err) } func Test_ProcessAvatarPNG(t *testing.T) { @@ -33,10 +34,10 @@ func Test_ProcessAvatarPNG(t *testing.T) { setting.Avatar.MaxHeight = 4096 data, err := os.ReadFile("testdata/avatar.png") - assert.NoError(t, err) + require.NoError(t, err) _, err = processAvatarImage(data, 262144) - assert.NoError(t, err) + require.NoError(t, err) } func Test_ProcessAvatarJPEG(t *testing.T) { @@ -44,10 +45,10 @@ func Test_ProcessAvatarJPEG(t *testing.T) { setting.Avatar.MaxHeight = 4096 data, err := os.ReadFile("testdata/avatar.jpeg") - assert.NoError(t, err) + require.NoError(t, err) _, err = processAvatarImage(data, 262144) - assert.NoError(t, err) + require.NoError(t, err) } func Test_ProcessAvatarInvalidData(t *testing.T) { @@ -63,7 +64,7 @@ func Test_ProcessAvatarInvalidImageSize(t *testing.T) { setting.Avatar.MaxHeight = 5 data, err := os.ReadFile("testdata/avatar.png") - assert.NoError(t, err) + require.NoError(t, err) _, err = processAvatarImage(data, 12800) assert.EqualError(t, err, "image width is too large: 10 > 5") @@ -83,54 +84,54 @@ func Test_ProcessAvatarImage(t *testing.T) { img := image.NewRGBA(image.Rect(0, 0, width, height)) bs := bytes.Buffer{} err := png.Encode(&bs, img) - assert.NoError(t, err) + require.NoError(t, err) return bs.Bytes() } // if origin image canvas is too large, crop and resize it origin := newImgData(500, 600) result, err := processAvatarImage(origin, 0) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, origin, result) decoded, err := png.Decode(bytes.NewReader(result)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, scaledSize, decoded.Bounds().Max.X) assert.EqualValues(t, scaledSize, decoded.Bounds().Max.Y) // if origin image is smaller than the default size, use the origin image origin = newImgData(1) result, err = processAvatarImage(origin, 0) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, origin, result) // use the origin image if the origin is smaller origin = newImgData(scaledSize + 100) result, err = processAvatarImage(origin, 0) - assert.NoError(t, err) + require.NoError(t, err) assert.Less(t, len(result), len(origin)) // still use the origin image if the origin doesn't exceed the max-origin-size origin = newImgData(scaledSize + 100) result, err = processAvatarImage(origin, 262144) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, origin, result) // allow to use known image format (eg: webp) if it is small enough origin, err = os.ReadFile("testdata/animated.webp") - assert.NoError(t, err) + require.NoError(t, err) result, err = processAvatarImage(origin, 262144) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, origin, result) // do not support unknown image formats, eg: SVG may contain embedded JS origin = []byte("") _, err = processAvatarImage(origin, 262144) - assert.ErrorContains(t, err, "image: unknown format") + require.ErrorContains(t, err, "image: unknown format") // make sure the canvas size limit works setting.Avatar.MaxWidth = 5 setting.Avatar.MaxHeight = 5 origin = newImgData(10) _, err = processAvatarImage(origin, 262144) - assert.ErrorContains(t, err, "image width is too large: 10 > 5") + require.ErrorContains(t, err, "image width is too large: 10 > 5") } diff --git a/modules/avatar/identicon/identicon_test.go b/modules/avatar/identicon/identicon_test.go index 23bcc73e2e..88702b0f38 100644 --- a/modules/avatar/identicon/identicon_test.go +++ b/modules/avatar/identicon/identicon_test.go @@ -12,7 +12,7 @@ import ( "strconv" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGenerate(t *testing.T) { @@ -24,17 +24,16 @@ func TestGenerate(t *testing.T) { backColor := color.White imgMaker, err := New(64, backColor, DarkColors...) - assert.NoError(t, err) + require.NoError(t, err) for i := 0; i < 100; i++ { s := strconv.Itoa(i) img := imgMaker.Make([]byte(s)) f, err := os.Create(dir + "/" + s + ".png") - if !assert.NoError(t, err) { - continue - } + require.NoError(t, err) + defer f.Close() err = png.Encode(f, img) - assert.NoError(t, err) + require.NoError(t, err) } } diff --git a/modules/base/tool_test.go b/modules/base/tool_test.go index cc37fdd324..eb38e2969e 100644 --- a/modules/base/tool_test.go +++ b/modules/base/tool_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestEncodeSha256(t *testing.T) { @@ -31,15 +32,15 @@ func TestBasicAuthDecode(t *testing.T) { assert.Equal(t, "illegal base64 data at input byte 0", err.Error()) user, pass, err := BasicAuthDecode("Zm9vOmJhcg==") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "foo", user) assert.Equal(t, "bar", pass) _, _, err = BasicAuthDecode("aW52YWxpZA==") - assert.Error(t, err) + require.Error(t, err) _, _, err = BasicAuthDecode("invalid") - assert.Error(t, err) + require.Error(t, err) } func TestVerifyTimeLimitCode(t *testing.T) { @@ -143,7 +144,7 @@ func TestTruncateString(t *testing.T) { func TestStringsToInt64s(t *testing.T) { testSuccess := func(input []string, expected []int64) { result, err := StringsToInt64s(input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, result) } testSuccess(nil, nil) @@ -152,8 +153,8 @@ func TestStringsToInt64s(t *testing.T) { testSuccess([]string{"1", "4", "16", "64", "256"}, []int64{1, 4, 16, 64, 256}) ints, err := StringsToInt64s([]string{"-1", "a"}) - assert.Len(t, ints, 0) - assert.Error(t, err) + assert.Empty(t, ints) + require.Error(t, err) } func TestInt64sToStrings(t *testing.T) { diff --git a/modules/cache/cache_test.go b/modules/cache/cache_test.go index 3f65040924..8bc986f1a7 100644 --- a/modules/cache/cache_test.go +++ b/modules/cache/cache_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func createTestCache() { @@ -22,7 +23,7 @@ func createTestCache() { } func TestNewContext(t *testing.T) { - assert.NoError(t, Init()) + require.NoError(t, Init()) setting.CacheService.Cache = setting.Cache{Adapter: "redis", Conn: "some random string"} con, err := newCache(setting.Cache{ @@ -30,7 +31,7 @@ func TestNewContext(t *testing.T) { Conn: "false conf", Interval: 100, }) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, con) } @@ -46,32 +47,32 @@ func TestGetString(t *testing.T) { data, err := GetString("key", func() (string, error) { return "", fmt.Errorf("some error") }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "", data) data, err = GetString("key", func() (string, error) { return "", nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "", data) data, err = GetString("key", func() (string, error) { return "some data", nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "", data) Remove("key") data, err = GetString("key", func() (string, error) { return "some data", nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "some data", data) data, err = GetString("key", func() (string, error) { return "", fmt.Errorf("some error") }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "some data", data) Remove("key") } @@ -82,32 +83,32 @@ func TestGetInt(t *testing.T) { data, err := GetInt("key", func() (int, error) { return 0, fmt.Errorf("some error") }) - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, 0, data) data, err = GetInt("key", func() (int, error) { return 0, nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0, data) data, err = GetInt("key", func() (int, error) { return 100, nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 0, data) Remove("key") data, err = GetInt("key", func() (int, error) { return 100, nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 100, data) data, err = GetInt("key", func() (int, error) { return 0, fmt.Errorf("some error") }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 100, data) Remove("key") } @@ -118,32 +119,32 @@ func TestGetInt64(t *testing.T) { data, err := GetInt64("key", func() (int64, error) { return 0, fmt.Errorf("some error") }) - assert.Error(t, err) + require.Error(t, err) assert.EqualValues(t, 0, data) data, err = GetInt64("key", func() (int64, error) { return 0, nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, data) data, err = GetInt64("key", func() (int64, error) { return 100, nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, data) Remove("key") data, err = GetInt64("key", func() (int64, error) { return 100, nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 100, data) data, err = GetInt64("key", func() (int64, error) { return 0, fmt.Errorf("some error") }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 100, data) Remove("key") } diff --git a/modules/cache/context_test.go b/modules/cache/context_test.go index 5315547865..1ee3d2dd52 100644 --- a/modules/cache/context_test.go +++ b/modules/cache/context_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestWithCacheContext(t *testing.T) { @@ -34,7 +35,7 @@ func TestWithCacheContext(t *testing.T) { vInt, err := GetWithContextCache(ctx, field, "my_config1", func() (int, error) { return 1, nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, vInt) v = GetContextData(ctx, field, "my_config1") diff --git a/modules/charset/charset_test.go b/modules/charset/charset_test.go index 829844a976..42c8415376 100644 --- a/modules/charset/charset_test.go +++ b/modules/charset/charset_test.go @@ -12,6 +12,7 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func resetDefaultCharsetsOrder() { @@ -48,12 +49,12 @@ func TestToUTF8(t *testing.T) { // depend on particular conversions but in expected behaviors. res, err = ToUTF8([]byte{0x41, 0x42, 0x43}, ConvertOpts{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "ABC", res) // "áéíóú" res, err = ToUTF8([]byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, ConvertOpts{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) // "áéíóú" @@ -61,14 +62,14 @@ func TestToUTF8(t *testing.T) { 0xef, 0xbb, 0xbf, 0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba, }, ConvertOpts{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte{0xc3, 0xa1, 0xc3, 0xa9, 0xc3, 0xad, 0xc3, 0xb3, 0xc3, 0xba}, []byte(res)) res, err = ToUTF8([]byte{ 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, 0xF3, 0x6D, 0x6F, 0x20, 0xF1, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, }, ConvertOpts{}) - assert.NoError(t, err) + require.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) @@ -76,7 +77,7 @@ func TestToUTF8(t *testing.T) { 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, 0xF3, 0x6D, 0x6F, 0x20, 0x07, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, }, ConvertOpts{}) - assert.NoError(t, err) + require.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) @@ -84,7 +85,7 @@ func TestToUTF8(t *testing.T) { 0x48, 0x6F, 0x6C, 0x61, 0x2C, 0x20, 0x61, 0x73, 0xED, 0x20, 0x63, 0xF3, 0x6D, 0x6F, 0x20, 0x81, 0xA4, 0x6F, 0x73, 0x41, 0x41, 0x41, 0x2e, }, ConvertOpts{}) - assert.NoError(t, err) + require.NoError(t, err) stringMustStartWith(t, "Hola,", res) stringMustEndWith(t, "AAA.", res) @@ -94,7 +95,7 @@ func TestToUTF8(t *testing.T) { 0x93, 0xFA, 0x91, 0xAE, 0x94, 0xE9, 0x82, 0xBC, 0x82, 0xB5, 0x82, 0xBF, 0x82, 0xE3, 0x81, 0x42, }, ConvertOpts{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte{ 0xE6, 0x97, 0xA5, 0xE5, 0xB1, 0x9E, 0xE7, 0xA7, 0x98, 0xE3, 0x81, 0x9E, 0xE3, 0x81, 0x97, 0xE3, 0x81, 0xA1, 0xE3, 0x82, 0x85, 0xE3, 0x80, 0x82, @@ -102,7 +103,7 @@ func TestToUTF8(t *testing.T) { []byte(res)) res, err = ToUTF8([]byte{0x00, 0x00, 0x00, 0x00}, ConvertOpts{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte{0x00, 0x00, 0x00, 0x00}, []byte(res)) } @@ -199,7 +200,7 @@ func TestDetectEncoding(t *testing.T) { resetDefaultCharsetsOrder() testSuccess := func(b []byte, expected string) { encoding, err := DetectEncoding(b) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, encoding) } // utf-8 @@ -217,7 +218,7 @@ func TestDetectEncoding(t *testing.T) { // iso-8859-1: dcor b = []byte{0x44, 0xe9, 0x63, 0x6f, 0x72, 0x0a} encoding, err := DetectEncoding(b) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, encoding, "ISO-8859-1") old := setting.Repository.AnsiCharset @@ -230,7 +231,7 @@ func TestDetectEncoding(t *testing.T) { // invalid bytes b = []byte{0xfa} _, err = DetectEncoding(b) - assert.Error(t, err) + require.Error(t, err) } func stringMustStartWith(t *testing.T, expected, value string) { diff --git a/modules/charset/escape_test.go b/modules/charset/escape_test.go index 83dda16c53..2ca76f88d5 100644 --- a/modules/charset/escape_test.go +++ b/modules/charset/escape_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/translation" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var testContext = escapeContext("test") @@ -163,7 +164,7 @@ func TestEscapeControlReader(t *testing.T) { t.Run(tt.name, func(t *testing.T) { output := &strings.Builder{} status, err := EscapeControlReader(strings.NewReader(tt.text), output, &translation.MockLocale{}, testContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.status, *status) assert.Equal(t, tt.result, output.String()) }) diff --git a/modules/csv/csv_test.go b/modules/csv/csv_test.go index f6e782a5a4..6ed6986629 100644 --- a/modules/csv/csv_test.go +++ b/modules/csv/csv_test.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/translation" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCreateReader(t *testing.T) { @@ -27,7 +28,7 @@ func decodeSlashes(t *testing.T, s string) string { s = strings.ReplaceAll(s, "\n", "\\n") s = strings.ReplaceAll(s, "\"", "\\\"") decoded, err := strconv.Unquote(`"` + s + `"`) - assert.NoError(t, err, "unable to decode string") + require.NoError(t, err, "unable to decode string") return decoded } @@ -99,10 +100,10 @@ j, ,\x20 for n, c := range cases { rd, err := CreateReaderAndDetermineDelimiter(nil, strings.NewReader(decodeSlashes(t, c.csv))) - assert.NoError(t, err, "case %d: should not throw error: %v\n", n, err) + require.NoError(t, err, "case %d: should not throw error: %v\n", n, err) assert.EqualValues(t, c.expectedDelimiter, rd.Comma, "case %d: delimiter should be '%c', got '%c'", n, c.expectedDelimiter, rd.Comma) rows, err := rd.ReadAll() - assert.NoError(t, err, "case %d: should not throw error: %v\n", n, err) + require.NoError(t, err, "case %d: should not throw error: %v\n", n, err) assert.EqualValues(t, c.expectedRows, rows, "case %d: rows should be equal", n) } } @@ -115,8 +116,8 @@ func (r *mockReader) Read(buf []byte) (int, error) { func TestDetermineDelimiterShortBufferError(t *testing.T) { rd, err := CreateReaderAndDetermineDelimiter(nil, &mockReader{}) - assert.Error(t, err, "CreateReaderAndDetermineDelimiter() should throw an error") - assert.ErrorIs(t, err, io.ErrShortBuffer) + require.Error(t, err, "CreateReaderAndDetermineDelimiter() should throw an error") + require.ErrorIs(t, err, io.ErrShortBuffer) assert.Nil(t, rd, "CSV reader should be mnil") } @@ -127,11 +128,11 @@ func TestDetermineDelimiterReadAllError(t *testing.T) { f g h|i jkl`)) - assert.NoError(t, err, "CreateReaderAndDetermineDelimiter() shouldn't throw error") + require.NoError(t, err, "CreateReaderAndDetermineDelimiter() shouldn't throw error") assert.NotNil(t, rd, "CSV reader should not be mnil") rows, err := rd.ReadAll() - assert.Error(t, err, "RaadAll() should throw error") - assert.ErrorIs(t, err, csv.ErrFieldCount) + require.Error(t, err, "RaadAll() should throw error") + require.ErrorIs(t, err, csv.ErrFieldCount) assert.Empty(t, rows, "rows should be empty") } @@ -580,9 +581,9 @@ func TestFormatError(t *testing.T) { for n, c := range cases { message, err := FormatError(c.err, &translation.MockLocale{}) if c.expectsError { - assert.Error(t, err, "case %d: expected an error to be returned", n) + require.Error(t, err, "case %d: expected an error to be returned", n) } else { - assert.NoError(t, err, "case %d: no error was expected, got error: %v", n, err) + require.NoError(t, err, "case %d: no error was expected, got error: %v", n, err) assert.EqualValues(t, c.expectedMessage, message, "case %d: messages should be equal, expected '%s' got '%s'", n, c.expectedMessage, message) } } diff --git a/modules/generate/generate_test.go b/modules/generate/generate_test.go index 7d023b23ad..eb7178af33 100644 --- a/modules/generate/generate_test.go +++ b/modules/generate/generate_test.go @@ -9,26 +9,27 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDecodeJwtSecret(t *testing.T) { _, err := DecodeJwtSecret("abcd") - assert.ErrorContains(t, err, "invalid base64 decoded length") + require.ErrorContains(t, err, "invalid base64 decoded length") _, err = DecodeJwtSecret(strings.Repeat("a", 64)) - assert.ErrorContains(t, err, "invalid base64 decoded length") + require.ErrorContains(t, err, "invalid base64 decoded length") str32 := strings.Repeat("x", 32) encoded32 := base64.RawURLEncoding.EncodeToString([]byte(str32)) decoded32, err := DecodeJwtSecret(encoded32) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, str32, string(decoded32)) } func TestNewJwtSecret(t *testing.T) { secret, encoded, err := NewJwtSecret() - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, secret, 32) decoded, err := DecodeJwtSecret(encoded) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, secret, decoded) } diff --git a/modules/git/blame_sha256_test.go b/modules/git/blame_sha256_test.go index fcb00e2a38..eeeeb9fdb5 100644 --- a/modules/git/blame_sha256_test.go +++ b/modules/git/blame_sha256_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestReadingBlameOutputSha256(t *testing.T) { @@ -18,11 +19,11 @@ func TestReadingBlameOutputSha256(t *testing.T) { t.Run("Without .git-blame-ignore-revs", func(t *testing.T) { repo, err := OpenRepository(ctx, "./tests/repos/repo5_pulls_sha256") - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() commit, err := repo.GetCommit("0b69b7bb649b5d46e14cabb6468685e5dd721290acc7ffe604d37cde57927345") - assert.NoError(t, err) + require.NoError(t, err) parts := []*BlamePart{ { @@ -42,7 +43,7 @@ func TestReadingBlameOutputSha256(t *testing.T) { for _, bypass := range []bool{false, true} { blameReader, err := CreateBlameReader(ctx, Sha256ObjectFormat, "./tests/repos/repo5_pulls_sha256", commit, "README.md", bypass) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, blameReader) defer blameReader.Close() @@ -50,20 +51,20 @@ func TestReadingBlameOutputSha256(t *testing.T) { for _, part := range parts { actualPart, err := blameReader.NextPart() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, part, actualPart) } // make sure all parts have been read actualPart, err := blameReader.NextPart() assert.Nil(t, actualPart) - assert.NoError(t, err) + require.NoError(t, err) } }) t.Run("With .git-blame-ignore-revs", func(t *testing.T) { repo, err := OpenRepository(ctx, "./tests/repos/repo6_blame_sha256") - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() full := []*BlamePart{ @@ -121,12 +122,12 @@ func TestReadingBlameOutputSha256(t *testing.T) { } objectFormat, err := repo.GetObjectFormat() - assert.NoError(t, err) + require.NoError(t, err) for _, c := range cases { commit, err := repo.GetCommit(c.CommitID) - assert.NoError(t, err) + require.NoError(t, err) blameReader, err := CreateBlameReader(ctx, objectFormat, "./tests/repos/repo6_blame_sha256", commit, "blame.txt", c.Bypass) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, blameReader) defer blameReader.Close() @@ -134,14 +135,14 @@ func TestReadingBlameOutputSha256(t *testing.T) { for _, part := range c.Parts { actualPart, err := blameReader.NextPart() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, part, actualPart) } // make sure all parts have been read actualPart, err := blameReader.NextPart() assert.Nil(t, actualPart) - assert.NoError(t, err) + require.NoError(t, err) } }) } diff --git a/modules/git/blame_test.go b/modules/git/blame_test.go index 4220c85600..65320c78c0 100644 --- a/modules/git/blame_test.go +++ b/modules/git/blame_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestReadingBlameOutput(t *testing.T) { @@ -16,11 +17,11 @@ func TestReadingBlameOutput(t *testing.T) { t.Run("Without .git-blame-ignore-revs", func(t *testing.T) { repo, err := OpenRepository(ctx, "./tests/repos/repo5_pulls") - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() commit, err := repo.GetCommit("f32b0a9dfd09a60f616f29158f772cedd89942d2") - assert.NoError(t, err) + require.NoError(t, err) parts := []*BlamePart{ { @@ -40,7 +41,7 @@ func TestReadingBlameOutput(t *testing.T) { for _, bypass := range []bool{false, true} { blameReader, err := CreateBlameReader(ctx, Sha1ObjectFormat, "./tests/repos/repo5_pulls", commit, "README.md", bypass) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, blameReader) defer blameReader.Close() @@ -48,20 +49,20 @@ func TestReadingBlameOutput(t *testing.T) { for _, part := range parts { actualPart, err := blameReader.NextPart() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, part, actualPart) } // make sure all parts have been read actualPart, err := blameReader.NextPart() assert.Nil(t, actualPart) - assert.NoError(t, err) + require.NoError(t, err) } }) t.Run("With .git-blame-ignore-revs", func(t *testing.T) { repo, err := OpenRepository(ctx, "./tests/repos/repo6_blame") - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() full := []*BlamePart{ @@ -119,13 +120,13 @@ func TestReadingBlameOutput(t *testing.T) { } objectFormat, err := repo.GetObjectFormat() - assert.NoError(t, err) + require.NoError(t, err) for _, c := range cases { commit, err := repo.GetCommit(c.CommitID) - assert.NoError(t, err) + require.NoError(t, err) blameReader, err := CreateBlameReader(ctx, objectFormat, "./tests/repos/repo6_blame", commit, "blame.txt", c.Bypass) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, blameReader) defer blameReader.Close() @@ -133,14 +134,14 @@ func TestReadingBlameOutput(t *testing.T) { for _, part := range c.Parts { actualPart, err := blameReader.NextPart() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, part, actualPart) } // make sure all parts have been read actualPart, err := blameReader.NextPart() assert.Nil(t, actualPart) - assert.NoError(t, err) + require.NoError(t, err) } }) } diff --git a/modules/git/blob_test.go b/modules/git/blob_test.go index 63374384f6..810964b33d 100644 --- a/modules/git/blob_test.go +++ b/modules/git/blob_test.go @@ -17,22 +17,21 @@ func TestBlob_Data(t *testing.T) { output := "file2\n" bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") repo, err := openRepositoryWithDefaultContext(bareRepo1Path) - if !assert.NoError(t, err) { - t.Fatal() - } + require.NoError(t, err) + defer repo.Close() testBlob, err := repo.GetBlob("6c493ff740f9380390d5c9ddef4af18697ac9375") - assert.NoError(t, err) + require.NoError(t, err) r, err := testBlob.DataAsync() - assert.NoError(t, err) + require.NoError(t, err) require.NotNil(t, r) data, err := io.ReadAll(r) - assert.NoError(t, r.Close()) + require.NoError(t, r.Close()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, output, string(data)) } diff --git a/modules/git/command_test.go b/modules/git/command_test.go index 9a6228c9ad..1d8d3bc12b 100644 --- a/modules/git/command_test.go +++ b/modules/git/command_test.go @@ -8,12 +8,13 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRunWithContextStd(t *testing.T) { cmd := NewCommand(context.Background(), "--version") stdout, stderr, err := cmd.RunStdString(&RunOpts{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, stderr) assert.Contains(t, stdout, "git version") @@ -28,16 +29,16 @@ func TestRunWithContextStd(t *testing.T) { cmd = NewCommand(context.Background()) cmd.AddDynamicArguments("-test") - assert.ErrorIs(t, cmd.Run(&RunOpts{}), ErrBrokenCommand) + require.ErrorIs(t, cmd.Run(&RunOpts{}), ErrBrokenCommand) cmd = NewCommand(context.Background()) cmd.AddDynamicArguments("--test") - assert.ErrorIs(t, cmd.Run(&RunOpts{}), ErrBrokenCommand) + require.ErrorIs(t, cmd.Run(&RunOpts{}), ErrBrokenCommand) subCmd := "version" cmd = NewCommand(context.Background()).AddDynamicArguments(subCmd) // for test purpose only, the sub-command should never be dynamic for production stdout, stderr, err = cmd.RunStdString(&RunOpts{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, stderr) assert.Contains(t, stdout, "git version") } diff --git a/modules/git/commit_info_test.go b/modules/git/commit_info_test.go index 1e331fac00..dbe9ab547d 100644 --- a/modules/git/commit_info_test.go +++ b/modules/git/commit_info_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -57,7 +58,7 @@ func testGetCommitsInfo(t *testing.T, repo1 *Repository) { for _, testCase := range testCases { commit, err := repo1.GetCommit(testCase.CommitID) if err != nil { - assert.NoError(t, err, "Unable to get commit: %s from testcase due to error: %v", testCase.CommitID, err) + require.NoError(t, err, "Unable to get commit: %s from testcase due to error: %v", testCase.CommitID, err) // no point trying to do anything else for this test. continue } @@ -67,7 +68,7 @@ func testGetCommitsInfo(t *testing.T, repo1 *Repository) { tree, err := commit.Tree.SubTree(testCase.Path) if err != nil { - assert.NoError(t, err, "Unable to get subtree: %s of commit: %s from testcase due to error: %v", testCase.Path, testCase.CommitID, err) + require.NoError(t, err, "Unable to get subtree: %s of commit: %s from testcase due to error: %v", testCase.Path, testCase.CommitID, err) // no point trying to do anything else for this test. continue } @@ -77,14 +78,14 @@ func testGetCommitsInfo(t *testing.T, repo1 *Repository) { entries, err := tree.ListEntries() if err != nil { - assert.NoError(t, err, "Unable to get entries of subtree: %s in commit: %s from testcase due to error: %v", testCase.Path, testCase.CommitID, err) + require.NoError(t, err, "Unable to get entries of subtree: %s in commit: %s from testcase due to error: %v", testCase.Path, testCase.CommitID, err) // no point trying to do anything else for this test. continue } // FIXME: Context.TODO() - if graceful has started we should use its Shutdown context otherwise use install signals in TestMain. commitsInfo, treeCommit, err := entries.GetCommitsInfo(context.TODO(), commit, testCase.Path) - assert.NoError(t, err, "Unable to get commit information for entries of subtree: %s in commit: %s from testcase due to error: %v", testCase.Path, testCase.CommitID, err) + require.NoError(t, err, "Unable to get commit information for entries of subtree: %s in commit: %s from testcase due to error: %v", testCase.Path, testCase.CommitID, err) if err != nil { t.FailNow() } @@ -105,18 +106,18 @@ func testGetCommitsInfo(t *testing.T, repo1 *Repository) { func TestEntries_GetCommitsInfo(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() testGetCommitsInfo(t, bareRepo1) clonedPath, err := cloneRepo(t, bareRepo1Path) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) } clonedRepo1, err := openRepositoryWithDefaultContext(clonedPath) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) } defer clonedRepo1.Close() diff --git a/modules/git/commit_sha256_test.go b/modules/git/commit_sha256_test.go index a4309519cf..f0e392a35e 100644 --- a/modules/git/commit_sha256_test.go +++ b/modules/git/commit_sha256_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCommitsCountSha256(t *testing.T) { @@ -24,7 +25,7 @@ func TestCommitsCountSha256(t *testing.T) { Revision: []string{"f004f41359117d319dedd0eaab8c5259ee2263da839dcba33637997458627fdc"}, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(3), commitsCount) } @@ -40,7 +41,7 @@ func TestCommitsCountWithoutBaseSha256(t *testing.T) { Revision: []string{"branch1"}, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), commitsCount) } @@ -50,7 +51,7 @@ func TestGetFullCommitIDSha256(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256") id, err := GetFullCommitID(DefaultContext, bareRepo1Path, "f004f4") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "f004f41359117d319dedd0eaab8c5259ee2263da839dcba33637997458627fdc", id) } @@ -98,12 +99,12 @@ signed commit` 0x5d, 0x3e, 0x69, 0xd3, 0x1b, 0x78, 0x60, 0x87, 0x77, 0x5e, 0x28, 0xc6, 0xb6, 0x39, 0x9d, 0xf0, } gitRepo, err := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo1_bare_sha256")) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, gitRepo) defer gitRepo.Close() commitFromReader, err := CommitFromReader(gitRepo, sha, strings.NewReader(commitString)) - assert.NoError(t, err) + require.NoError(t, err) if !assert.NotNil(t, commitFromReader) { return } @@ -134,7 +135,7 @@ signed commit`, commitFromReader.Signature.Payload) assert.EqualValues(t, "Adam Majer ", commitFromReader.Author.String()) commitFromReader2, err := CommitFromReader(gitRepo, sha, strings.NewReader(commitString+"\n\n")) - assert.NoError(t, err) + require.NoError(t, err) commitFromReader.CommitMessage += "\n\n" commitFromReader.Signature.Payload += "\n\n" assert.EqualValues(t, commitFromReader, commitFromReader2) @@ -146,30 +147,30 @@ func TestHasPreviousCommitSha256(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare_sha256") repo, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() commit, err := repo.GetCommit("f004f41359117d319dedd0eaab8c5259ee2263da839dcba33637997458627fdc") - assert.NoError(t, err) + require.NoError(t, err) objectFormat, err := repo.GetObjectFormat() - assert.NoError(t, err) + require.NoError(t, err) parentSHA := MustIDFromString("b0ec7af4547047f12d5093e37ef8f1b3b5415ed8ee17894d43a34d7d34212e9c") notParentSHA := MustIDFromString("42e334efd04cd36eea6da0599913333c26116e1a537ca76e5b6e4af4dda00236") - assert.Equal(t, objectFormat, parentSHA.Type()) - assert.Equal(t, objectFormat.Name(), "sha256") + assert.Equal(t, parentSHA.Type(), objectFormat) + assert.Equal(t, "sha256", objectFormat.Name()) haz, err := commit.HasPreviousCommit(parentSHA) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, haz) hazNot, err := commit.HasPreviousCommit(notParentSHA) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, hazNot) selfNot, err := commit.HasPreviousCommit(commit.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, selfNot) } @@ -179,7 +180,7 @@ func TestGetCommitFileStatusMergesSha256(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo6_merge_sha256") commitFileStatus, err := GetCommitFileStatus(DefaultContext, bareRepo1Path, "d2e5609f630dd8db500f5298d05d16def282412e3e66ed68cc7d0833b29129a1") - assert.NoError(t, err) + require.NoError(t, err) expected := CommitFileStatus{ []string{ @@ -204,7 +205,7 @@ func TestGetCommitFileStatusMergesSha256(t *testing.T) { } commitFileStatus, err = GetCommitFileStatus(DefaultContext, bareRepo1Path, "da1ded40dc8e5b7c564171f4bf2fc8370487decfb1cb6a99ef28f3ed73d09172") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected.Added, commitFileStatus.Added) assert.Equal(t, expected.Removed, commitFileStatus.Removed) diff --git a/modules/git/commit_test.go b/modules/git/commit_test.go index 01c628fb80..af85bfe093 100644 --- a/modules/git/commit_test.go +++ b/modules/git/commit_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCommitsCount(t *testing.T) { @@ -20,7 +21,7 @@ func TestCommitsCount(t *testing.T) { Revision: []string{"8006ff9adbf0cb94da7dad9e537e53817f9fa5c0"}, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(3), commitsCount) } @@ -34,7 +35,7 @@ func TestCommitsCountWithoutBase(t *testing.T) { Revision: []string{"branch1"}, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), commitsCount) } @@ -42,7 +43,7 @@ func TestGetFullCommitID(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") id, err := GetFullCommitID(DefaultContext, bareRepo1Path, "8006ff9a") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", id) } @@ -83,15 +84,13 @@ empty commit` sha := &Sha1Hash{0xfe, 0xaf, 0x4b, 0xa6, 0xbc, 0x63, 0x5f, 0xec, 0x44, 0x2f, 0x46, 0xdd, 0xd4, 0x51, 0x24, 0x16, 0xec, 0x43, 0xc2, 0xc2} gitRepo, err := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo1_bare")) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, gitRepo) defer gitRepo.Close() commitFromReader, err := CommitFromReader(gitRepo, sha, strings.NewReader(commitString)) - assert.NoError(t, err) - if !assert.NotNil(t, commitFromReader) { - return - } + require.NoError(t, err) + require.NotNil(t, commitFromReader) assert.EqualValues(t, sha, commitFromReader.ID) assert.EqualValues(t, `-----BEGIN PGP SIGNATURE----- @@ -119,7 +118,7 @@ empty commit`, commitFromReader.Signature.Payload) assert.EqualValues(t, "silverwind ", commitFromReader.Author.String()) commitFromReader2, err := CommitFromReader(gitRepo, sha, strings.NewReader(commitString+"\n\n")) - assert.NoError(t, err) + require.NoError(t, err) commitFromReader.CommitMessage += "\n\n" commitFromReader.Signature.Payload += "\n\n" assert.EqualValues(t, commitFromReader, commitFromReader2) @@ -133,7 +132,7 @@ author KN4CK3R 1711702962 +0100 committer KN4CK3R 1711702962 +0100 encoding ISO-8859-1 gpgsig -----BEGIN PGP SIGNATURE----- - +` + " " + ` iQGzBAABCgAdFiEE9HRrbqvYxPT8PXbefPSEkrowAa8FAmYGg7IACgkQfPSEkrow Aa9olwv+P0HhtCM6CRvlUmPaqswRsDPNR4i66xyXGiSxdI9V5oJL7HLiQIM7KrFR gizKa2COiGtugv8fE+TKqXKaJx6uJUJEjaBd8E9Af9PrAzjWj+A84lU6/PgPS8hq @@ -151,15 +150,13 @@ ISO-8859-1` sha := &Sha1Hash{0xfe, 0xaf, 0x4b, 0xa6, 0xbc, 0x63, 0x5f, 0xec, 0x44, 0x2f, 0x46, 0xdd, 0xd4, 0x51, 0x24, 0x16, 0xec, 0x43, 0xc2, 0xc2} gitRepo, err := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo1_bare")) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, gitRepo) defer gitRepo.Close() commitFromReader, err := CommitFromReader(gitRepo, sha, strings.NewReader(commitString)) - assert.NoError(t, err) - if !assert.NotNil(t, commitFromReader) { - return - } + require.NoError(t, err) + require.NotNil(t, commitFromReader) assert.EqualValues(t, sha, commitFromReader.ID) assert.EqualValues(t, `-----BEGIN PGP SIGNATURE----- @@ -186,7 +183,7 @@ ISO-8859-1`, commitFromReader.Signature.Payload) assert.EqualValues(t, "KN4CK3R ", commitFromReader.Author.String()) commitFromReader2, err := CommitFromReader(gitRepo, sha, strings.NewReader(commitString+"\n\n")) - assert.NoError(t, err) + require.NoError(t, err) commitFromReader.CommitMessage += "\n\n" commitFromReader.Signature.Payload += "\n\n" assert.EqualValues(t, commitFromReader, commitFromReader2) @@ -196,25 +193,25 @@ func TestHasPreviousCommit(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") repo, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() commit, err := repo.GetCommit("8006ff9adbf0cb94da7dad9e537e53817f9fa5c0") - assert.NoError(t, err) + require.NoError(t, err) parentSHA := MustIDFromString("8d92fc957a4d7cfd98bc375f0b7bb189a0d6c9f2") notParentSHA := MustIDFromString("2839944139e0de9737a044f78b0e4b40d989a9e3") haz, err := commit.HasPreviousCommit(parentSHA) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, haz) hazNot, err := commit.HasPreviousCommit(notParentSHA) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, hazNot) selfNot, err := commit.HasPreviousCommit(commit.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, selfNot) } @@ -327,7 +324,7 @@ func TestGetCommitFileStatusMerges(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo6_merge") commitFileStatus, err := GetCommitFileStatus(DefaultContext, bareRepo1Path, "022f4ce6214973e018f02bf363bf8a2e3691f699") - assert.NoError(t, err) + require.NoError(t, err) expected := CommitFileStatus{ []string{ @@ -341,9 +338,9 @@ func TestGetCommitFileStatusMerges(t *testing.T) { }, } - assert.Equal(t, commitFileStatus.Added, expected.Added) - assert.Equal(t, commitFileStatus.Removed, expected.Removed) - assert.Equal(t, commitFileStatus.Modified, expected.Modified) + assert.Equal(t, expected.Added, commitFileStatus.Added) + assert.Equal(t, expected.Removed, commitFileStatus.Removed) + assert.Equal(t, expected.Modified, commitFileStatus.Modified) } func TestParseCommitRenames(t *testing.T) { diff --git a/modules/git/diff_test.go b/modules/git/diff_test.go index 8fa47a943c..0855a7de1c 100644 --- a/modules/git/diff_test.go +++ b/modules/git/diff_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const exampleDiff = `diff --git a/README.md b/README.md @@ -81,7 +82,7 @@ index d46c152..a7d2d55 100644 func TestCutDiffAroundLineIssue17875(t *testing.T) { result, err := CutDiffAroundLine(strings.NewReader(issue17875Diff), 23, false, 3) - assert.NoError(t, err) + require.NoError(t, err) expected := `diff --git a/Geschäftsordnung.md b/Geschäftsordnung.md --- a/Geschäftsordnung.md +++ b/Geschäftsordnung.md @@ -94,7 +95,7 @@ func TestCutDiffAroundLineIssue17875(t *testing.T) { func TestCutDiffAroundLine(t *testing.T) { result, err := CutDiffAroundLine(strings.NewReader(exampleDiff), 4, false, 3) - assert.NoError(t, err) + require.NoError(t, err) resultByLine := strings.Split(result, "\n") assert.Len(t, resultByLine, 7) // Check if headers got transferred @@ -108,25 +109,25 @@ func TestCutDiffAroundLine(t *testing.T) { // Must be same result as before since old line 3 == new line 5 newResult, err := CutDiffAroundLine(strings.NewReader(exampleDiff), 3, true, 3) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, result, newResult, "Must be same result as before since old line 3 == new line 5") newResult, err = CutDiffAroundLine(strings.NewReader(exampleDiff), 6, false, 300) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, exampleDiff, newResult) emptyResult, err := CutDiffAroundLine(strings.NewReader(exampleDiff), 6, false, 0) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, emptyResult) // Line is out of scope emptyResult, err = CutDiffAroundLine(strings.NewReader(exampleDiff), 434, false, 0) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, emptyResult) // Handle minus diffs properly minusDiff, err := CutDiffAroundLine(strings.NewReader(breakingDiff), 2, false, 4) - assert.NoError(t, err) + require.NoError(t, err) expected := `diff --git a/aaa.sql b/aaa.sql --- a/aaa.sql @@ -139,7 +140,7 @@ func TestCutDiffAroundLine(t *testing.T) { // Handle minus diffs properly minusDiff, err = CutDiffAroundLine(strings.NewReader(breakingDiff), 3, false, 4) - assert.NoError(t, err) + require.NoError(t, err) expected = `diff --git a/aaa.sql b/aaa.sql --- a/aaa.sql diff --git a/modules/git/git_test.go b/modules/git/git_test.go index 37ab669ea4..cdbd2a1768 100644 --- a/modules/git/git_test.go +++ b/modules/git/git_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testRun(m *testing.M) error { @@ -52,33 +53,33 @@ func gitConfigContains(sub string) bool { func TestGitConfig(t *testing.T) { assert.False(t, gitConfigContains("key-a")) - assert.NoError(t, configSetNonExist("test.key-a", "val-a")) + require.NoError(t, configSetNonExist("test.key-a", "val-a")) assert.True(t, gitConfigContains("key-a = val-a")) - assert.NoError(t, configSetNonExist("test.key-a", "val-a-changed")) + require.NoError(t, configSetNonExist("test.key-a", "val-a-changed")) assert.False(t, gitConfigContains("key-a = val-a-changed")) - assert.NoError(t, configSet("test.key-a", "val-a-changed")) + require.NoError(t, configSet("test.key-a", "val-a-changed")) assert.True(t, gitConfigContains("key-a = val-a-changed")) - assert.NoError(t, configAddNonExist("test.key-b", "val-b")) + require.NoError(t, configAddNonExist("test.key-b", "val-b")) assert.True(t, gitConfigContains("key-b = val-b")) - assert.NoError(t, configAddNonExist("test.key-b", "val-2b")) + require.NoError(t, configAddNonExist("test.key-b", "val-2b")) assert.True(t, gitConfigContains("key-b = val-b")) assert.True(t, gitConfigContains("key-b = val-2b")) - assert.NoError(t, configUnsetAll("test.key-b", "val-b")) + require.NoError(t, configUnsetAll("test.key-b", "val-b")) assert.False(t, gitConfigContains("key-b = val-b")) assert.True(t, gitConfigContains("key-b = val-2b")) - assert.NoError(t, configUnsetAll("test.key-b", "val-2b")) + require.NoError(t, configUnsetAll("test.key-b", "val-2b")) assert.False(t, gitConfigContains("key-b = val-2b")) - assert.NoError(t, configSet("test.key-x", "*")) + require.NoError(t, configSet("test.key-x", "*")) assert.True(t, gitConfigContains("key-x = *")) - assert.NoError(t, configSetNonExist("test.key-x", "*")) - assert.NoError(t, configUnsetAll("test.key-x", "*")) + require.NoError(t, configSetNonExist("test.key-x", "*")) + require.NoError(t, configUnsetAll("test.key-x", "*")) assert.False(t, gitConfigContains("key-x = *")) } @@ -89,7 +90,7 @@ func TestSyncConfig(t *testing.T) { }() setting.GitConfig.Options["sync-test.cfg-key-a"] = "CfgValA" - assert.NoError(t, syncGitConfig()) + require.NoError(t, syncGitConfig()) assert.True(t, gitConfigContains("[sync-test]")) assert.True(t, gitConfigContains("cfg-key-a = CfgValA")) } diff --git a/modules/git/grep_test.go b/modules/git/grep_test.go index d2ed7300c1..486b5bc56b 100644 --- a/modules/git/grep_test.go +++ b/modules/git/grep_test.go @@ -12,15 +12,16 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGrepSearch(t *testing.T) { repo, err := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "language_stats_repo")) - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() res, err := GrepSearch(context.Background(), repo, "void", GrepOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []*GrepResult{ { Filename: "java-hello/main.java", @@ -35,7 +36,7 @@ func TestGrepSearch(t *testing.T) { }, res) res, err = GrepSearch(context.Background(), repo, "void", GrepOptions{MaxResultLimit: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []*GrepResult{ { Filename: "java-hello/main.java", @@ -45,7 +46,7 @@ func TestGrepSearch(t *testing.T) { }, res) res, err = GrepSearch(context.Background(), repo, "world", GrepOptions{MatchesPerFile: 1}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []*GrepResult{ { Filename: "i-am-a-python.p", @@ -70,34 +71,34 @@ func TestGrepSearch(t *testing.T) { }, res) res, err = GrepSearch(context.Background(), repo, "no-such-content", GrepOptions{}) - assert.NoError(t, err) - assert.Len(t, res, 0) + require.NoError(t, err) + assert.Empty(t, res) res, err = GrepSearch(context.Background(), &Repository{Path: "no-such-git-repo"}, "no-such-content", GrepOptions{}) - assert.Error(t, err) - assert.Len(t, res, 0) + require.Error(t, err) + assert.Empty(t, res) } func TestGrepLongFiles(t *testing.T) { tmpDir := t.TempDir() err := InitRepository(DefaultContext, tmpDir, false, Sha1ObjectFormat.Name()) - assert.NoError(t, err) + require.NoError(t, err) gitRepo, err := openRepositoryWithDefaultContext(tmpDir) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() - assert.NoError(t, os.WriteFile(path.Join(tmpDir, "README.md"), bytes.Repeat([]byte{'a'}, 65*1024), 0o666)) + require.NoError(t, os.WriteFile(path.Join(tmpDir, "README.md"), bytes.Repeat([]byte{'a'}, 65*1024), 0o666)) err = AddChanges(tmpDir, true) - assert.NoError(t, err) + require.NoError(t, err) err = CommitChanges(tmpDir, CommitChangesOptions{Message: "Long file"}) - assert.NoError(t, err) + require.NoError(t, err) res, err := GrepSearch(context.Background(), gitRepo, "a", GrepOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, res, 1) assert.Len(t, res[0].LineCodes[0], 65*1024) } @@ -106,28 +107,28 @@ func TestGrepRefs(t *testing.T) { tmpDir := t.TempDir() err := InitRepository(DefaultContext, tmpDir, false, Sha1ObjectFormat.Name()) - assert.NoError(t, err) + require.NoError(t, err) gitRepo, err := openRepositoryWithDefaultContext(tmpDir) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() - assert.NoError(t, os.WriteFile(path.Join(tmpDir, "README.md"), []byte{'A'}, 0o666)) - assert.NoError(t, AddChanges(tmpDir, true)) + require.NoError(t, os.WriteFile(path.Join(tmpDir, "README.md"), []byte{'A'}, 0o666)) + require.NoError(t, AddChanges(tmpDir, true)) err = CommitChanges(tmpDir, CommitChangesOptions{Message: "add A"}) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, gitRepo.CreateTag("v1", "HEAD")) + require.NoError(t, gitRepo.CreateTag("v1", "HEAD")) - assert.NoError(t, os.WriteFile(path.Join(tmpDir, "README.md"), []byte{'A', 'B', 'C', 'D'}, 0o666)) - assert.NoError(t, AddChanges(tmpDir, true)) + require.NoError(t, os.WriteFile(path.Join(tmpDir, "README.md"), []byte{'A', 'B', 'C', 'D'}, 0o666)) + require.NoError(t, AddChanges(tmpDir, true)) err = CommitChanges(tmpDir, CommitChangesOptions{Message: "add BCD"}) - assert.NoError(t, err) + require.NoError(t, err) res, err := GrepSearch(context.Background(), gitRepo, "a", GrepOptions{RefName: "v1"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, res, 1) - assert.Equal(t, res[0].LineCodes[0], "A") + assert.Equal(t, "A", res[0].LineCodes[0]) } diff --git a/modules/git/notes_test.go b/modules/git/notes_test.go index 267671d8fa..bbb16ccb14 100644 --- a/modules/git/notes_test.go +++ b/modules/git/notes_test.go @@ -9,17 +9,18 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetNotes(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() note := Note{} err = GetNote(context.Background(), bareRepo1, "95bb4d39648ee7e325106df01a621c530863a653", ¬e) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("Note contents\n"), note.Message) assert.Equal(t, "Vladimir Panteleev", note.Commit.Author.Name) } @@ -27,26 +28,26 @@ func TestGetNotes(t *testing.T) { func TestGetNestedNotes(t *testing.T) { repoPath := filepath.Join(testReposDir, "repo3_notes") repo, err := openRepositoryWithDefaultContext(repoPath) - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() note := Note{} err = GetNote(context.Background(), repo, "3e668dbfac39cbc80a9ff9c61eb565d944453ba4", ¬e) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("Note 2"), note.Message) err = GetNote(context.Background(), repo, "ba0a96fa63532d6c5087ecef070b0250ed72fa47", ¬e) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("Note 1"), note.Message) } func TestGetNonExistentNotes(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() note := Note{} err = GetNote(context.Background(), bareRepo1, "non_existent_sha", ¬e) - assert.Error(t, err) + require.Error(t, err) assert.IsType(t, ErrNotExist{}, err) } diff --git a/modules/git/parse_gogit_test.go b/modules/git/parse_gogit_test.go index 3e171d7e56..7622478550 100644 --- a/modules/git/parse_gogit_test.go +++ b/modules/git/parse_gogit_test.go @@ -13,6 +13,7 @@ import ( "github.com/go-git/go-git/v5/plumbing/filemode" "github.com/go-git/go-git/v5/plumbing/object" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParseTreeEntries(t *testing.T) { @@ -68,7 +69,7 @@ func TestParseTreeEntries(t *testing.T) { for _, testCase := range testCases { entries, err := ParseTreeEntries([]byte(testCase.Input)) - assert.NoError(t, err) + require.NoError(t, err) if len(entries) > 1 { fmt.Println(testCase.Expected[0].ID) fmt.Println(entries[0].ID) diff --git a/modules/git/parse_nogogit_test.go b/modules/git/parse_nogogit_test.go index 23fddb014c..cc1d02cc0c 100644 --- a/modules/git/parse_nogogit_test.go +++ b/modules/git/parse_nogogit_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParseTreeEntriesLong(t *testing.T) { @@ -55,7 +56,7 @@ func TestParseTreeEntriesLong(t *testing.T) { } for _, testCase := range testCases { entries, err := ParseTreeEntries([]byte(testCase.Input)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, entries, len(testCase.Expected)) for i, entry := range entries { assert.EqualValues(t, testCase.Expected[i], entry) @@ -88,7 +89,7 @@ func TestParseTreeEntriesShort(t *testing.T) { } for _, testCase := range testCases { entries, err := ParseTreeEntries([]byte(testCase.Input)) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, entries, len(testCase.Expected)) for i, entry := range entries { assert.EqualValues(t, testCase.Expected[i], entry) @@ -99,6 +100,6 @@ func TestParseTreeEntriesShort(t *testing.T) { func TestParseTreeEntriesInvalid(t *testing.T) { // there was a panic: "runtime error: slice bounds out of range" when the input was invalid: #20315 entries, err := ParseTreeEntries([]byte("100644 blob ea0d83c9081af9500ac9f804101b3fd0a5c293af")) - assert.Error(t, err) - assert.Len(t, entries, 0) + require.Error(t, err) + assert.Empty(t, entries) } diff --git a/modules/git/repo_attribute_test.go b/modules/git/repo_attribute_test.go index e9f7454413..fa34164816 100644 --- a/modules/git/repo_attribute_test.go +++ b/modules/git/repo_attribute_test.go @@ -30,14 +30,14 @@ func TestNewCheckAttrStdoutReader(t *testing.T) { // first read attr, err := read() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]GitAttribute{ "linguist-vendored": GitAttribute("unspecified"), }, attr) // second read attr, err = read() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]GitAttribute{ "linguist-vendored": GitAttribute("specified"), }, attr) @@ -59,21 +59,21 @@ func TestNewCheckAttrStdoutReader(t *testing.T) { // first read attr, err := read() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]GitAttribute{ "linguist-vendored": GitAttribute("set"), }, attr) // second read attr, err = read() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]GitAttribute{ "linguist-generated": GitAttribute("unspecified"), }, attr) // third read attr, err = read() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, map[string]GitAttribute{ "linguist-language": GitAttribute("unspecified"), }, attr) @@ -95,32 +95,32 @@ func TestGitAttributeBareNonBare(t *testing.T) { "341fca5b5ea3de596dc483e54c2db28633cd2f97", } { bareStats, err := gitRepo.GitAttributes(commitID, "i-am-a-python.p", LinguistAttributes...) - assert.NoError(t, err) + require.NoError(t, err) defer test.MockVariableValue(&SupportCheckAttrOnBare, false)() cloneStats, err := gitRepo.GitAttributes(commitID, "i-am-a-python.p", LinguistAttributes...) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, cloneStats, bareStats) refStats := cloneStats t.Run("GitAttributeChecker/"+commitID+"/SupportBare", func(t *testing.T) { bareChecker, err := gitRepo.GitAttributeChecker(commitID, LinguistAttributes...) - assert.NoError(t, err) + require.NoError(t, err) defer bareChecker.Close() bareStats, err := bareChecker.CheckPath("i-am-a-python.p") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, refStats, bareStats) }) t.Run("GitAttributeChecker/"+commitID+"/NoBareSupport", func(t *testing.T) { defer test.MockVariableValue(&SupportCheckAttrOnBare, false)() cloneChecker, err := gitRepo.GitAttributeChecker(commitID, LinguistAttributes...) - assert.NoError(t, err) + require.NoError(t, err) defer cloneChecker.Close() cloneStats, err := cloneChecker.CheckPath("i-am-a-python.p") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, refStats, cloneStats) }) @@ -134,7 +134,7 @@ func TestGitAttributes(t *testing.T) { defer gitRepo.Close() attr, err := gitRepo.GitAttributes("8fee858da5796dfb37704761701bb8e800ad9ef3", "i-am-a-python.p", LinguistAttributes...) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, map[string]GitAttribute{ "gitlab-language": "unspecified", "linguist-detectable": "unspecified", @@ -145,7 +145,7 @@ func TestGitAttributes(t *testing.T) { }, attr) attr, err = gitRepo.GitAttributes("341fca5b5ea3de596dc483e54c2db28633cd2f97", "i-am-a-python.p", LinguistAttributes...) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, map[string]GitAttribute{ "gitlab-language": "unspecified", "linguist-detectable": "unspecified", @@ -164,19 +164,19 @@ func TestGitAttributeFirst(t *testing.T) { t.Run("first is specified", func(t *testing.T) { language, err := gitRepo.GitAttributeFirst("8fee858da5796dfb37704761701bb8e800ad9ef3", "i-am-a-python.p", "linguist-language", "gitlab-language") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Python", language.String()) }) t.Run("second is specified", func(t *testing.T) { language, err := gitRepo.GitAttributeFirst("8fee858da5796dfb37704761701bb8e800ad9ef3", "i-am-a-python.p", "gitlab-language", "linguist-language") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Python", language.String()) }) t.Run("none is specified", func(t *testing.T) { language, err := gitRepo.GitAttributeFirst("8fee858da5796dfb37704761701bb8e800ad9ef3", "i-am-a-python.p", "linguist-detectable", "gitlab-language", "non-existing") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "", language.String()) }) } @@ -208,13 +208,13 @@ func TestGitAttributeCheckerError(t *testing.T) { gitRepo := prepareRepo(t) defer gitRepo.Close() - assert.NoError(t, os.RemoveAll(gitRepo.Path)) + require.NoError(t, os.RemoveAll(gitRepo.Path)) ac, err := gitRepo.GitAttributeChecker("", "linguist-language") require.NoError(t, err) _, err = ac.CheckPath("i-am-a-python.p") - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, err.Error(), `git check-attr (stderr: ""):`) }) @@ -226,7 +226,7 @@ func TestGitAttributeCheckerError(t *testing.T) { require.NoError(t, err) // calling CheckPath before would allow git to cache part of it and successfully return later - assert.NoError(t, os.RemoveAll(gitRepo.Path)) + require.NoError(t, os.RemoveAll(gitRepo.Path)) _, err = ac.CheckPath("i-am-a-python.p") if err == nil { @@ -254,7 +254,7 @@ func TestGitAttributeCheckerError(t *testing.T) { require.NoError(t, err) _, err = ac.CheckPath("i-am-a-python.p") - assert.ErrorIs(t, err, context.Canceled) + require.ErrorIs(t, err, context.Canceled) }) t.Run("Cancelled/DuringRun", func(t *testing.T) { @@ -268,7 +268,7 @@ func TestGitAttributeCheckerError(t *testing.T) { require.NoError(t, err) attr, err := ac.CheckPath("i-am-a-python.p") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Python", attr["linguist-language"].String()) errCh := make(chan error) @@ -286,7 +286,7 @@ func TestGitAttributeCheckerError(t *testing.T) { case <-time.After(time.Second): t.Error("CheckPath did not complete within 1s") case err = <-errCh: - assert.ErrorIs(t, err, context.Canceled) + require.ErrorIs(t, err, context.Canceled) } }) @@ -297,10 +297,10 @@ func TestGitAttributeCheckerError(t *testing.T) { ac, err := gitRepo.GitAttributeChecker("8fee858da5796dfb37704761701bb8e800ad9ef3", "linguist-language") require.NoError(t, err) - assert.NoError(t, ac.Close()) + require.NoError(t, ac.Close()) _, err = ac.CheckPath("i-am-a-python.p") - assert.ErrorIs(t, err, fs.ErrClosed) + require.ErrorIs(t, err, fs.ErrClosed) }) t.Run("Closed/DuringRun", func(t *testing.T) { @@ -311,13 +311,13 @@ func TestGitAttributeCheckerError(t *testing.T) { require.NoError(t, err) attr, err := ac.CheckPath("i-am-a-python.p") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Python", attr["linguist-language"].String()) - assert.NoError(t, ac.Close()) + require.NoError(t, ac.Close()) _, err = ac.CheckPath("i-am-a-python.p") - assert.ErrorIs(t, err, fs.ErrClosed) + require.ErrorIs(t, err, fs.ErrClosed) }) } diff --git a/modules/git/repo_blob_test.go b/modules/git/repo_blob_test.go index 8a5f5fcd5b..b01847955f 100644 --- a/modules/git/repo_blob_test.go +++ b/modules/git/repo_blob_test.go @@ -10,12 +10,13 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_GetBlob_Found(t *testing.T) { repoPath := filepath.Join(testReposDir, "repo1_bare") r, err := openRepositoryWithDefaultContext(repoPath) - assert.NoError(t, err) + require.NoError(t, err) defer r.Close() testCases := []struct { @@ -28,14 +29,14 @@ func TestRepository_GetBlob_Found(t *testing.T) { for _, testCase := range testCases { blob, err := r.GetBlob(testCase.OID) - assert.NoError(t, err) + require.NoError(t, err) dataReader, err := blob.DataAsync() - assert.NoError(t, err) + require.NoError(t, err) data, err := io.ReadAll(dataReader) - assert.NoError(t, dataReader.Close()) - assert.NoError(t, err) + require.NoError(t, dataReader.Close()) + require.NoError(t, err) assert.Equal(t, testCase.Data, data) } } @@ -43,7 +44,7 @@ func TestRepository_GetBlob_Found(t *testing.T) { func TestRepository_GetBlob_NotExist(t *testing.T) { repoPath := filepath.Join(testReposDir, "repo1_bare") r, err := openRepositoryWithDefaultContext(repoPath) - assert.NoError(t, err) + require.NoError(t, err) defer r.Close() testCase := "0000000000000000000000000000000000000000" @@ -57,7 +58,7 @@ func TestRepository_GetBlob_NotExist(t *testing.T) { func TestRepository_GetBlob_NoId(t *testing.T) { repoPath := filepath.Join(testReposDir, "repo1_bare") r, err := openRepositoryWithDefaultContext(repoPath) - assert.NoError(t, err) + require.NoError(t, err) defer r.Close() testCase := "" diff --git a/modules/git/repo_branch_test.go b/modules/git/repo_branch_test.go index fe788946e5..4b870c06fa 100644 --- a/modules/git/repo_branch_test.go +++ b/modules/git/repo_branch_test.go @@ -8,32 +8,33 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_GetBranches(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() branches, countAll, err := bareRepo1.GetBranchNames(0, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, branches, 2) assert.EqualValues(t, 3, countAll) assert.ElementsMatch(t, []string{"master", "branch2"}, branches) branches, countAll, err = bareRepo1.GetBranchNames(0, 0) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, branches, 3) assert.EqualValues(t, 3, countAll) assert.ElementsMatch(t, []string{"master", "branch2", "branch1"}, branches) branches, countAll, err = bareRepo1.GetBranchNames(5, 1) - assert.NoError(t, err) - assert.Len(t, branches, 0) + require.NoError(t, err) + assert.Empty(t, branches) assert.EqualValues(t, 3, countAll) assert.ElementsMatch(t, []string{}, branches) } @@ -64,20 +65,20 @@ func TestGetRefsBySha(t *testing.T) { // do not exist branches, err := bareRepo5.GetRefsBySha("8006ff9adbf0cb94da7dad9e537e53817f9fa5c0", "") - assert.NoError(t, err) - assert.Len(t, branches, 0) + require.NoError(t, err) + assert.Empty(t, branches) // refs/pull/1/head branches, err = bareRepo5.GetRefsBySha("c83380d7056593c51a699d12b9c00627bd5743e9", PullPrefix) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, []string{"refs/pull/1/head"}, branches) branches, err = bareRepo5.GetRefsBySha("d8e0bbb45f200e67d9a784ce55bd90821af45ebd", BranchPrefix) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, []string{"refs/heads/master", "refs/heads/master-clone"}, branches) branches, err = bareRepo5.GetRefsBySha("58a4bcc53ac13e7ff76127e0fb518b5262bf09af", BranchPrefix) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, []string{"refs/heads/test-patch-1"}, branches) } diff --git a/modules/git/repo_commit_test.go b/modules/git/repo_commit_test.go index fee145e924..e2a9f97fae 100644 --- a/modules/git/repo_commit_test.go +++ b/modules/git/repo_commit_test.go @@ -8,12 +8,13 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_GetCommitBranches(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() // these test case are specific to the repo1_bare test repo @@ -30,9 +31,9 @@ func TestRepository_GetCommitBranches(t *testing.T) { } for _, testCase := range testCases { commit, err := bareRepo1.GetCommit(testCase.CommitID) - assert.NoError(t, err) + require.NoError(t, err) branches, err := bareRepo1.getBranches(commit, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, testCase.ExpectedBranches, branches) } } @@ -40,12 +41,12 @@ func TestRepository_GetCommitBranches(t *testing.T) { func TestGetTagCommitWithSignature(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() // both the tag and the commit are signed here, this validates only the commit signature commit, err := bareRepo1.GetCommit("28b55526e7100924d864dd89e35c1ea62e7a5a32") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, commit) assert.NotNil(t, commit.Signature) // test that signature is not in message @@ -55,34 +56,34 @@ func TestGetTagCommitWithSignature(t *testing.T) { func TestGetCommitWithBadCommitID(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() commit, err := bareRepo1.GetCommit("bad_branch") assert.Nil(t, commit) - assert.Error(t, err) + require.Error(t, err) assert.True(t, IsErrNotExist(err)) } func TestIsCommitInBranch(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() result, err := bareRepo1.IsCommitInBranch("2839944139e0de9737a044f78b0e4b40d989a9e3", "branch1") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, result) result, err = bareRepo1.IsCommitInBranch("2839944139e0de9737a044f78b0e4b40d989a9e3", "branch2") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, result) } func TestRepository_CommitsBetweenIDs(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo4_commitsbetween") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() cases := []struct { @@ -96,7 +97,7 @@ func TestRepository_CommitsBetweenIDs(t *testing.T) { } for i, c := range cases { commits, err := bareRepo1.CommitsBetweenIDs(c.NewID, c.OldID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, commits, c.ExpectedCommits, "case %d", i) } } diff --git a/modules/git/repo_compare_test.go b/modules/git/repo_compare_test.go index 9983873186..86bd6855a7 100644 --- a/modules/git/repo_compare_test.go +++ b/modules/git/repo_compare_test.go @@ -10,19 +10,20 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetFormatPatch(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") clonedPath, err := cloneRepo(t, bareRepo1Path) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } repo, err := openRepositoryWithDefaultContext(clonedPath) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } defer repo.Close() @@ -30,13 +31,13 @@ func TestGetFormatPatch(t *testing.T) { rd := &bytes.Buffer{} err = repo.GetPatch("8d92fc95^", "8d92fc95", rd) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } patchb, err := io.ReadAll(rd) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } @@ -50,29 +51,29 @@ func TestReadPatch(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") repo, err := openRepositoryWithDefaultContext(bareRepo1Path) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } defer repo.Close() // This patch doesn't exist noFile, err := repo.ReadPatchCommit(0) - assert.Error(t, err) + require.Error(t, err) // This patch is an empty one (sometimes it's a 404) noCommit, err := repo.ReadPatchCommit(1) - assert.Error(t, err) + require.Error(t, err) // This patch is legit and should return a commit oldCommit, err := repo.ReadPatchCommit(2) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } assert.Empty(t, noFile) assert.Empty(t, noCommit) assert.Len(t, oldCommit, 40) - assert.True(t, oldCommit == "6e8e2a6f9efd71dbe6917816343ed8415ad696c3") + assert.Equal(t, "6e8e2a6f9efd71dbe6917816343ed8415ad696c3", oldCommit) } func TestReadWritePullHead(t *testing.T) { @@ -82,52 +83,52 @@ func TestReadWritePullHead(t *testing.T) { // As we are writing we should clone the repository first clonedPath, err := cloneRepo(t, bareRepo1Path) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } repo, err := openRepositoryWithDefaultContext(clonedPath) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } defer repo.Close() // Try to open non-existing Pull _, err = repo.GetRefCommitID(PullPrefix + "0/head") - assert.Error(t, err) + require.Error(t, err) // Write a fake sha1 with only 40 zeros newCommit := "feaf4ba6bc635fec442f46ddd4512416ec43c2c2" err = repo.SetReference(PullPrefix+"1/head", newCommit) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } // Read the file created headContents, err := repo.GetRefCommitID(PullPrefix + "1/head") if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } assert.Len(t, headContents, 40) - assert.True(t, headContents == newCommit) + assert.Equal(t, newCommit, headContents) // Remove file after the test err = repo.RemoveReference(PullPrefix + "1/head") - assert.NoError(t, err) + require.NoError(t, err) } func TestGetCommitFilesChanged(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") repo, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() objectFormat, err := repo.GetObjectFormat() - assert.NoError(t, err) + require.NoError(t, err) testCases := []struct { base, head string @@ -157,7 +158,7 @@ func TestGetCommitFilesChanged(t *testing.T) { for _, tc := range testCases { changedFiles, err := repo.GetFilesChangedBetween(tc.base, tc.head) - assert.NoError(t, err) + require.NoError(t, err) assert.ElementsMatch(t, tc.files, changedFiles) } } diff --git a/modules/git/repo_language_stats_test.go b/modules/git/repo_language_stats_test.go index da3871e909..1ee5f4c3af 100644 --- a/modules/git/repo_language_stats_test.go +++ b/modules/git/repo_language_stats_test.go @@ -10,20 +10,18 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_GetLanguageStats(t *testing.T) { repoPath := filepath.Join(testReposDir, "language_stats_repo") gitRepo, err := openRepositoryWithDefaultContext(repoPath) - if !assert.NoError(t, err) { - t.Fatal() - } + require.NoError(t, err) + defer gitRepo.Close() stats, err := gitRepo.GetLanguageStats("8fee858da5796dfb37704761701bb8e800ad9ef3") - if !assert.NoError(t, err) { - t.Fatal() - } + require.NoError(t, err) assert.EqualValues(t, map[string]int64{ "Python": 134, diff --git a/modules/git/repo_ref_test.go b/modules/git/repo_ref_test.go index c08ea12760..609bef585d 100644 --- a/modules/git/repo_ref_test.go +++ b/modules/git/repo_ref_test.go @@ -8,17 +8,18 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_GetRefs(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() refs, err := bareRepo1.GetRefs() - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, refs, 6) expectedRefs := []string{ @@ -38,12 +39,12 @@ func TestRepository_GetRefs(t *testing.T) { func TestRepository_GetRefsFiltered(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() refs, err := bareRepo1.GetRefsFiltered(TagPrefix) - assert.NoError(t, err) + require.NoError(t, err) if assert.Len(t, refs, 2) { assert.Equal(t, TagPrefix+"signed-tag", refs[0].Name) assert.Equal(t, "tag", refs[0].Type) diff --git a/modules/git/repo_stats_test.go b/modules/git/repo_stats_test.go index 3d032385ee..2a15b6f1b7 100644 --- a/modules/git/repo_stats_test.go +++ b/modules/git/repo_stats_test.go @@ -9,19 +9,20 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_GetCodeActivityStats(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) defer bareRepo1.Close() timeFrom, err := time.Parse(time.RFC3339, "2016-01-01T00:00:00+00:00") - assert.NoError(t, err) + require.NoError(t, err) code, err := bareRepo1.GetCodeActivityStats(timeFrom, "") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, code) assert.EqualValues(t, 10, code.CommitCount) diff --git a/modules/git/repo_tag_test.go b/modules/git/repo_tag_test.go index 8f0875c60d..1cf420ad63 100644 --- a/modules/git/repo_tag_test.go +++ b/modules/git/repo_tag_test.go @@ -15,14 +15,14 @@ func TestRepository_GetTags(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") bareRepo1, err := openRepositoryWithDefaultContext(bareRepo1Path) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } defer bareRepo1.Close() tags, total, err := bareRepo1.GetTagInfos(0, 0) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } assert.Len(t, tags, 2) @@ -40,13 +40,13 @@ func TestRepository_GetTag(t *testing.T) { clonedPath, err := cloneRepo(t, bareRepo1Path) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } bareRepo1, err := openRepositoryWithDefaultContext(clonedPath) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } defer bareRepo1.Close() @@ -58,14 +58,14 @@ func TestRepository_GetTag(t *testing.T) { // Create the lightweight tag err = bareRepo1.CreateTag(lTagName, lTagCommitID) if err != nil { - assert.NoError(t, err, "Unable to create the lightweight tag: %s for ID: %s. Error: %v", lTagName, lTagCommitID, err) + require.NoError(t, err, "Unable to create the lightweight tag: %s for ID: %s. Error: %v", lTagName, lTagCommitID, err) return } // and try to get the Tag for lightweight tag lTag, err := bareRepo1.GetTag(lTagName) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } if lTag == nil { @@ -85,20 +85,20 @@ func TestRepository_GetTag(t *testing.T) { // Create the annotated tag err = bareRepo1.CreateAnnotatedTag(aTagName, aTagMessage, aTagCommitID) if err != nil { - assert.NoError(t, err, "Unable to create the annotated tag: %s for ID: %s. Error: %v", aTagName, aTagCommitID, err) + require.NoError(t, err, "Unable to create the annotated tag: %s for ID: %s. Error: %v", aTagName, aTagCommitID, err) return } // Now try to get the tag for the annotated Tag aTagID, err := bareRepo1.GetTagID(aTagName) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } aTag, err := bareRepo1.GetTag(aTagName) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } if aTag == nil { @@ -118,20 +118,20 @@ func TestRepository_GetTag(t *testing.T) { err = bareRepo1.CreateTag(rTagName, rTagCommitID) if err != nil { - assert.NoError(t, err, "Unable to create the tag: %s for ID: %s. Error: %v", rTagName, rTagCommitID, err) + require.NoError(t, err, "Unable to create the tag: %s for ID: %s. Error: %v", rTagName, rTagCommitID, err) return } rTagID, err := bareRepo1.GetTagID(rTagName) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } assert.EqualValues(t, rTagCommitID, rTagID) oTagID, err := bareRepo1.GetTagID(lTagName) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } assert.EqualValues(t, lTagCommitID, oTagID) @@ -142,13 +142,13 @@ func TestRepository_GetAnnotatedTag(t *testing.T) { clonedPath, err := cloneRepo(t, bareRepo1Path) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } bareRepo1, err := openRepositoryWithDefaultContext(clonedPath) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } defer bareRepo1.Close() @@ -166,7 +166,7 @@ func TestRepository_GetAnnotatedTag(t *testing.T) { // Try an annotated tag tag, err := bareRepo1.GetAnnotatedTag(aTagID) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } assert.NotNil(t, tag) @@ -176,19 +176,19 @@ func TestRepository_GetAnnotatedTag(t *testing.T) { // Annotated tag's Commit ID should fail tag2, err := bareRepo1.GetAnnotatedTag(aTagCommitID) - assert.Error(t, err) + require.Error(t, err) assert.True(t, IsErrNotExist(err)) assert.Nil(t, tag2) // Annotated tag's name should fail tag3, err := bareRepo1.GetAnnotatedTag(aTagName) - assert.Error(t, err) - assert.Errorf(t, err, "Length must be 40: %d", len(aTagName)) + require.Error(t, err) + require.Errorf(t, err, "Length must be 40: %d", len(aTagName)) assert.Nil(t, tag3) // Lightweight Tag should fail tag4, err := bareRepo1.GetAnnotatedTag(lTagCommitID) - assert.Error(t, err) + require.Error(t, err) assert.True(t, IsErrNotExist(err)) assert.Nil(t, tag4) } diff --git a/modules/git/repo_test.go b/modules/git/repo_test.go index 9db78153a1..8fb19a5043 100644 --- a/modules/git/repo_test.go +++ b/modules/git/repo_test.go @@ -9,12 +9,13 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetLatestCommitTime(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") lct, err := GetLatestCommitTime(DefaultContext, bareRepo1Path) - assert.NoError(t, err) + require.NoError(t, err) // Time is Sun Nov 13 16:40:14 2022 +0100 // which is the time of commit // ce064814f4a0d337b333e646ece456cd39fab612 (refs/heads/master) @@ -24,31 +25,31 @@ func TestGetLatestCommitTime(t *testing.T) { func TestRepoIsEmpty(t *testing.T) { emptyRepo2Path := filepath.Join(testReposDir, "repo2_empty") repo, err := openRepositoryWithDefaultContext(emptyRepo2Path) - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() isEmpty, err := repo.IsEmpty() - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isEmpty) } func TestRepoGetDivergingCommits(t *testing.T) { bareRepo1Path := filepath.Join(testReposDir, "repo1_bare") do, err := GetDivergingCommits(context.Background(), bareRepo1Path, "master", "branch2") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, DivergeObject{ Ahead: 1, Behind: 5, }, do) do, err = GetDivergingCommits(context.Background(), bareRepo1Path, "master", "master") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, DivergeObject{ Ahead: 0, Behind: 0, }, do) do, err = GetDivergingCommits(context.Background(), bareRepo1Path, "master", "test") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, DivergeObject{ Ahead: 0, Behind: 2, diff --git a/modules/git/tag_test.go b/modules/git/tag_test.go index 79796bbdc2..8279066b2f 100644 --- a/modules/git/tag_test.go +++ b/modules/git/tag_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_parseTagData(t *testing.T) { @@ -85,7 +86,7 @@ v0 for _, test := range testData { tag, err := parseTagData(Sha1ObjectFormat, test.data) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, test.tag.ID, tag.ID) assert.EqualValues(t, test.tag.Object, tag.Object) assert.EqualValues(t, test.tag.Name, tag.Name) diff --git a/modules/git/tree_entry_test.go b/modules/git/tree_entry_test.go index 30eee13669..e628c05a82 100644 --- a/modules/git/tree_entry_test.go +++ b/modules/git/tree_entry_test.go @@ -11,6 +11,7 @@ import ( "github.com/go-git/go-git/v5/plumbing/filemode" "github.com/go-git/go-git/v5/plumbing/object" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func getTestEntries() Entries { @@ -56,47 +57,47 @@ func TestEntriesCustomSort(t *testing.T) { func TestFollowLink(t *testing.T) { r, err := openRepositoryWithDefaultContext("tests/repos/repo1_bare") - assert.NoError(t, err) + require.NoError(t, err) defer r.Close() commit, err := r.GetCommit("37991dec2c8e592043f47155ce4808d4580f9123") - assert.NoError(t, err) + require.NoError(t, err) // get the symlink lnk, err := commit.Tree.GetTreeEntryByPath("foo/bar/link_to_hello") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, lnk.IsLink()) // should be able to dereference to target target, err := lnk.FollowLink() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "hello", target.Name()) assert.False(t, target.IsLink()) assert.Equal(t, "b14df6442ea5a1b382985a6549b85d435376c351", target.ID.String()) // should error when called on normal file target, err = commit.Tree.GetTreeEntryByPath("file1.txt") - assert.NoError(t, err) + require.NoError(t, err) _, err = target.FollowLink() assert.EqualError(t, err, "file1.txt: not a symlink") // should error for broken links target, err = commit.Tree.GetTreeEntryByPath("foo/broken_link") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, target.IsLink()) _, err = target.FollowLink() assert.EqualError(t, err, "broken_link: broken link") // should error for external links target, err = commit.Tree.GetTreeEntryByPath("foo/outside_repo") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, target.IsLink()) _, err = target.FollowLink() assert.EqualError(t, err, "outside_repo: points outside of repo") // testing fix for short link bug target, err = commit.Tree.GetTreeEntryByPath("foo/link_short") - assert.NoError(t, err) + require.NoError(t, err) _, err = target.FollowLink() assert.EqualError(t, err, "link_short: broken link") } diff --git a/modules/git/tree_test.go b/modules/git/tree_test.go index 6d2b5c84d5..6e5d7f4415 100644 --- a/modules/git/tree_test.go +++ b/modules/git/tree_test.go @@ -8,20 +8,21 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSubTree_Issue29101(t *testing.T) { repo, err := openRepositoryWithDefaultContext(filepath.Join(testReposDir, "repo1_bare")) - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() commit, err := repo.GetCommit("ce064814f4a0d337b333e646ece456cd39fab612") - assert.NoError(t, err) + require.NoError(t, err) // old code could produce a different error if called multiple times for i := 0; i < 10; i++ { _, err = commit.SubTree("file1.txt") - assert.Error(t, err) + require.Error(t, err) assert.True(t, IsErrNotExist(err)) } } diff --git a/modules/git/url/url_test.go b/modules/git/url/url_test.go index da820ed889..e1e52c0ed5 100644 --- a/modules/git/url/url_test.go +++ b/modules/git/url/url_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParseGitURLs(t *testing.T) { @@ -158,7 +159,7 @@ func TestParseGitURLs(t *testing.T) { for _, kase := range kases { t.Run(kase.kase, func(t *testing.T) { u, err := Parse(kase.kase) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, kase.expected.extraMark, u.extraMark) assert.EqualValues(t, *kase.expected, *u) }) diff --git a/modules/graceful/releasereopen/releasereopen_test.go b/modules/graceful/releasereopen/releasereopen_test.go index 0e8b48257d..6ab9f955f6 100644 --- a/modules/graceful/releasereopen/releasereopen_test.go +++ b/modules/graceful/releasereopen/releasereopen_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type testReleaseReopener struct { @@ -29,14 +30,14 @@ func TestManager(t *testing.T) { c2 := m.Register(t2) _ = m.Register(t3) - assert.NoError(t, m.ReleaseReopen()) + require.NoError(t, m.ReleaseReopen()) assert.EqualValues(t, 1, t1.count) assert.EqualValues(t, 1, t2.count) assert.EqualValues(t, 1, t3.count) c2() - assert.NoError(t, m.ReleaseReopen()) + require.NoError(t, m.ReleaseReopen()) assert.EqualValues(t, 2, t1.count) assert.EqualValues(t, 1, t2.count) assert.EqualValues(t, 2, t3.count) diff --git a/modules/highlight/highlight_test.go b/modules/highlight/highlight_test.go index dd15b97847..83d35d93ef 100644 --- a/modules/highlight/highlight_test.go +++ b/modules/highlight/highlight_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func lines(s string) (out []template.HTML) { @@ -113,7 +114,7 @@ c=2 for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { out, lexerName, err := File(tt.name, "", []byte(tt.code)) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tt.want, out) assert.Equal(t, tt.lexerName, lexerName) }) diff --git a/modules/httplib/serve_test.go b/modules/httplib/serve_test.go index c2229dffe9..fe609e1672 100644 --- a/modules/httplib/serve_test.go +++ b/modules/httplib/serve_test.go @@ -13,6 +13,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestServeContentByReader(t *testing.T) { @@ -61,7 +62,7 @@ func TestServeContentByReadSeeker(t *testing.T) { data := "0123456789abcdef" tmpFile := t.TempDir() + "/test" err := os.WriteFile(tmpFile, []byte(data), 0o644) - assert.NoError(t, err) + require.NoError(t, err) test := func(t *testing.T, expectedStatusCode int, expectedContent string) { _, rangeStr, _ := strings.Cut(t.Name(), "_range_") @@ -71,9 +72,8 @@ func TestServeContentByReadSeeker(t *testing.T) { } seekReader, err := os.OpenFile(tmpFile, os.O_RDONLY, 0o644) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer seekReader.Close() w := httptest.NewRecorder() diff --git a/modules/indexer/code/indexer_test.go b/modules/indexer/code/indexer_test.go index 2d013e08ed..f43e8e42b6 100644 --- a/modules/indexer/code/indexer_test.go +++ b/modules/indexer/code/indexer_test.go @@ -20,6 +20,7 @@ import ( _ "code.gitea.io/gitea/models/activities" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -30,7 +31,7 @@ func testIndexer(name string, t *testing.T, indexer internal.Indexer) { t.Run(name, func(t *testing.T) { var repoID int64 = 1 err := index(git.DefaultContext, indexer, repoID) - assert.NoError(t, err) + require.NoError(t, err) keywords := []struct { RepoIDs []int64 Keyword string @@ -86,7 +87,7 @@ func testIndexer(name string, t *testing.T, indexer internal.Indexer) { }, IsKeywordFuzzy: true, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, kw.IDs, int(total)) assert.Len(t, langs, kw.Langs) @@ -99,7 +100,7 @@ func testIndexer(name string, t *testing.T, indexer internal.Indexer) { }) } - assert.NoError(t, indexer.Delete(context.Background(), repoID)) + require.NoError(t, indexer.Delete(context.Background(), repoID)) }) } diff --git a/modules/indexer/internal/bleve/metadata_test.go b/modules/indexer/internal/bleve/metadata_test.go index 38827cefc8..31603a92a3 100644 --- a/modules/indexer/internal/bleve/metadata_test.go +++ b/modules/indexer/internal/bleve/metadata_test.go @@ -9,19 +9,20 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMetadata(t *testing.T) { dir := t.TempDir() meta, err := readIndexMetadata(dir) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, &IndexMetadata{}, meta) meta.Version = 24 - assert.NoError(t, writeIndexMetadata(dir, meta)) + require.NoError(t, writeIndexMetadata(dir, meta)) meta, err = readIndexMetadata(dir) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 24, meta.Version) } diff --git a/modules/indexer/issues/indexer_test.go b/modules/indexer/issues/indexer_test.go index 0026ac57b3..a010218b72 100644 --- a/modules/indexer/issues/indexer_test.go +++ b/modules/indexer/issues/indexer_test.go @@ -19,6 +19,7 @@ import ( _ "code.gitea.io/gitea/models/activities" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -26,7 +27,7 @@ func TestMain(m *testing.M) { } func TestDBSearchIssues(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) setting.Indexer.IssueType = "db" InitIssueIndexer(true) @@ -81,9 +82,8 @@ func searchIssueWithKeyword(t *testing.T) { for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -127,9 +127,8 @@ func searchIssueInRepo(t *testing.T) { for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -199,9 +198,7 @@ func searchIssueByID(t *testing.T) { for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -226,9 +223,8 @@ func searchIssueIsPull(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -253,9 +249,7 @@ func searchIssueIsClosed(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -280,9 +274,8 @@ func searchIssueByMilestoneID(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -313,9 +306,8 @@ func searchIssueByLabelID(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -334,9 +326,8 @@ func searchIssueByTime(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -355,9 +346,8 @@ func searchIssueWithOrder(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -388,9 +378,8 @@ func searchIssueInProject(t *testing.T) { } for _, test := range tests { issueIDs, _, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, test.expectedIDs, issueIDs) } } @@ -413,9 +402,8 @@ func searchIssueWithPaginator(t *testing.T) { } for _, test := range tests { issueIDs, total, err := SearchIssues(context.TODO(), &test.opts) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, test.expectedIDs, issueIDs) assert.Equal(t, test.expectedTotal, total) } diff --git a/modules/indexer/issues/internal/tests/tests.go b/modules/indexer/issues/internal/tests/tests.go index 5f2488a06e..a93b2913e9 100644 --- a/modules/indexer/issues/internal/tests/tests.go +++ b/modules/indexer/issues/internal/tests/tests.go @@ -113,7 +113,7 @@ var cases = []*testIndexerCase{ }, }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) assert.Equal(t, len(data), int(result.Total)) }, }, @@ -190,7 +190,7 @@ var cases = []*testIndexerCase{ IsPull: optional.Some(false), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.False(t, data[v.ID].IsPull) } @@ -206,7 +206,7 @@ var cases = []*testIndexerCase{ IsPull: optional.Some(true), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.True(t, data[v.ID].IsPull) } @@ -222,7 +222,7 @@ var cases = []*testIndexerCase{ IsClosed: optional.Some(false), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.False(t, data[v.ID].IsClosed) } @@ -238,7 +238,7 @@ var cases = []*testIndexerCase{ IsClosed: optional.Some(true), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.True(t, data[v.ID].IsClosed) } @@ -288,7 +288,7 @@ var cases = []*testIndexerCase{ MilestoneIDs: []int64{1, 2, 6}, }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Contains(t, []int64{1, 2, 6}, data[v.ID].MilestoneID) } @@ -306,7 +306,7 @@ var cases = []*testIndexerCase{ MilestoneIDs: []int64{0}, }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Equal(t, int64(0), data[v.ID].MilestoneID) } @@ -324,7 +324,7 @@ var cases = []*testIndexerCase{ ProjectID: optional.Some(int64(1)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Equal(t, int64(1), data[v.ID].ProjectID) } @@ -342,7 +342,7 @@ var cases = []*testIndexerCase{ ProjectID: optional.Some(int64(0)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Equal(t, int64(0), data[v.ID].ProjectID) } @@ -360,7 +360,7 @@ var cases = []*testIndexerCase{ ProjectColumnID: optional.Some(int64(1)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Equal(t, int64(1), data[v.ID].ProjectColumnID) } @@ -378,7 +378,7 @@ var cases = []*testIndexerCase{ ProjectColumnID: optional.Some(int64(0)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Equal(t, int64(0), data[v.ID].ProjectColumnID) } @@ -396,7 +396,7 @@ var cases = []*testIndexerCase{ PosterID: optional.Some(int64(1)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Equal(t, int64(1), data[v.ID].PosterID) } @@ -414,7 +414,7 @@ var cases = []*testIndexerCase{ AssigneeID: optional.Some(int64(1)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Equal(t, int64(1), data[v.ID].AssigneeID) } @@ -432,7 +432,7 @@ var cases = []*testIndexerCase{ AssigneeID: optional.Some(int64(0)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Equal(t, int64(0), data[v.ID].AssigneeID) } @@ -450,7 +450,7 @@ var cases = []*testIndexerCase{ MentionID: optional.Some(int64(1)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Contains(t, data[v.ID].MentionIDs, int64(1)) } @@ -468,7 +468,7 @@ var cases = []*testIndexerCase{ ReviewedID: optional.Some(int64(1)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Contains(t, data[v.ID].ReviewedIDs, int64(1)) } @@ -486,7 +486,7 @@ var cases = []*testIndexerCase{ ReviewRequestedID: optional.Some(int64(1)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Contains(t, data[v.ID].ReviewRequestedIDs, int64(1)) } @@ -504,7 +504,7 @@ var cases = []*testIndexerCase{ SubscriberID: optional.Some(int64(1)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.Contains(t, data[v.ID].SubscriberIDs, int64(1)) } @@ -523,7 +523,7 @@ var cases = []*testIndexerCase{ UpdatedBeforeUnix: optional.Some(int64(30)), }, Expected: func(t *testing.T, data map[int64]*internal.IndexerData, result *internal.SearchResult) { - assert.Equal(t, 5, len(result.Hits)) + assert.Len(t, result.Hits, 5) for _, v := range result.Hits { assert.GreaterOrEqual(t, data[v.ID].UpdatedUnix, int64(20)) assert.LessOrEqual(t, data[v.ID].UpdatedUnix, int64(30)) diff --git a/modules/indexer/issues/meilisearch/meilisearch_test.go b/modules/indexer/issues/meilisearch/meilisearch_test.go index 3c19ac85b3..349102b762 100644 --- a/modules/indexer/issues/meilisearch/meilisearch_test.go +++ b/modules/indexer/issues/meilisearch/meilisearch_test.go @@ -15,6 +15,7 @@ import ( "github.com/meilisearch/meilisearch-go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMeilisearchIndexer(t *testing.T) { @@ -58,7 +59,7 @@ func TestConvertHits(t *testing.T) { _, err := convertHits(&meilisearch.SearchResponse{ Hits: []any{"aa", "bb", "cc", "dd"}, }) - assert.ErrorIs(t, err, ErrMalformedResponse) + require.ErrorIs(t, err, ErrMalformedResponse) validResponse := &meilisearch.SearchResponse{ Hits: []any{ @@ -83,7 +84,7 @@ func TestConvertHits(t *testing.T) { }, } hits, err := convertHits(validResponse) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, []internal.Match{{ID: 11}, {ID: 22}, {ID: 33}}, hits) } diff --git a/modules/indexer/stats/indexer_test.go b/modules/indexer/stats/indexer_test.go index 5be45d7a3b..3ab2e58546 100644 --- a/modules/indexer/stats/indexer_test.go +++ b/modules/indexer/stats/indexer_test.go @@ -19,6 +19,7 @@ import ( _ "code.gitea.io/gitea/models/activities" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -26,26 +27,26 @@ func TestMain(m *testing.M) { } func TestRepoStatsIndex(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) setting.CfgProvider, _ = setting.NewConfigProviderFromData("") setting.LoadQueueSettings() err := Init() - assert.NoError(t, err) + require.NoError(t, err) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) err = UpdateRepoIndexer(repo) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, queue.GetManager().FlushAll(context.Background(), 5*time.Second)) + require.NoError(t, queue.GetManager().FlushAll(context.Background(), 5*time.Second)) status, err := repo_model.GetIndexerStatus(db.DefaultContext, repo, repo_model.RepoIndexerTypeStats) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "65f1bf27bc3bf70f64657658635e66094edbcb4d", status.CommitSha) langs, err := repo_model.GetTopLanguageStats(db.DefaultContext, repo, 5) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, langs) } diff --git a/modules/lfs/http_client_test.go b/modules/lfs/http_client_test.go index ec90f5375d..534a445310 100644 --- a/modules/lfs/http_client_test.go +++ b/modules/lfs/http_client_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type RoundTripFunc func(req *http.Request) *http.Response @@ -170,7 +171,7 @@ func TestHTTPClientDownload(t *testing.T) { var batchRequest BatchRequest err := json.NewDecoder(req.Body).Decode(&batchRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "download", batchRequest.Operation) assert.Len(t, batchRequest.Objects, 1) @@ -261,14 +262,14 @@ func TestHTTPClientDownload(t *testing.T) { return objectError } b, err := io.ReadAll(content) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("dummy"), b) return nil }) if len(c.expectederror) > 0 { assert.True(t, strings.Contains(err.Error(), c.expectederror), "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror) } else { - assert.NoError(t, err, "case %d", n) + require.NoError(t, err, "case %d", n) } } } @@ -283,7 +284,7 @@ func TestHTTPClientUpload(t *testing.T) { var batchRequest BatchRequest err := json.NewDecoder(req.Body).Decode(&batchRequest) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "upload", batchRequest.Operation) assert.Len(t, batchRequest.Objects, 1) @@ -370,7 +371,7 @@ func TestHTTPClientUpload(t *testing.T) { if len(c.expectederror) > 0 { assert.True(t, strings.Contains(err.Error(), c.expectederror), "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror) } else { - assert.NoError(t, err, "case %d", n) + require.NoError(t, err, "case %d", n) } } } diff --git a/modules/lfs/pointer_test.go b/modules/lfs/pointer_test.go index 41b5459fef..9299a8a832 100644 --- a/modules/lfs/pointer_test.go +++ b/modules/lfs/pointer_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestStringContent(t *testing.T) { @@ -45,7 +46,7 @@ func TestIsValid(t *testing.T) { func TestGeneratePointer(t *testing.T) { p, err := GeneratePointer(strings.NewReader("Gitea")) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, p.IsValid()) assert.Equal(t, "94cb57646c54a297c9807697e80a30946f79a4b82cb079d2606847825b1812cc", p.Oid) assert.Equal(t, int64(5), p.Size) @@ -53,41 +54,41 @@ func TestGeneratePointer(t *testing.T) { func TestReadPointerFromBuffer(t *testing.T) { p, err := ReadPointerFromBuffer([]byte{}) - assert.ErrorIs(t, err, ErrMissingPrefix) + require.ErrorIs(t, err, ErrMissingPrefix) assert.False(t, p.IsValid()) p, err = ReadPointerFromBuffer([]byte("test")) - assert.ErrorIs(t, err, ErrMissingPrefix) + require.ErrorIs(t, err, ErrMissingPrefix) assert.False(t, p.IsValid()) p, err = ReadPointerFromBuffer([]byte("version https://git-lfs.github.com/spec/v1\n")) - assert.ErrorIs(t, err, ErrInvalidStructure) + require.ErrorIs(t, err, ErrInvalidStructure) assert.False(t, p.IsValid()) p, err = ReadPointerFromBuffer([]byte("version https://git-lfs.github.com/spec/v1\noid sha256:4d7a\nsize 1234\n")) - assert.ErrorIs(t, err, ErrInvalidOIDFormat) + require.ErrorIs(t, err, ErrInvalidOIDFormat) assert.False(t, p.IsValid()) p, err = ReadPointerFromBuffer([]byte("version https://git-lfs.github.com/spec/v1\noid sha256:4d7a2146z4ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize 1234\n")) - assert.ErrorIs(t, err, ErrInvalidOIDFormat) + require.ErrorIs(t, err, ErrInvalidOIDFormat) assert.False(t, p.IsValid()) p, err = ReadPointerFromBuffer([]byte("version https://git-lfs.github.com/spec/v1\noid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\ntest 1234\n")) - assert.Error(t, err) + require.Error(t, err) assert.False(t, p.IsValid()) p, err = ReadPointerFromBuffer([]byte("version https://git-lfs.github.com/spec/v1\noid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize test\n")) - assert.Error(t, err) + require.Error(t, err) assert.False(t, p.IsValid()) p, err = ReadPointerFromBuffer([]byte("version https://git-lfs.github.com/spec/v1\noid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize 1234\n")) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, p.IsValid()) assert.Equal(t, "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393", p.Oid) assert.Equal(t, int64(1234), p.Size) p, err = ReadPointerFromBuffer([]byte("version https://git-lfs.github.com/spec/v1\noid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize 1234\ntest")) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, p.IsValid()) assert.Equal(t, "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393", p.Oid) assert.Equal(t, int64(1234), p.Size) @@ -95,7 +96,7 @@ func TestReadPointerFromBuffer(t *testing.T) { func TestReadPointer(t *testing.T) { p, err := ReadPointer(strings.NewReader("version https://git-lfs.github.com/spec/v1\noid sha256:4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393\nsize 1234\n")) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, p.IsValid()) assert.Equal(t, "4d7a214614ab2935c943f9e0ff69d22eadbb8f32b1258daaa5e2ca24d17e2393", p.Oid) assert.Equal(t, int64(1234), p.Size) diff --git a/modules/lfs/transferadapter_test.go b/modules/lfs/transferadapter_test.go index 7fec137efe..0766e4a0a9 100644 --- a/modules/lfs/transferadapter_test.go +++ b/modules/lfs/transferadapter_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestBasicTransferAdapterName(t *testing.T) { @@ -39,7 +40,7 @@ func TestBasicTransferAdapter(t *testing.T) { assert.Equal(t, "application/octet-stream", req.Header.Get("Content-Type")) b, err := io.ReadAll(req.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "dummy", string(b)) return &http.Response{StatusCode: http.StatusOK} @@ -49,7 +50,7 @@ func TestBasicTransferAdapter(t *testing.T) { var vp Pointer err := json.NewDecoder(req.Body).Decode(&vp) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, p.Oid, vp.Oid) assert.Equal(t, p.Size, vp.Size) @@ -98,7 +99,7 @@ func TestBasicTransferAdapter(t *testing.T) { if len(c.expectederror) > 0 { assert.True(t, strings.Contains(err.Error(), c.expectederror), "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror) } else { - assert.NoError(t, err, "case %d", n) + require.NoError(t, err, "case %d", n) } } }) @@ -131,7 +132,7 @@ func TestBasicTransferAdapter(t *testing.T) { if len(c.expectederror) > 0 { assert.True(t, strings.Contains(err.Error(), c.expectederror), "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror) } else { - assert.NoError(t, err, "case %d", n) + require.NoError(t, err, "case %d", n) } } }) @@ -164,7 +165,7 @@ func TestBasicTransferAdapter(t *testing.T) { if len(c.expectederror) > 0 { assert.True(t, strings.Contains(err.Error(), c.expectederror), "case %d: '%s' should contain '%s'", n, err.Error(), c.expectederror) } else { - assert.NoError(t, err, "case %d", n) + require.NoError(t, err, "case %d", n) } } }) diff --git a/modules/log/event_writer_conn_test.go b/modules/log/event_writer_conn_test.go index 69e87aa8c4..de8694f2c5 100644 --- a/modules/log/event_writer_conn_test.go +++ b/modules/log/event_writer_conn_test.go @@ -14,15 +14,16 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func listenReadAndClose(t *testing.T, l net.Listener, expected string) { conn, err := l.Accept() - assert.NoError(t, err) + require.NoError(t, err) defer conn.Close() written, err := io.ReadAll(conn) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, string(written)) } diff --git a/modules/log/flags_test.go b/modules/log/flags_test.go index 03972a9fb0..a101c42a78 100644 --- a/modules/log/flags_test.go +++ b/modules/log/flags_test.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestFlags(t *testing.T) { @@ -22,9 +23,9 @@ func TestFlags(t *testing.T) { assert.EqualValues(t, "medfile", FlagsFromString("medfile").String()) bs, err := json.Marshal(FlagsFromString("utc,level")) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, `"level,utc"`, string(bs)) var flags Flags - assert.NoError(t, json.Unmarshal(bs, &flags)) + require.NoError(t, json.Unmarshal(bs, &flags)) assert.EqualValues(t, LUTC|Llevel, flags.Bits()) } diff --git a/modules/log/level_test.go b/modules/log/level_test.go index cd18a807d8..9831ca5650 100644 --- a/modules/log/level_test.go +++ b/modules/log/level_test.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type testLevel struct { @@ -20,34 +21,34 @@ func TestLevelMarshalUnmarshalJSON(t *testing.T) { levelBytes, err := json.Marshal(testLevel{ Level: INFO, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, string(makeTestLevelBytes(INFO.String())), string(levelBytes)) var testLevel testLevel err = json.Unmarshal(levelBytes, &testLevel) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, INFO, testLevel.Level) err = json.Unmarshal(makeTestLevelBytes(`FOFOO`), &testLevel) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, INFO, testLevel.Level) err = json.Unmarshal([]byte(fmt.Sprintf(`{"level":%d}`, 2)), &testLevel) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, INFO, testLevel.Level) err = json.Unmarshal([]byte(fmt.Sprintf(`{"level":%d}`, 10012)), &testLevel) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, INFO, testLevel.Level) err = json.Unmarshal([]byte(`{"level":{}}`), &testLevel) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, INFO, testLevel.Level) assert.Equal(t, INFO.String(), Level(1001).String()) err = json.Unmarshal([]byte(`{"level":{}`), &testLevel.Level) - assert.Error(t, err) + require.Error(t, err) } func makeTestLevelBytes(level string) []byte { diff --git a/modules/log/logger_test.go b/modules/log/logger_test.go index 70222f64f5..0de14eb411 100644 --- a/modules/log/logger_test.go +++ b/modules/log/logger_test.go @@ -56,7 +56,7 @@ func TestLogger(t *testing.T) { logger := NewLoggerWithWriters(context.Background(), "test") dump := logger.DumpWriters() - assert.EqualValues(t, 0, len(dump)) + assert.Empty(t, dump) assert.EqualValues(t, NONE, logger.GetLevel()) assert.False(t, logger.IsEnabled()) @@ -69,7 +69,7 @@ func TestLogger(t *testing.T) { assert.EqualValues(t, DEBUG, logger.GetLevel()) dump = logger.DumpWriters() - assert.EqualValues(t, 2, len(dump)) + assert.Len(t, dump, 2) logger.Trace("trace-level") // this level is not logged logger.Debug("debug-level") diff --git a/modules/log/manager_test.go b/modules/log/manager_test.go index b8fbf84613..3839080172 100644 --- a/modules/log/manager_test.go +++ b/modules/log/manager_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSharedWorker(t *testing.T) { @@ -16,7 +17,7 @@ func TestSharedWorker(t *testing.T) { m := NewManager() _, err := m.NewSharedWriter("dummy-1", "dummy", WriterMode{Level: DEBUG, Flags: FlagsFromBits(0)}) - assert.NoError(t, err) + require.NoError(t, err) w := m.GetSharedWriter("dummy-1") assert.NotNil(t, w) diff --git a/modules/markup/console/console_test.go b/modules/markup/console/console_test.go index 2337d91ac5..0d4a2bbeb9 100644 --- a/modules/markup/console/console_test.go +++ b/modules/markup/console/console_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/markup" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRenderConsole(t *testing.T) { @@ -26,7 +27,7 @@ func TestRenderConsole(t *testing.T) { err := render.Render(&markup.RenderContext{Ctx: git.DefaultContext}, strings.NewReader(k), &buf) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, v, buf.String()) } } diff --git a/modules/markup/csv/csv_test.go b/modules/markup/csv/csv_test.go index 8c07184b21..383f134155 100644 --- a/modules/markup/csv/csv_test.go +++ b/modules/markup/csv/csv_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/markup" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRenderCSV(t *testing.T) { @@ -26,7 +27,7 @@ func TestRenderCSV(t *testing.T) { var buf strings.Builder err := render.Render(&markup.RenderContext{Ctx: git.DefaultContext}, strings.NewReader(k), &buf) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, v, buf.String()) } } diff --git a/modules/markup/html_internal_test.go b/modules/markup/html_internal_test.go index 18088af0ca..17eff59d56 100644 --- a/modules/markup/html_internal_test.go +++ b/modules/markup/html_internal_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -294,7 +295,7 @@ func testRenderIssueIndexPattern(t *testing.T, input, expected string, ctx *Rend var buf strings.Builder err := postProcess(ctx, []processor{issueIndexPatternProcessor}, strings.NewReader(input), &buf) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, buf.String(), "input=%q", input) } @@ -310,7 +311,7 @@ func TestRender_AutoLink(t *testing.T) { }, Metas: localMetas, }, strings.NewReader(input), &buffer) - assert.Equal(t, err, nil) + require.NoError(t, err, nil) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer.String())) buffer.Reset() @@ -322,7 +323,7 @@ func TestRender_AutoLink(t *testing.T) { Metas: localMetas, IsWiki: true, }, strings.NewReader(input), &buffer) - assert.Equal(t, err, nil) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer.String())) } @@ -353,7 +354,7 @@ func TestRender_FullIssueURLs(t *testing.T) { }, Metas: localMetas, }, []processor{fullIssuePatternProcessor}, strings.NewReader(input), &result) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, result.String()) } test("Here is a link https://git.osgeo.org/gogs/postgis/postgis/pulls/6", diff --git a/modules/markup/html_test.go b/modules/markup/html_test.go index fa49e60a16..42ce99903d 100644 --- a/modules/markup/html_test.go +++ b/modules/markup/html_test.go @@ -51,7 +51,7 @@ func TestRender_Commits(t *testing.T) { }, Metas: localMetas, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } @@ -105,7 +105,7 @@ func TestRender_CrossReferences(t *testing.T) { }, Metas: localMetas, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } @@ -146,7 +146,7 @@ func TestRender_links(t *testing.T) { Base: markup.TestRepoURL, }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } // Text that should be turned into URL @@ -248,7 +248,7 @@ func TestRender_email(t *testing.T) { Base: markup.TestRepoURL, }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(res)) } // Text that should be turned into email link @@ -321,7 +321,7 @@ func TestRender_emoji(t *testing.T) { Base: markup.TestRepoURL, }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } @@ -387,7 +387,7 @@ func TestRender_ShortLinks(t *testing.T) { BranchPath: "master", }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(string(buffer))) buffer, err = markdown.RenderString(&markup.RenderContext{ Ctx: git.DefaultContext, @@ -397,7 +397,7 @@ func TestRender_ShortLinks(t *testing.T) { Metas: localMetas, IsWiki: true, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expectedWiki), strings.TrimSpace(string(buffer))) } @@ -500,7 +500,7 @@ func TestRender_RelativeImages(t *testing.T) { }, Metas: localMetas, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(string(buffer))) buffer, err = markdown.RenderString(&markup.RenderContext{ Ctx: git.DefaultContext, @@ -510,7 +510,7 @@ func TestRender_RelativeImages(t *testing.T) { Metas: localMetas, IsWiki: true, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expectedWiki), strings.TrimSpace(string(buffer))) } @@ -546,7 +546,7 @@ func Test_ParseClusterFuzz(t *testing.T) { }, Metas: localMetas, }, strings.NewReader(data), &res) - assert.NoError(t, err) + require.NoError(t, err) assert.NotContains(t, res.String(), "783b039...da951ce", res.String()) } @@ -707,7 +707,7 @@ func TestRender_FilePreview(t *testing.T) { RelativePath: ".md", Metas: metas, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } diff --git a/modules/markup/markdown/markdown_test.go b/modules/markup/markdown/markdown_test.go index d0bb129b71..e3dc6c9655 100644 --- a/modules/markup/markdown/markdown_test.go +++ b/modules/markup/markdown/markdown_test.go @@ -20,6 +20,7 @@ import ( "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -57,7 +58,7 @@ func TestRender_StandardLinks(t *testing.T) { Base: FullURL, }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(string(buffer))) buffer, err = markdown.RenderString(&markup.RenderContext{ @@ -67,7 +68,7 @@ func TestRender_StandardLinks(t *testing.T) { }, IsWiki: true, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expectedWiki), strings.TrimSpace(string(buffer))) } @@ -91,7 +92,7 @@ func TestRender_Images(t *testing.T) { Base: FullURL, }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(string(buffer))) } @@ -300,7 +301,7 @@ func TestTotal_RenderWiki(t *testing.T) { Metas: localMetas, IsWiki: true, }, sameCases[i]) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, template.HTML(answers[i]), line) } @@ -325,7 +326,7 @@ func TestTotal_RenderWiki(t *testing.T) { }, IsWiki: true, }, testCases[i]) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, template.HTML(testCases[i+1]), line) } } @@ -344,7 +345,7 @@ func TestTotal_RenderString(t *testing.T) { }, Metas: localMetas, }, sameCases[i]) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, template.HTML(answers[i]), line) } @@ -357,7 +358,7 @@ func TestTotal_RenderString(t *testing.T) { Base: FullURL, }, }, testCases[i]) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, template.HTML(testCases[i+1]), line) } } @@ -365,17 +366,17 @@ func TestTotal_RenderString(t *testing.T) { func TestRender_RenderParagraphs(t *testing.T) { test := func(t *testing.T, str string, cnt int) { res, err := markdown.RenderRawString(&markup.RenderContext{Ctx: git.DefaultContext}, str) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, cnt, strings.Count(res, "image2

` res, err := markdown.RenderRawString(&markup.RenderContext{Ctx: git.DefaultContext}, testcase) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expected, res) } @@ -424,7 +425,7 @@ func TestRenderEmojiInLinks_Issue12331(t *testing.T) { expected := `

Link with emoji 🌔 in text

` res, err := markdown.RenderString(&markup.RenderContext{Ctx: git.DefaultContext}, testcase) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, template.HTML(expected), res) } @@ -458,7 +459,7 @@ func TestColorPreview(t *testing.T) { for _, test := range positiveTests { res, err := markdown.RenderString(&markup.RenderContext{Ctx: git.DefaultContext}, test.testcase) - assert.NoError(t, err, "Unexpected error in testcase: %q", test.testcase) + require.NoError(t, err, "Unexpected error in testcase: %q", test.testcase) assert.Equal(t, template.HTML(test.expected), res, "Unexpected result in testcase %q", test.testcase) } @@ -477,7 +478,7 @@ func TestColorPreview(t *testing.T) { for _, test := range negativeTests { res, err := markdown.RenderString(&markup.RenderContext{Ctx: git.DefaultContext}, test) - assert.NoError(t, err, "Unexpected error in testcase: %q", test) + require.NoError(t, err, "Unexpected error in testcase: %q", test) assert.NotContains(t, res, ` for i, c := range cases { result, err := markdown.RenderString(&markup.RenderContext{Ctx: context.Background(), Links: c.Links, IsWiki: c.IsWiki}, input) - assert.NoError(t, err, "Unexpected error in testcase: %v", i) + require.NoError(t, err, "Unexpected error in testcase: %v", i) assert.Equal(t, template.HTML(c.Expected), result, "Unexpected result in testcase %v", i) } } @@ -1207,7 +1208,7 @@ func TestCustomMarkdownURL(t *testing.T) { BranchPath: "branch/main", }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(string(buffer))) } @@ -1226,7 +1227,7 @@ func TestYAMLMeta(t *testing.T) { buffer, err := markdown.RenderString(&markup.RenderContext{ Ctx: git.DefaultContext, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(string(buffer))) } @@ -1350,7 +1351,7 @@ func TestCallout(t *testing.T) { buffer, err := markdown.RenderString(&markup.RenderContext{ Ctx: git.DefaultContext, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(string(buffer))) } diff --git a/modules/markup/markdown/meta_test.go b/modules/markup/markdown/meta_test.go index 6949966328..d341ae43e4 100644 --- a/modules/markup/markdown/meta_test.go +++ b/modules/markup/markdown/meta_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) /* @@ -31,7 +32,7 @@ func TestExtractMetadata(t *testing.T) { t.Run("ValidFrontAndBody", func(t *testing.T) { var meta IssueTemplate body, err := ExtractMetadata(fmt.Sprintf("%s\n%s\n%s\n%s", sepTest, frontTest, sepTest, bodyTest), &meta) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, bodyTest, body) assert.Equal(t, metaTest, meta) assert.True(t, meta.Valid()) @@ -40,19 +41,19 @@ func TestExtractMetadata(t *testing.T) { t.Run("NoFirstSeparator", func(t *testing.T) { var meta IssueTemplate _, err := ExtractMetadata(fmt.Sprintf("%s\n%s\n%s", frontTest, sepTest, bodyTest), &meta) - assert.Error(t, err) + require.Error(t, err) }) t.Run("NoLastSeparator", func(t *testing.T) { var meta IssueTemplate _, err := ExtractMetadata(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, bodyTest), &meta) - assert.Error(t, err) + require.Error(t, err) }) t.Run("NoBody", func(t *testing.T) { var meta IssueTemplate body, err := ExtractMetadata(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, sepTest), &meta) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "", body) assert.Equal(t, metaTest, meta) assert.True(t, meta.Valid()) @@ -63,7 +64,7 @@ func TestExtractMetadataBytes(t *testing.T) { t.Run("ValidFrontAndBody", func(t *testing.T) { var meta IssueTemplate body, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s\n%s", sepTest, frontTest, sepTest, bodyTest)), &meta) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, bodyTest, string(body)) assert.Equal(t, metaTest, meta) assert.True(t, meta.Valid()) @@ -72,19 +73,19 @@ func TestExtractMetadataBytes(t *testing.T) { t.Run("NoFirstSeparator", func(t *testing.T) { var meta IssueTemplate _, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", frontTest, sepTest, bodyTest)), &meta) - assert.Error(t, err) + require.Error(t, err) }) t.Run("NoLastSeparator", func(t *testing.T) { var meta IssueTemplate _, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, bodyTest)), &meta) - assert.Error(t, err) + require.Error(t, err) }) t.Run("NoBody", func(t *testing.T) { var meta IssueTemplate body, err := ExtractMetadataBytes([]byte(fmt.Sprintf("%s\n%s\n%s", sepTest, frontTest, sepTest)), &meta) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "", string(body)) assert.Equal(t, metaTest, meta) assert.True(t, meta.Valid()) diff --git a/modules/markup/orgmode/orgmode_test.go b/modules/markup/orgmode/orgmode_test.go index 5ced819984..f41d86a8a8 100644 --- a/modules/markup/orgmode/orgmode_test.go +++ b/modules/markup/orgmode/orgmode_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -32,7 +33,7 @@ func TestRender_StandardLinks(t *testing.T) { Base: setting.AppSubURL, }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } @@ -60,7 +61,7 @@ func TestRender_BaseLinks(t *testing.T) { BranchPath: "branch/main", }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } @@ -73,7 +74,7 @@ func TestRender_BaseLinks(t *testing.T) { TreePath: "deep/nested/folder", }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } @@ -99,7 +100,7 @@ func TestRender_Media(t *testing.T) { Base: setting.AppSubURL, }, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } @@ -140,7 +141,7 @@ func TestRender_Source(t *testing.T) { buffer, err := RenderString(&markup.RenderContext{ Ctx: git.DefaultContext, }, input) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(buffer)) } diff --git a/modules/migration/file_format_test.go b/modules/migration/file_format_test.go index fd7db9074b..f6651cd373 100644 --- a/modules/migration/file_format_test.go +++ b/modules/migration/file_format_test.go @@ -9,14 +9,15 @@ import ( "github.com/santhosh-tekuri/jsonschema/v6" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMigrationJSON_IssueOK(t *testing.T) { issues := make([]*Issue, 0, 10) err := Load("file_format_testdata/issue_a.json", &issues, true) - assert.NoError(t, err) + require.NoError(t, err) err = Load("file_format_testdata/issue_a.yml", &issues, true) - assert.NoError(t, err) + require.NoError(t, err) } func TestMigrationJSON_IssueFail(t *testing.T) { @@ -34,5 +35,5 @@ func TestMigrationJSON_IssueFail(t *testing.T) { func TestMigrationJSON_MilestoneOK(t *testing.T) { milestones := make([]*Milestone, 0, 10) err := Load("file_format_testdata/milestones.json", &milestones, true) - assert.NoError(t, err) + require.NoError(t, err) } diff --git a/modules/optional/serialization_test.go b/modules/optional/serialization_test.go index 09a4bddea0..c852b8a70f 100644 --- a/modules/optional/serialization_test.go +++ b/modules/optional/serialization_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/optional" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) @@ -50,11 +51,11 @@ func TestOptionalToJson(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { b, err := json.Marshal(tc.obj) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tc.want, string(b), "gitea json module returned unexpected") b, err = std_json.Marshal(tc.obj) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tc.want, string(b), "std json module returned unexpected") }) } @@ -88,12 +89,12 @@ func TestOptionalFromJson(t *testing.T) { t.Run(tc.name, func(t *testing.T) { var obj1 testSerializationStruct err := json.Unmarshal([]byte(tc.data), &obj1) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tc.want, obj1, "gitea json module returned unexpected") var obj2 testSerializationStruct err = std_json.Unmarshal([]byte(tc.data), &obj2) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tc.want, obj2, "std json module returned unexpected") }) } @@ -134,7 +135,7 @@ optional_two_string: null for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { b, err := yaml.Marshal(tc.obj) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tc.want, string(b), "yaml module returned unexpected") }) } @@ -183,7 +184,7 @@ optional_twostring: null t.Run(tc.name, func(t *testing.T) { var obj testSerializationStruct err := yaml.Unmarshal([]byte(tc.data), &obj) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, tc.want, obj, "yaml module returned unexpected") }) } diff --git a/modules/packages/alpine/metadata_test.go b/modules/packages/alpine/metadata_test.go index 2a3c48ffb9..8167b4902a 100644 --- a/modules/packages/alpine/metadata_test.go +++ b/modules/packages/alpine/metadata_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -77,7 +78,7 @@ func TestParsePackage(t *testing.T) { pp, err := ParsePackage(data) assert.Nil(t, pp) - assert.ErrorIs(t, err, ErrMissingPKGINFOFile) + require.ErrorIs(t, err, ErrMissingPKGINFOFile) }) t.Run("InvalidPKGINFOFile", func(t *testing.T) { @@ -85,14 +86,14 @@ func TestParsePackage(t *testing.T) { pp, err := ParsePackage(data) assert.Nil(t, pp) - assert.ErrorIs(t, err, ErrInvalidName) + require.ErrorIs(t, err, ErrInvalidName) }) t.Run("Valid", func(t *testing.T) { data := createPackage(".PKGINFO", createPKGINFOContent(packageName, packageVersion)) p, err := ParsePackage(data) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, p) assert.Equal(t, "Q1SRYURM5+uQDqfHSwTnNIOIuuDVQ=", p.FileMetadata.Checksum) @@ -105,7 +106,7 @@ func TestParsePackageInfo(t *testing.T) { p, err := ParsePackageInfo(bytes.NewReader(data)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidName) + require.ErrorIs(t, err, ErrInvalidName) }) t.Run("InvalidVersion", func(t *testing.T) { @@ -113,14 +114,14 @@ func TestParsePackageInfo(t *testing.T) { p, err := ParsePackageInfo(bytes.NewReader(data)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidVersion) + require.ErrorIs(t, err, ErrInvalidVersion) }) t.Run("Valid", func(t *testing.T) { data := createPKGINFOContent(packageName, packageVersion) p, err := ParsePackageInfo(bytes.NewReader(data)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, p) assert.Equal(t, packageName, p.Name) diff --git a/modules/packages/cargo/parser_test.go b/modules/packages/cargo/parser_test.go index 2230a5b499..4b357cb869 100644 --- a/modules/packages/cargo/parser_test.go +++ b/modules/packages/cargo/parser_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -51,7 +52,7 @@ func TestParsePackage(t *testing.T) { cp, err := ParsePackage(data) assert.Nil(t, cp) - assert.ErrorIs(t, err, ErrInvalidName) + require.ErrorIs(t, err, ErrInvalidName) } }) @@ -61,7 +62,7 @@ func TestParsePackage(t *testing.T) { cp, err := ParsePackage(data) assert.Nil(t, cp) - assert.ErrorIs(t, err, ErrInvalidVersion) + require.ErrorIs(t, err, ErrInvalidVersion) } }) @@ -70,7 +71,7 @@ func TestParsePackage(t *testing.T) { cp, err := ParsePackage(data) assert.NotNil(t, cp) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "test", cp.Name) assert.Equal(t, "1.0.0", cp.Version) diff --git a/modules/packages/chef/metadata_test.go b/modules/packages/chef/metadata_test.go index 6def4162a9..8784c629e6 100644 --- a/modules/packages/chef/metadata_test.go +++ b/modules/packages/chef/metadata_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -31,7 +32,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(&buf) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrMissingMetadataFile) + require.ErrorIs(t, err, ErrMissingMetadataFile) }) t.Run("Valid", func(t *testing.T) { @@ -53,7 +54,7 @@ func TestParsePackage(t *testing.T) { zw.Close() p, err := ParsePackage(&buf) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, p) assert.Equal(t, packageName, p.Name) assert.Equal(t, packageVersion, p.Version) @@ -66,7 +67,7 @@ func TestParseChefMetadata(t *testing.T) { for _, name := range []string{" test", "test "} { p, err := ParseChefMetadata(strings.NewReader(`{"name":"` + name + `","version":"1.0.0"}`)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidName) + require.ErrorIs(t, err, ErrInvalidName) } }) @@ -74,14 +75,14 @@ func TestParseChefMetadata(t *testing.T) { for _, version := range []string{"1", "1.2.3.4", "1.0.0 "} { p, err := ParseChefMetadata(strings.NewReader(`{"name":"test","version":"` + version + `"}`)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidVersion) + require.ErrorIs(t, err, ErrInvalidVersion) } }) t.Run("Valid", func(t *testing.T) { p, err := ParseChefMetadata(strings.NewReader(`{"name":"` + packageName + `","version":"` + packageVersion + `","description":"` + packageDescription + `","maintainer":"` + packageAuthor + `","source_url":"` + packageRepositoryURL + `"}`)) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageName, p.Name) assert.Equal(t, packageVersion, p.Version) diff --git a/modules/packages/composer/metadata_test.go b/modules/packages/composer/metadata_test.go index a5e317daf1..2bdb23965b 100644 --- a/modules/packages/composer/metadata_test.go +++ b/modules/packages/composer/metadata_test.go @@ -12,6 +12,7 @@ import ( "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -49,20 +50,20 @@ const composerContent = `{ func TestLicenseUnmarshal(t *testing.T) { var l Licenses - assert.NoError(t, json.NewDecoder(strings.NewReader(`["MIT"]`)).Decode(&l)) + require.NoError(t, json.NewDecoder(strings.NewReader(`["MIT"]`)).Decode(&l)) assert.Len(t, l, 1) assert.Equal(t, "MIT", l[0]) - assert.NoError(t, json.NewDecoder(strings.NewReader(`"MIT"`)).Decode(&l)) + require.NoError(t, json.NewDecoder(strings.NewReader(`"MIT"`)).Decode(&l)) assert.Len(t, l, 1) assert.Equal(t, "MIT", l[0]) } func TestCommentsUnmarshal(t *testing.T) { var c Comments - assert.NoError(t, json.NewDecoder(strings.NewReader(`["comment"]`)).Decode(&c)) + require.NoError(t, json.NewDecoder(strings.NewReader(`["comment"]`)).Decode(&c)) assert.Len(t, c, 1) assert.Equal(t, "comment", c[0]) - assert.NoError(t, json.NewDecoder(strings.NewReader(`"comment"`)).Decode(&c)) + require.NoError(t, json.NewDecoder(strings.NewReader(`"comment"`)).Decode(&c)) assert.Len(t, c, 1) assert.Equal(t, "comment", c[0]) } @@ -84,7 +85,7 @@ func TestParsePackage(t *testing.T) { cp, err := ParsePackage(bytes.NewReader(data), int64(len(data))) assert.Nil(t, cp) - assert.ErrorIs(t, err, ErrMissingComposerFile) + require.ErrorIs(t, err, ErrMissingComposerFile) }) t.Run("MissingComposerFileInRoot", func(t *testing.T) { @@ -92,7 +93,7 @@ func TestParsePackage(t *testing.T) { cp, err := ParsePackage(bytes.NewReader(data), int64(len(data))) assert.Nil(t, cp) - assert.ErrorIs(t, err, ErrMissingComposerFile) + require.ErrorIs(t, err, ErrMissingComposerFile) }) t.Run("InvalidComposerFile", func(t *testing.T) { @@ -100,7 +101,7 @@ func TestParsePackage(t *testing.T) { cp, err := ParsePackage(bytes.NewReader(data), int64(len(data))) assert.Nil(t, cp) - assert.Error(t, err) + require.Error(t, err) }) t.Run("InvalidPackageName", func(t *testing.T) { @@ -108,7 +109,7 @@ func TestParsePackage(t *testing.T) { cp, err := ParsePackage(bytes.NewReader(data), int64(len(data))) assert.Nil(t, cp) - assert.ErrorIs(t, err, ErrInvalidName) + require.ErrorIs(t, err, ErrInvalidName) }) t.Run("InvalidPackageVersion", func(t *testing.T) { @@ -116,14 +117,14 @@ func TestParsePackage(t *testing.T) { cp, err := ParsePackage(bytes.NewReader(data), int64(len(data))) assert.Nil(t, cp) - assert.ErrorIs(t, err, ErrInvalidVersion) + require.ErrorIs(t, err, ErrInvalidVersion) }) t.Run("InvalidReadmePath", func(t *testing.T) { data := createArchive(map[string]string{"composer.json": `{"name": "gitea/composer-package", "readme": "sub/README.md"}`}) cp, err := ParsePackage(bytes.NewReader(data), int64(len(data))) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, cp) assert.Empty(t, cp.Metadata.Readme) @@ -133,7 +134,7 @@ func TestParsePackage(t *testing.T) { data := createArchive(map[string]string{"composer.json": composerContent, "README.md": readme}) cp, err := ParsePackage(bytes.NewReader(data), int64(len(data))) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, cp) assert.Equal(t, name, cp.Name) diff --git a/modules/packages/conan/conanfile_parser_test.go b/modules/packages/conan/conanfile_parser_test.go index 5801570184..fe867fbe76 100644 --- a/modules/packages/conan/conanfile_parser_test.go +++ b/modules/packages/conan/conanfile_parser_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -40,7 +41,7 @@ class ConanPackageConan(ConanFile): func TestParseConanfile(t *testing.T) { metadata, err := ParseConanfile(strings.NewReader(contentConanfile)) - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, license, metadata.License) assert.Equal(t, author, metadata.Author) assert.Equal(t, homepage, metadata.ProjectURL) diff --git a/modules/packages/conan/conaninfo_parser_test.go b/modules/packages/conan/conaninfo_parser_test.go index 556a4b939e..dfb1836474 100644 --- a/modules/packages/conan/conaninfo_parser_test.go +++ b/modules/packages/conan/conaninfo_parser_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -50,7 +51,7 @@ const ( func TestParseConaninfo(t *testing.T) { info, err := ParseConaninfo(strings.NewReader(contentConaninfo)) assert.NotNil(t, info) - assert.Nil(t, err) + require.NoError(t, err) assert.Equal( t, map[string]string{ diff --git a/modules/packages/conan/reference_test.go b/modules/packages/conan/reference_test.go index 6ea86eb0dd..7d39bd8238 100644 --- a/modules/packages/conan/reference_test.go +++ b/modules/packages/conan/reference_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewRecipeReference(t *testing.T) { @@ -40,53 +41,53 @@ func TestNewRecipeReference(t *testing.T) { for i, c := range cases { rref, err := NewRecipeReference(c.Name, c.Version, c.User, c.Channel, c.Revision) if c.IsValid { - assert.NoError(t, err, "case %d, should be invalid", i) + require.NoError(t, err, "case %d, should be invalid", i) assert.NotNil(t, rref, "case %d, should not be nil", i) } else { - assert.Error(t, err, "case %d, should be valid", i) + require.Error(t, err, "case %d, should be valid", i) } } } func TestRecipeReferenceRevisionOrDefault(t *testing.T) { rref, err := NewRecipeReference("name", "1.0", "", "", "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, DefaultRevision, rref.RevisionOrDefault()) rref, err = NewRecipeReference("name", "1.0", "", "", DefaultRevision) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, DefaultRevision, rref.RevisionOrDefault()) rref, err = NewRecipeReference("name", "1.0", "", "", "Az09") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Az09", rref.RevisionOrDefault()) } func TestRecipeReferenceString(t *testing.T) { rref, err := NewRecipeReference("name", "1.0", "", "", "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "name/1.0", rref.String()) rref, err = NewRecipeReference("name", "1.0", "user", "channel", "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "name/1.0@user/channel", rref.String()) rref, err = NewRecipeReference("name", "1.0", "user", "channel", "Az09") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "name/1.0@user/channel#Az09", rref.String()) } func TestRecipeReferenceLinkName(t *testing.T) { rref, err := NewRecipeReference("name", "1.0", "", "", "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "name/1.0/_/_/0", rref.LinkName()) rref, err = NewRecipeReference("name", "1.0", "user", "channel", "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "name/1.0/user/channel/0", rref.LinkName()) rref, err = NewRecipeReference("name", "1.0", "user", "channel", "Az09") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "name/1.0/user/channel/Az09", rref.LinkName()) } @@ -110,10 +111,10 @@ func TestNewPackageReference(t *testing.T) { for i, c := range cases { pref, err := NewPackageReference(c.Recipe, c.Reference, c.Revision) if c.IsValid { - assert.NoError(t, err, "case %d, should be invalid", i) + require.NoError(t, err, "case %d, should be invalid", i) assert.NotNil(t, pref, "case %d, should not be nil", i) } else { - assert.Error(t, err, "case %d, should be valid", i) + require.Error(t, err, "case %d, should be valid", i) } } } @@ -122,15 +123,15 @@ func TestPackageReferenceRevisionOrDefault(t *testing.T) { rref, _ := NewRecipeReference("name", "1.0", "", "", "") pref, err := NewPackageReference(rref, "ref", "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, DefaultRevision, pref.RevisionOrDefault()) pref, err = NewPackageReference(rref, "ref", DefaultRevision) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, DefaultRevision, pref.RevisionOrDefault()) pref, err = NewPackageReference(rref, "ref", "Az09") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Az09", pref.RevisionOrDefault()) } @@ -138,10 +139,10 @@ func TestPackageReferenceLinkName(t *testing.T) { rref, _ := NewRecipeReference("name", "1.0", "", "", "") pref, err := NewPackageReference(rref, "ref", "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "ref/0", pref.LinkName()) pref, err = NewPackageReference(rref, "ref", "Az09") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "ref/Az09", pref.LinkName()) } diff --git a/modules/packages/conda/metadata_test.go b/modules/packages/conda/metadata_test.go index 2bb114f030..1bc4695b56 100644 --- a/modules/packages/conda/metadata_test.go +++ b/modules/packages/conda/metadata_test.go @@ -13,6 +13,7 @@ import ( "github.com/dsnet/compress/bzip2" "github.com/klauspost/compress/zstd" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -46,7 +47,7 @@ func TestParsePackage(t *testing.T) { p, err := parsePackageTar(buf) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidStructure) + require.ErrorIs(t, err, ErrInvalidStructure) }) t.Run("MissingAboutFile", func(t *testing.T) { @@ -54,7 +55,7 @@ func TestParsePackage(t *testing.T) { p, err := parsePackageTar(buf) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "name", p.Name) assert.Equal(t, "1.0", p.Version) @@ -67,7 +68,7 @@ func TestParsePackage(t *testing.T) { p, err := parsePackageTar(buf) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidName) + require.ErrorIs(t, err, ErrInvalidName) } }) @@ -77,7 +78,7 @@ func TestParsePackage(t *testing.T) { p, err := parsePackageTar(buf) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidVersion) + require.ErrorIs(t, err, ErrInvalidVersion) } }) @@ -89,7 +90,7 @@ func TestParsePackage(t *testing.T) { p, err := parsePackageTar(buf) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageName, p.Name) assert.Equal(t, packageVersion, p.Version) @@ -114,7 +115,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackageBZ2(br) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageName, p.Name) assert.Equal(t, packageVersion, p.Version) @@ -141,7 +142,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackageConda(br, int64(br.Len())) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageName, p.Name) assert.Equal(t, packageVersion, p.Version) diff --git a/modules/packages/container/metadata_test.go b/modules/packages/container/metadata_test.go index 665499b2e6..930cf48f68 100644 --- a/modules/packages/container/metadata_test.go +++ b/modules/packages/container/metadata_test.go @@ -11,6 +11,7 @@ import ( oci "github.com/opencontainers/image-spec/specs-go/v1" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParseImageConfig(t *testing.T) { @@ -24,7 +25,7 @@ func TestParseImageConfig(t *testing.T) { configOCI := `{"config": {"labels": {"` + labelAuthors + `": "` + author + `", "` + labelLicenses + `": "` + license + `", "` + labelURL + `": "` + projectURL + `", "` + labelSource + `": "` + repositoryURL + `", "` + labelDocumentation + `": "` + documentationURL + `", "` + labelDescription + `": "` + description + `"}}, "history": [{"created_by": "do it 1"}, {"created_by": "dummy #(nop) do it 2"}]}` metadata, err := ParseImageConfig(oci.MediaTypeImageManifest, strings.NewReader(configOCI)) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, TypeOCI, metadata.Type) assert.Equal(t, description, metadata.Description) @@ -51,7 +52,7 @@ func TestParseImageConfig(t *testing.T) { configHelm := `{"description":"` + description + `", "home": "` + projectURL + `", "sources": ["` + repositoryURL + `"], "maintainers":[{"name":"` + author + `"}]}` metadata, err = ParseImageConfig(helm.ConfigMediaType, strings.NewReader(configHelm)) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, TypeHelm, metadata.Type) assert.Equal(t, description, metadata.Description) diff --git a/modules/packages/cran/metadata_test.go b/modules/packages/cran/metadata_test.go index ff68c34c51..3287380cf0 100644 --- a/modules/packages/cran/metadata_test.go +++ b/modules/packages/cran/metadata_test.go @@ -12,6 +12,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -62,7 +63,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(buf, buf.Size()) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrMissingDescriptionFile) + require.ErrorIs(t, err, ErrMissingDescriptionFile) }) t.Run("Valid", func(t *testing.T) { @@ -74,7 +75,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(buf, buf.Size()) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageName, p.Name) assert.Equal(t, packageVersion, p.Version) @@ -99,7 +100,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(buf, buf.Size()) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrMissingDescriptionFile) + require.ErrorIs(t, err, ErrMissingDescriptionFile) }) t.Run("Valid", func(t *testing.T) { @@ -110,7 +111,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(buf, buf.Size()) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageName, p.Name) assert.Equal(t, packageVersion, p.Version) @@ -123,7 +124,7 @@ func TestParseDescription(t *testing.T) { for _, name := range []string{"123abc", "ab-cd", "ab cd", "ab/cd"} { p, err := ParseDescription(createDescription(name, packageVersion)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidName) + require.ErrorIs(t, err, ErrInvalidName) } }) @@ -131,13 +132,13 @@ func TestParseDescription(t *testing.T) { for _, version := range []string{"1", "1 0", "1.2.3.4.5", "1-2-3-4-5", "1.", "1.0.", "1-", "1-0-"} { p, err := ParseDescription(createDescription(packageName, version)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidVersion) + require.ErrorIs(t, err, ErrInvalidVersion) } }) t.Run("Valid", func(t *testing.T) { p, err := ParseDescription(createDescription(packageName, packageVersion)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, p) assert.Equal(t, packageName, p.Name) diff --git a/modules/packages/debian/metadata_test.go b/modules/packages/debian/metadata_test.go index 26c2a6fc68..94a9805639 100644 --- a/modules/packages/debian/metadata_test.go +++ b/modules/packages/debian/metadata_test.go @@ -13,6 +13,7 @@ import ( "github.com/blakesmith/ar" "github.com/klauspost/compress/zstd" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/ulikunitz/xz" ) @@ -47,7 +48,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrMissingControlFile) + require.ErrorIs(t, err, ErrMissingControlFile) }) t.Run("Compression", func(t *testing.T) { @@ -56,7 +57,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrUnsupportedCompression) + require.ErrorIs(t, err, ErrUnsupportedCompression) }) var buf bytes.Buffer @@ -112,7 +113,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "gitea", p.Name) t.Run("TrailingSlash", func(t *testing.T) { @@ -120,7 +121,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "gitea", p.Name) }) }) @@ -147,7 +148,7 @@ func TestParseControlFile(t *testing.T) { for _, name := range []string{"", "-cd"} { p, err := ParseControlFile(buildContent(name, packageVersion, packageArchitecture)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidName) + require.ErrorIs(t, err, ErrInvalidName) } }) @@ -155,14 +156,14 @@ func TestParseControlFile(t *testing.T) { for _, version := range []string{"", "1-", ":1.0", "1_0"} { p, err := ParseControlFile(buildContent(packageName, version, packageArchitecture)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidVersion) + require.ErrorIs(t, err, ErrInvalidVersion) } }) t.Run("InvalidArchitecture", func(t *testing.T) { p, err := ParseControlFile(buildContent(packageName, packageVersion, "")) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidArchitecture) + require.ErrorIs(t, err, ErrInvalidArchitecture) }) t.Run("Valid", func(t *testing.T) { @@ -170,7 +171,7 @@ func TestParseControlFile(t *testing.T) { full := content.String() p, err := ParseControlFile(content) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, p) assert.Equal(t, packageName, p.Name) diff --git a/modules/packages/goproxy/metadata_test.go b/modules/packages/goproxy/metadata_test.go index 4e7f394f8b..3a47f10269 100644 --- a/modules/packages/goproxy/metadata_test.go +++ b/modules/packages/goproxy/metadata_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -33,7 +34,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data, int64(data.Len())) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidStructure) + require.ErrorIs(t, err, ErrInvalidStructure) }) t.Run("InvalidNameOrVersionStructure", func(t *testing.T) { @@ -43,7 +44,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data, int64(data.Len())) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidStructure) + require.ErrorIs(t, err, ErrInvalidStructure) }) t.Run("GoModFileInWrongDirectory", func(t *testing.T) { @@ -53,7 +54,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data, int64(data.Len())) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageName, p.Name) assert.Equal(t, packageVersion, p.Version) assert.Equal(t, "module gitea.com/go-gitea/gitea", p.GoMod) @@ -67,7 +68,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data, int64(data.Len())) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageName, p.Name) assert.Equal(t, packageVersion, p.Version) assert.Equal(t, "valid", p.GoMod) diff --git a/modules/packages/hashed_buffer_test.go b/modules/packages/hashed_buffer_test.go index 564e782f18..ed5267cd6f 100644 --- a/modules/packages/hashed_buffer_test.go +++ b/modules/packages/hashed_buffer_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestHashedBuffer(t *testing.T) { @@ -27,12 +28,12 @@ func TestHashedBuffer(t *testing.T) { for _, c := range cases { buf, err := CreateHashedBufferFromReaderWithSize(strings.NewReader(c.Data), c.MaxMemorySize) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, len(c.Data), buf.Size()) data, err := io.ReadAll(buf) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, c.Data, string(data)) hashMD5, hashSHA1, hashSHA256, hashSHA512 := buf.Sums() @@ -41,6 +42,6 @@ func TestHashedBuffer(t *testing.T) { assert.Equal(t, c.HashSHA256, hex.EncodeToString(hashSHA256)) assert.Equal(t, c.HashSHA512, hex.EncodeToString(hashSHA512)) - assert.NoError(t, buf.Close()) + require.NoError(t, buf.Close()) } } diff --git a/modules/packages/maven/metadata_test.go b/modules/packages/maven/metadata_test.go index e675467730..d0093013f9 100644 --- a/modules/packages/maven/metadata_test.go +++ b/modules/packages/maven/metadata_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "golang.org/x/text/encoding/charmap" ) @@ -50,12 +51,12 @@ func TestParsePackageMetaData(t *testing.T) { t.Run("InvalidFile", func(t *testing.T) { m, err := ParsePackageMetaData(strings.NewReader("")) assert.Nil(t, m) - assert.Error(t, err) + require.Error(t, err) }) t.Run("Valid", func(t *testing.T) { m, err := ParsePackageMetaData(strings.NewReader(pomContent)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, m) assert.Equal(t, groupID, m.GroupID) @@ -80,10 +81,10 @@ func TestParsePackageMetaData(t *testing.T) { ``, ), ) - assert.NoError(t, err) + require.NoError(t, err) m, err := ParsePackageMetaData(strings.NewReader(pomContent8859_1)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, m) }) } diff --git a/modules/packages/multi_hasher_test.go b/modules/packages/multi_hasher_test.go index a37debbc95..ca333cb0a4 100644 --- a/modules/packages/multi_hasher_test.go +++ b/modules/packages/multi_hasher_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -35,11 +36,11 @@ func TestMultiHasherSums(t *testing.T) { h.Write([]byte("git")) state, err := h.MarshalBinary() - assert.NoError(t, err) + require.NoError(t, err) h2 := NewMultiHasher() err = h2.UnmarshalBinary(state) - assert.NoError(t, err) + require.NoError(t, err) h2.Write([]byte("ea")) diff --git a/modules/packages/npm/creator_test.go b/modules/packages/npm/creator_test.go index 806377a52b..b2cf1aae0e 100644 --- a/modules/packages/npm/creator_test.go +++ b/modules/packages/npm/creator_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParsePackage(t *testing.T) { @@ -34,14 +35,14 @@ func TestParsePackage(t *testing.T) { t.Run("InvalidUpload", func(t *testing.T) { p, err := ParsePackage(bytes.NewReader([]byte{0})) assert.Nil(t, p) - assert.Error(t, err) + require.Error(t, err) }) t.Run("InvalidUploadNoData", func(t *testing.T) { b, _ := json.Marshal(packageUpload{}) p, err := ParsePackage(bytes.NewReader(b)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidPackage) + require.ErrorIs(t, err, ErrInvalidPackage) }) t.Run("InvalidPackageName", func(t *testing.T) { @@ -60,7 +61,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(bytes.NewReader(b)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidPackageName) + require.ErrorIs(t, err, ErrInvalidPackageName) } test(t, " test ") @@ -99,7 +100,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(bytes.NewReader(b)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidPackageVersion) + require.ErrorIs(t, err, ErrInvalidPackageVersion) } test(t, "test") @@ -131,7 +132,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(bytes.NewReader(b)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidPackageVersion) + require.ErrorIs(t, err, ErrInvalidPackageVersion) }) t.Run("InvalidAttachment", func(t *testing.T) { @@ -153,7 +154,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(bytes.NewReader(b)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidAttachment) + require.ErrorIs(t, err, ErrInvalidAttachment) }) t.Run("InvalidData", func(t *testing.T) { @@ -178,7 +179,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(bytes.NewReader(b)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidAttachment) + require.ErrorIs(t, err, ErrInvalidAttachment) }) t.Run("InvalidIntegrity", func(t *testing.T) { @@ -206,7 +207,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(bytes.NewReader(b)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidIntegrity) + require.ErrorIs(t, err, ErrInvalidIntegrity) }) t.Run("InvalidIntegrity2", func(t *testing.T) { @@ -234,7 +235,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(bytes.NewReader(b)) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrInvalidIntegrity) + require.ErrorIs(t, err, ErrInvalidIntegrity) }) t.Run("Valid", func(t *testing.T) { @@ -277,7 +278,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(bytes.NewReader(b)) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageFullName, p.Name) assert.Equal(t, packageVersion, p.Version) diff --git a/modules/packages/nuget/metadata_test.go b/modules/packages/nuget/metadata_test.go index f466492f8a..ecce052be4 100644 --- a/modules/packages/nuget/metadata_test.go +++ b/modules/packages/nuget/metadata_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -77,7 +78,7 @@ func TestParsePackageMetaData(t *testing.T) { np, err := ParsePackageMetaData(bytes.NewReader(data), int64(len(data))) assert.Nil(t, np) - assert.ErrorIs(t, err, ErrMissingNuspecFile) + require.ErrorIs(t, err, ErrMissingNuspecFile) }) t.Run("MissingNuspecFileInRoot", func(t *testing.T) { @@ -85,7 +86,7 @@ func TestParsePackageMetaData(t *testing.T) { np, err := ParsePackageMetaData(bytes.NewReader(data), int64(len(data))) assert.Nil(t, np) - assert.ErrorIs(t, err, ErrMissingNuspecFile) + require.ErrorIs(t, err, ErrMissingNuspecFile) }) t.Run("InvalidNuspecFile", func(t *testing.T) { @@ -93,7 +94,7 @@ func TestParsePackageMetaData(t *testing.T) { np, err := ParsePackageMetaData(bytes.NewReader(data), int64(len(data))) assert.Nil(t, np) - assert.Error(t, err) + require.Error(t, err) }) t.Run("InvalidPackageId", func(t *testing.T) { @@ -104,7 +105,7 @@ func TestParsePackageMetaData(t *testing.T) { np, err := ParsePackageMetaData(bytes.NewReader(data), int64(len(data))) assert.Nil(t, np) - assert.ErrorIs(t, err, ErrNuspecInvalidID) + require.ErrorIs(t, err, ErrNuspecInvalidID) }) t.Run("InvalidPackageVersion", func(t *testing.T) { @@ -117,14 +118,14 @@ func TestParsePackageMetaData(t *testing.T) { np, err := ParsePackageMetaData(bytes.NewReader(data), int64(len(data))) assert.Nil(t, np) - assert.ErrorIs(t, err, ErrNuspecInvalidVersion) + require.ErrorIs(t, err, ErrNuspecInvalidVersion) }) t.Run("MissingReadme", func(t *testing.T) { data := createArchive(map[string]string{"package.nuspec": nuspecContent}) np, err := ParsePackageMetaData(bytes.NewReader(data), int64(len(data))) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, np) assert.Empty(t, np.Metadata.Readme) }) @@ -136,7 +137,7 @@ func TestParsePackageMetaData(t *testing.T) { }) np, err := ParsePackageMetaData(bytes.NewReader(data), int64(len(data))) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, np) assert.Equal(t, DependencyPackage, np.PackageType) @@ -165,7 +166,7 @@ func TestParsePackageMetaData(t *testing.T) { `}) np, err := ParsePackageMetaData(bytes.NewReader(data), int64(len(data))) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, np) assert.Equal(t, "1.4.5.2-rc.1", np.Version) }) @@ -175,7 +176,7 @@ func TestParsePackageMetaData(t *testing.T) { data := createArchive(map[string]string{"package.nuspec": symbolsNuspecContent}) np, err := ParsePackageMetaData(bytes.NewReader(data), int64(len(data))) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, np) assert.Equal(t, SymbolsPackage, np.PackageType) diff --git a/modules/packages/nuget/symbol_extractor_test.go b/modules/packages/nuget/symbol_extractor_test.go index fa1b80ee82..b767ed0387 100644 --- a/modules/packages/nuget/symbol_extractor_test.go +++ b/modules/packages/nuget/symbol_extractor_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const pdbContent = `QlNKQgEAAQAAAAAADAAAAFBEQiB2MS4wAAAAAAAABgB8AAAAWAAAACNQZGIAAAAA1AAAAAgBAAAj @@ -31,7 +32,7 @@ func TestExtractPortablePdb(t *testing.T) { zip.NewWriter(&buf).Close() pdbs, err := ExtractPortablePdb(bytes.NewReader(buf.Bytes()), int64(buf.Len())) - assert.ErrorIs(t, err, ErrMissingPdbFiles) + require.ErrorIs(t, err, ErrMissingPdbFiles) assert.Empty(t, pdbs) }) @@ -39,7 +40,7 @@ func TestExtractPortablePdb(t *testing.T) { data := createArchive("sub/test.bin", []byte{}) pdbs, err := ExtractPortablePdb(bytes.NewReader(data), int64(len(data))) - assert.ErrorIs(t, err, ErrInvalidFiles) + require.ErrorIs(t, err, ErrInvalidFiles) assert.Empty(t, pdbs) }) @@ -48,7 +49,7 @@ func TestExtractPortablePdb(t *testing.T) { data := createArchive("test.pdb", b) pdbs, err := ExtractPortablePdb(bytes.NewReader(data), int64(len(data))) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pdbs, 1) assert.Equal(t, "test.pdb", pdbs[0].Name) assert.Equal(t, "d910bb6948bd4c6cb40155bcf52c3c94", pdbs[0].ID) @@ -59,7 +60,7 @@ func TestExtractPortablePdb(t *testing.T) { func TestParseDebugHeaderID(t *testing.T) { t.Run("InvalidPdbMagicNumber", func(t *testing.T) { id, err := ParseDebugHeaderID(bytes.NewReader([]byte{0, 0, 0, 0})) - assert.ErrorIs(t, err, ErrInvalidPdbMagicNumber) + require.ErrorIs(t, err, ErrInvalidPdbMagicNumber) assert.Empty(t, id) }) @@ -67,7 +68,7 @@ func TestParseDebugHeaderID(t *testing.T) { b, _ := base64.StdEncoding.DecodeString(`QlNKQgEAAQAAAAAADAAAAFBEQiB2MS4wAAAAAAAAAQB8AAAAWAAAACNVUwA=`) id, err := ParseDebugHeaderID(bytes.NewReader(b)) - assert.ErrorIs(t, err, ErrMissingPdbStream) + require.ErrorIs(t, err, ErrMissingPdbStream) assert.Empty(t, id) }) @@ -75,7 +76,7 @@ func TestParseDebugHeaderID(t *testing.T) { b, _ := base64.StdEncoding.DecodeString(pdbContent) id, err := ParseDebugHeaderID(bytes.NewReader(b)) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "d910bb6948bd4c6cb40155bcf52c3c94", id) }) } diff --git a/modules/packages/pub/metadata_test.go b/modules/packages/pub/metadata_test.go index 8f9126e0c9..5ed083b952 100644 --- a/modules/packages/pub/metadata_test.go +++ b/modules/packages/pub/metadata_test.go @@ -12,6 +12,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -65,7 +66,7 @@ func TestParsePackage(t *testing.T) { pp, err := ParsePackage(data) assert.Nil(t, pp) - assert.ErrorIs(t, err, ErrMissingPubspecFile) + require.ErrorIs(t, err, ErrMissingPubspecFile) }) t.Run("PubspecFileTooLarge", func(t *testing.T) { @@ -73,7 +74,7 @@ func TestParsePackage(t *testing.T) { pp, err := ParsePackage(data) assert.Nil(t, pp) - assert.ErrorIs(t, err, ErrPubspecFileTooLarge) + require.ErrorIs(t, err, ErrPubspecFileTooLarge) }) t.Run("InvalidPubspecFile", func(t *testing.T) { @@ -81,14 +82,14 @@ func TestParsePackage(t *testing.T) { pp, err := ParsePackage(data) assert.Nil(t, pp) - assert.Error(t, err) + require.Error(t, err) }) t.Run("Valid", func(t *testing.T) { data := createArchive(map[string][]byte{"pubspec.yaml": []byte(pubspecContent)}) pp, err := ParsePackage(data) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pp) assert.Empty(t, pp.Metadata.Readme) }) @@ -97,7 +98,7 @@ func TestParsePackage(t *testing.T) { data := createArchive(map[string][]byte{"pubspec.yaml": []byte(pubspecContent), "README.md": []byte("readme")}) pp, err := ParsePackage(data) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pp) assert.Equal(t, "readme", pp.Metadata.Readme) }) @@ -108,7 +109,7 @@ func TestParsePubspecMetadata(t *testing.T) { for _, name := range []string{"123abc", "ab-cd"} { pp, err := ParsePubspecMetadata(strings.NewReader(`name: ` + name)) assert.Nil(t, pp) - assert.ErrorIs(t, err, ErrInvalidName) + require.ErrorIs(t, err, ErrInvalidName) } }) @@ -116,12 +117,12 @@ func TestParsePubspecMetadata(t *testing.T) { pp, err := ParsePubspecMetadata(strings.NewReader(`name: dummy version: invalid`)) assert.Nil(t, pp) - assert.ErrorIs(t, err, ErrInvalidVersion) + require.ErrorIs(t, err, ErrInvalidVersion) }) t.Run("Valid", func(t *testing.T) { pp, err := ParsePubspecMetadata(strings.NewReader(pubspecContent)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pp) assert.Equal(t, packageName, pp.Name) diff --git a/modules/packages/rpm/metadata_test.go b/modules/packages/rpm/metadata_test.go index bb538ef9d0..dc9b480723 100644 --- a/modules/packages/rpm/metadata_test.go +++ b/modules/packages/rpm/metadata_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParsePackage(t *testing.T) { @@ -42,14 +43,14 @@ Mu0UFYgZ/bYnuvn/vz4wtCz8qMwsHUvP0PX3tbYFUctAPdrY6tiiDtcCddDECahx7SuVNP5dpmb5 7tpp/pEjDS7cGPZ6BY430+7danDq6f42Nw49b9F7zp6BiKpJb9s5P0AYN2+L159cnrur636rx+v1 7ae1K28QbMMcqI8CqwIrgwg9nTOp8Oj9q81plUY7ZuwXN8Vvs8wbAAA=` rpmPackageContent, err := base64.StdEncoding.DecodeString(base64RpmPackageContent) - assert.NoError(t, err) + require.NoError(t, err) zr, err := gzip.NewReader(bytes.NewReader(rpmPackageContent)) - assert.NoError(t, err) + require.NoError(t, err) p, err := ParsePackage(zr) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "gitea-test", p.Name) assert.Equal(t, "1.0.2-1", p.Version) diff --git a/modules/packages/rubygems/marshal_test.go b/modules/packages/rubygems/marshal_test.go index 6d2354cd87..8aa9160e20 100644 --- a/modules/packages/rubygems/marshal_test.go +++ b/modules/packages/rubygems/marshal_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMinimalEncoder(t *testing.T) { @@ -92,7 +93,7 @@ func TestMinimalEncoder(t *testing.T) { for i, c := range cases { var b bytes.Buffer err := NewMarshalEncoder(&b).Encode(c.Value) - assert.ErrorIs(t, err, c.Error) + require.ErrorIs(t, err, c.Error) assert.Equal(t, c.Expected, b.Bytes(), "case %d", i) } } diff --git a/modules/packages/rubygems/metadata_test.go b/modules/packages/rubygems/metadata_test.go index ec2fa08b6b..cd3a5bbd10 100644 --- a/modules/packages/rubygems/metadata_test.go +++ b/modules/packages/rubygems/metadata_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestParsePackageMetaData(t *testing.T) { @@ -32,7 +33,7 @@ func TestParsePackageMetaData(t *testing.T) { data := createArchive("dummy.txt", []byte{0}) rp, err := ParsePackageMetaData(data) - assert.ErrorIs(t, err, ErrMissingMetadataFile) + require.ErrorIs(t, err, ErrMissingMetadataFile) assert.Nil(t, rp) }) @@ -41,7 +42,7 @@ func TestParsePackageMetaData(t *testing.T) { data := createArchive("metadata.gz", content) rp, err := ParsePackageMetaData(data) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, rp) }) } @@ -58,7 +59,7 @@ dVoR6hj07u0HZgAl3SRS8G/fmXcRK20jyq6rDMSYQFgidamqkXbbuspLXE/0k7GphtKqe67GuRC/ yjAbmt9LsOMp8xMamFkSQ38fP5EFjdz8LA4do2C69VvqWXAJgrPbKZb58/xZXrKoW6ttW13Bhvzi 4ftn7/yUxd4YGcglvTmmY8aGY3ZwRn4CqcWcidUGAAA=`) rp, err := parseMetadataFile(bytes.NewReader(content)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, rp) assert.Equal(t, "gitea", rp.Name) diff --git a/modules/packages/swift/metadata_test.go b/modules/packages/swift/metadata_test.go index 3913c2355b..b223d8c15f 100644 --- a/modules/packages/swift/metadata_test.go +++ b/modules/packages/swift/metadata_test.go @@ -11,6 +11,7 @@ import ( "github.com/hashicorp/go-version" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -39,7 +40,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data, data.Size(), nil) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrMissingManifestFile) + require.ErrorIs(t, err, ErrMissingManifestFile) }) t.Run("ManifestFileTooLarge", func(t *testing.T) { @@ -49,7 +50,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data, data.Size(), nil) assert.Nil(t, p) - assert.ErrorIs(t, err, ErrManifestFileTooLarge) + require.ErrorIs(t, err, ErrManifestFileTooLarge) }) t.Run("WithoutMetadata", func(t *testing.T) { @@ -63,7 +64,7 @@ func TestParsePackage(t *testing.T) { p, err := ParsePackage(data, data.Size(), nil) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, p.Metadata) assert.Empty(t, p.RepositoryURLs) @@ -87,7 +88,7 @@ func TestParsePackage(t *testing.T) { strings.NewReader(`{"name":"`+packageName+`","version":"`+packageVersion+`","description":"`+packageDescription+`","keywords":["swift","package"],"license":"`+packageLicense+`","codeRepository":"`+packageRepositoryURL+`","author":{"givenName":"`+packageAuthor+`"},"repositoryURLs":["`+packageRepositoryURL+`"]}`), ) assert.NotNil(t, p) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, p.Metadata) assert.Len(t, p.Metadata.Manifests, 1) diff --git a/modules/packages/vagrant/metadata_test.go b/modules/packages/vagrant/metadata_test.go index d616ffe3d3..f467781a08 100644 --- a/modules/packages/vagrant/metadata_test.go +++ b/modules/packages/vagrant/metadata_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/json" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -46,7 +47,7 @@ func TestParseMetadataFromBox(t *testing.T) { metadata, err := ParseMetadataFromBox(data) assert.NotNil(t, metadata) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("Valid", func(t *testing.T) { @@ -56,13 +57,13 @@ func TestParseMetadataFromBox(t *testing.T) { "website": projectURL, "repository": repositoryURL, }) - assert.NoError(t, err) + require.NoError(t, err) data := createArchive(map[string][]byte{"info.json": content}) metadata, err := ParseMetadataFromBox(data) assert.NotNil(t, metadata) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, author, metadata.Author) assert.Equal(t, description, metadata.Description) @@ -77,11 +78,11 @@ func TestParseInfoFile(t *testing.T) { "package": "", "dummy": "", }) - assert.NoError(t, err) + require.NoError(t, err) metadata, err := ParseInfoFile(bytes.NewReader(content)) assert.NotNil(t, metadata) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, metadata.Author) assert.Empty(t, metadata.Description) @@ -96,11 +97,11 @@ func TestParseInfoFile(t *testing.T) { "website": projectURL, "repository": repositoryURL, }) - assert.NoError(t, err) + require.NoError(t, err) metadata, err := ParseInfoFile(bytes.NewReader(content)) assert.NotNil(t, metadata) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, author, metadata.Author) assert.Equal(t, description, metadata.Description) diff --git a/modules/queue/base_levelqueue_test.go b/modules/queue/base_levelqueue_test.go index b881802ca2..b65b570c4b 100644 --- a/modules/queue/base_levelqueue_test.go +++ b/modules/queue/base_levelqueue_test.go @@ -11,15 +11,16 @@ import ( "gitea.com/lunny/levelqueue" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/syndtr/goleveldb/leveldb" ) func TestBaseLevelDB(t *testing.T) { _, err := newBaseLevelQueueGeneric(&BaseConfig{ConnStr: "redis://"}, false) - assert.ErrorContains(t, err, "invalid leveldb connection string") + require.ErrorContains(t, err, "invalid leveldb connection string") _, err = newBaseLevelQueueGeneric(&BaseConfig{DataFullDir: "relative"}, false) - assert.ErrorContains(t, err, "invalid leveldb data dir") + require.ErrorContains(t, err, "invalid leveldb data dir") testQueueBasic(t, newBaseLevelQueueSimple, toBaseConfig("baseLevelQueue", setting.QueueSettings{Datadir: t.TempDir() + "/queue-test", Length: 10}), false) testQueueBasic(t, newBaseLevelQueueUnique, toBaseConfig("baseLevelQueueUnique", setting.QueueSettings{ConnStr: "leveldb://" + t.TempDir() + "/queue-test", Length: 10}), true) @@ -29,22 +30,21 @@ func TestCorruptedLevelQueue(t *testing.T) { // sometimes the levelqueue could be in a corrupted state, this test is to make sure it can recover from it dbDir := t.TempDir() + "/levelqueue-test" db, err := leveldb.OpenFile(dbDir, nil) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer db.Close() - assert.NoError(t, db.Put([]byte("other-key"), []byte("other-value"), nil)) + require.NoError(t, db.Put([]byte("other-key"), []byte("other-value"), nil)) nameQueuePrefix := []byte("queue_name") nameSetPrefix := []byte("set_name") lq, err := levelqueue.NewUniqueQueue(db, nameQueuePrefix, nameSetPrefix, false) - assert.NoError(t, err) - assert.NoError(t, lq.RPush([]byte("item-1"))) + require.NoError(t, err) + require.NoError(t, lq.RPush([]byte("item-1"))) itemKey := lqinternal.QueueItemKeyBytes(nameQueuePrefix, 1) itemValue, err := db.Get(itemKey, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("item-1"), itemValue) // there should be 5 keys in db: queue low, queue high, 1 queue item, 1 set item, and "other-key" @@ -52,11 +52,11 @@ func TestCorruptedLevelQueue(t *testing.T) { assert.Len(t, keys, 5) // delete the queue item key, to corrupt the queue - assert.NoError(t, db.Delete(itemKey, nil)) + require.NoError(t, db.Delete(itemKey, nil)) // now the queue is corrupted, it never works again _, err = lq.LPop() - assert.ErrorIs(t, err, levelqueue.ErrNotFound) - assert.NoError(t, lq.Close()) + require.ErrorIs(t, err, levelqueue.ErrNotFound) + require.NoError(t, lq.Close()) // remove all the queue related keys to reset the queue lqinternal.RemoveLevelQueueKeys(db, nameQueuePrefix) @@ -68,11 +68,11 @@ func TestCorruptedLevelQueue(t *testing.T) { // re-create a queue from db lq, err = levelqueue.NewUniqueQueue(db, nameQueuePrefix, nameSetPrefix, false) - assert.NoError(t, err) - assert.NoError(t, lq.RPush([]byte("item-new-1"))) + require.NoError(t, err) + require.NoError(t, lq.RPush([]byte("item-new-1"))) // now the queue works again itemValue, err = lq.LPop() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("item-new-1"), itemValue) - assert.NoError(t, lq.Close()) + require.NoError(t, lq.Close()) } diff --git a/modules/queue/base_test.go b/modules/queue/base_test.go index c5bf526ae6..a5600fea63 100644 --- a/modules/queue/base_test.go +++ b/modules/queue/base_test.go @@ -10,89 +10,90 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testQueueBasic(t *testing.T, newFn func(cfg *BaseConfig) (baseQueue, error), cfg *BaseConfig, isUnique bool) { t.Run(fmt.Sprintf("testQueueBasic-%s-unique:%v", cfg.ManagedName, isUnique), func(t *testing.T) { q, err := newFn(cfg) - assert.NoError(t, err) + require.NoError(t, err) ctx := context.Background() _ = q.RemoveAll(ctx) cnt, err := q.Len(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, cnt) // push the first item err = q.PushItem(ctx, []byte("foo")) - assert.NoError(t, err) + require.NoError(t, err) cnt, err = q.Len(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, cnt) // push a duplicate item err = q.PushItem(ctx, []byte("foo")) if !isUnique { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.ErrorIs(t, err, ErrAlreadyInQueue) + require.ErrorIs(t, err, ErrAlreadyInQueue) } // check the duplicate item cnt, err = q.Len(ctx) - assert.NoError(t, err) + require.NoError(t, err) has, err := q.HasItem(ctx, []byte("foo")) - assert.NoError(t, err) + require.NoError(t, err) if !isUnique { assert.EqualValues(t, 2, cnt) - assert.EqualValues(t, false, has) // non-unique queues don't check for duplicates + assert.False(t, has) // non-unique queues don't check for duplicates } else { assert.EqualValues(t, 1, cnt) - assert.EqualValues(t, true, has) + assert.True(t, has) } // push another item err = q.PushItem(ctx, []byte("bar")) - assert.NoError(t, err) + require.NoError(t, err) // pop the first item (and the duplicate if non-unique) it, err := q.PopItem(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "foo", string(it)) if !isUnique { it, err = q.PopItem(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "foo", string(it)) } // pop another item it, err = q.PopItem(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "bar", string(it)) // pop an empty queue (timeout, cancel) ctxTimed, cancel := context.WithTimeout(ctx, 10*time.Millisecond) it, err = q.PopItem(ctxTimed) - assert.ErrorIs(t, err, context.DeadlineExceeded) + require.ErrorIs(t, err, context.DeadlineExceeded) assert.Nil(t, it) cancel() ctxTimed, cancel = context.WithTimeout(ctx, 10*time.Millisecond) cancel() it, err = q.PopItem(ctxTimed) - assert.ErrorIs(t, err, context.Canceled) + require.ErrorIs(t, err, context.Canceled) assert.Nil(t, it) // test blocking push if queue is full for i := 0; i < cfg.Length; i++ { err = q.PushItem(ctx, []byte(fmt.Sprintf("item-%d", i))) - assert.NoError(t, err) + require.NoError(t, err) } ctxTimed, cancel = context.WithTimeout(ctx, 10*time.Millisecond) err = q.PushItem(ctxTimed, []byte("item-full")) - assert.ErrorIs(t, err, context.DeadlineExceeded) + require.ErrorIs(t, err, context.DeadlineExceeded) cancel() // test blocking push if queue is full (with custom pushBlockTime) @@ -100,41 +101,41 @@ func testQueueBasic(t *testing.T, newFn func(cfg *BaseConfig) (baseQueue, error) timeStart := time.Now() pushBlockTime = 30 * time.Millisecond err = q.PushItem(ctx, []byte("item-full")) - assert.ErrorIs(t, err, context.DeadlineExceeded) - assert.True(t, time.Since(timeStart) >= pushBlockTime*2/3) + require.ErrorIs(t, err, context.DeadlineExceeded) + assert.GreaterOrEqual(t, time.Since(timeStart), pushBlockTime*2/3) pushBlockTime = oldPushBlockTime // remove all cnt, err = q.Len(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, cfg.Length, cnt) _ = q.RemoveAll(ctx) cnt, err = q.Len(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, cnt) }) } func TestBaseDummy(t *testing.T) { q, err := newBaseDummy(&BaseConfig{}, true) - assert.NoError(t, err) + require.NoError(t, err) ctx := context.Background() - assert.NoError(t, q.PushItem(ctx, []byte("foo"))) + require.NoError(t, q.PushItem(ctx, []byte("foo"))) cnt, err := q.Len(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, cnt) has, err := q.HasItem(ctx, []byte("foo")) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, has) it, err := q.PopItem(ctx) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, it) - assert.NoError(t, q.RemoveAll(ctx)) + require.NoError(t, q.RemoveAll(ctx)) } diff --git a/modules/queue/manager_test.go b/modules/queue/manager_test.go index 15dd1b4f2f..a76c238752 100644 --- a/modules/queue/manager_test.go +++ b/modules/queue/manager_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestManager(t *testing.T) { @@ -38,11 +39,11 @@ func TestManager(t *testing.T) { DATADIR = temp-dir CONN_STR = redis:// `) - assert.ErrorContains(t, err, "invalid leveldb connection string") + require.ErrorContains(t, err, "invalid leveldb connection string") // test default config q, err := newQueueFromConfig("default", "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "default", q.GetName()) assert.Equal(t, "level", q.GetType()) assert.Equal(t, filepath.Join(setting.AppDataPath, "queues/common"), q.baseConfig.DataFullDir) @@ -78,7 +79,7 @@ SET_NAME = _u2 MAX_WORKERS = 123 `) - assert.NoError(t, err) + require.NoError(t, err) q1 := createWorkerPoolQueue[string](context.Background(), "no-such", cfgProvider, nil, false) assert.Equal(t, "no-such", q1.GetName()) @@ -118,7 +119,7 @@ MAX_WORKERS = 123 assert.Equal(t, 120, q1.workerMaxNum) stop := runWorkerPoolQueue(q2) - assert.NoError(t, GetManager().GetManagedQueue(qid2).FlushWithContext(context.Background(), 0)) - assert.NoError(t, GetManager().FlushAll(context.Background(), 0)) + require.NoError(t, GetManager().GetManagedQueue(qid2).FlushWithContext(context.Background(), 0)) + require.NoError(t, GetManager().FlushAll(context.Background(), 0)) stop() } diff --git a/modules/queue/workerqueue_test.go b/modules/queue/workerqueue_test.go index 9898ceb873..112a16c8e3 100644 --- a/modules/queue/workerqueue_test.go +++ b/modules/queue/workerqueue_test.go @@ -57,9 +57,9 @@ func TestWorkerPoolQueueUnhandled(t *testing.T) { stop := runWorkerPoolQueue(q) for i := 0; i < queueSetting.Length; i++ { testRecorder.Record("push:%v", i) - assert.NoError(t, q.Push(i)) + require.NoError(t, q.Push(i)) } - assert.NoError(t, q.FlushWithContext(context.Background(), 0)) + require.NoError(t, q.FlushWithContext(context.Background(), 0)) stop() ok := true @@ -167,7 +167,7 @@ func testWorkerPoolQueuePersistence(t *testing.T, queueSetting setting.QueueSett q, _ := newWorkerPoolQueueForTest("pr_patch_checker_test", queueSetting, testHandler, true) stop := runWorkerPoolQueue(q) - assert.NoError(t, q.FlushWithContext(context.Background(), 0)) + require.NoError(t, q.FlushWithContext(context.Background(), 0)) stop() } @@ -189,7 +189,7 @@ func TestWorkerPoolQueueActiveWorkers(t *testing.T) { q, _ := newWorkerPoolQueueForTest("test-workpoolqueue", setting.QueueSettings{Type: "channel", BatchLength: 1, MaxWorkers: 1, Length: 100}, handler, false) stop := runWorkerPoolQueue(q) for i := 0; i < 5; i++ { - assert.NoError(t, q.Push(i)) + require.NoError(t, q.Push(i)) } time.Sleep(50 * time.Millisecond) @@ -205,7 +205,7 @@ func TestWorkerPoolQueueActiveWorkers(t *testing.T) { q, _ = newWorkerPoolQueueForTest("test-workpoolqueue", setting.QueueSettings{Type: "channel", BatchLength: 1, MaxWorkers: 3, Length: 100}, handler, false) stop = runWorkerPoolQueue(q) for i := 0; i < 15; i++ { - assert.NoError(t, q.Push(i)) + require.NoError(t, q.Push(i)) } time.Sleep(50 * time.Millisecond) @@ -238,7 +238,7 @@ func TestWorkerPoolQueueShutdown(t *testing.T) { q, _ := newWorkerPoolQueueForTest("test-workpoolqueue", qs, handler, false) stop := runWorkerPoolQueue(q) for i := 0; i < qs.Length; i++ { - assert.NoError(t, q.Push(i)) + require.NoError(t, q.Push(i)) } <-handlerCalled time.Sleep(200 * time.Millisecond) // wait for a while to make sure all workers are active @@ -266,7 +266,7 @@ func TestWorkerPoolQueueWorkerIdleReset(t *testing.T) { const workloadSize = 12 for i := 0; i < workloadSize; i++ { - assert.NoError(t, q.Push(i)) + require.NoError(t, q.Push(i)) } workerIDs := make(map[string]struct{}) diff --git a/modules/references/references_test.go b/modules/references/references_test.go index 498374b2a7..ffa7f993e3 100644 --- a/modules/references/references_test.go +++ b/modules/references/references_test.go @@ -529,7 +529,7 @@ func TestCustomizeCloseKeywords(t *testing.T) { func TestParseCloseKeywords(t *testing.T) { // Test parsing of CloseKeywords and ReopenKeywords - assert.Len(t, parseKeywords([]string{""}), 0) + assert.Empty(t, parseKeywords([]string{""})) assert.Len(t, parseKeywords([]string{" aa ", " bb ", "99", "#", "", "this is", "cc"}), 3) for _, test := range []struct { diff --git a/modules/regexplru/regexplru_test.go b/modules/regexplru/regexplru_test.go index 9c24b23fa9..8c0c722336 100644 --- a/modules/regexplru/regexplru_test.go +++ b/modules/regexplru/regexplru_test.go @@ -7,20 +7,21 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRegexpLru(t *testing.T) { r, err := GetCompiled("a") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, r.MatchString("a")) r, err = GetCompiled("a") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, r.MatchString("a")) assert.EqualValues(t, 1, lruCache.Len()) _, err = GetCompiled("(") - assert.Error(t, err) + require.Error(t, err) assert.EqualValues(t, 2, lruCache.Len()) } diff --git a/modules/repository/branch_test.go b/modules/repository/branch_test.go index acf75a1ac0..b98618a16b 100644 --- a/modules/repository/branch_test.go +++ b/modules/repository/branch_test.go @@ -12,20 +12,21 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSyncRepoBranches(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) _, err := db.GetEngine(db.DefaultContext).ID(1).Update(&repo_model.Repository{ObjectFormatName: "bad-fmt"}) - assert.NoError(t, db.TruncateBeans(db.DefaultContext, &git_model.Branch{})) - assert.NoError(t, err) + require.NoError(t, db.TruncateBeans(db.DefaultContext, &git_model.Branch{})) + require.NoError(t, err) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) assert.Equal(t, "bad-fmt", repo.ObjectFormatName) _, err = SyncRepoBranches(db.DefaultContext, 1, 0) - assert.NoError(t, err) + require.NoError(t, err) repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) assert.Equal(t, "sha1", repo.ObjectFormatName) branch, err := git_model.GetBranch(db.DefaultContext, 1, "master") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "master", branch.Name) } diff --git a/modules/repository/collaborator_test.go b/modules/repository/collaborator_test.go index e623dbdaa4..3844197bf1 100644 --- a/modules/repository/collaborator_test.go +++ b/modules/repository/collaborator_test.go @@ -16,16 +16,17 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_AddCollaborator(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(repoID, userID int64) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) - assert.NoError(t, repo.LoadOwner(db.DefaultContext)) + require.NoError(t, repo.LoadOwner(db.DefaultContext)) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID}) - assert.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) + require.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}, &user_model.User{ID: userID}) } testSuccess(1, 4) @@ -34,23 +35,23 @@ func TestRepository_AddCollaborator(t *testing.T) { } func TestRepository_AddCollaborator_IsBlocked(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(repoID, userID int64) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) - assert.NoError(t, repo.LoadOwner(db.DefaultContext)) + require.NoError(t, repo.LoadOwner(db.DefaultContext)) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID}) // Owner blocked user. unittest.AssertSuccessfulInsert(t, &user_model.BlockedUser{UserID: repo.OwnerID, BlockID: userID}) - assert.ErrorIs(t, AddCollaborator(db.DefaultContext, repo, user), user_model.ErrBlockedByUser) + require.ErrorIs(t, AddCollaborator(db.DefaultContext, repo, user), user_model.ErrBlockedByUser) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}, &user_model.User{ID: userID}) _, err := db.DeleteByBean(db.DefaultContext, &user_model.BlockedUser{UserID: repo.OwnerID, BlockID: userID}) - assert.NoError(t, err) + require.NoError(t, err) // User has owner blocked. unittest.AssertSuccessfulInsert(t, &user_model.BlockedUser{UserID: userID, BlockID: repo.OwnerID}) - assert.ErrorIs(t, AddCollaborator(db.DefaultContext, repo, user), user_model.ErrBlockedByUser) + require.ErrorIs(t, AddCollaborator(db.DefaultContext, repo, user), user_model.ErrBlockedByUser) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}, &user_model.User{ID: userID}) } // Ensure idempotency (public repository). @@ -61,25 +62,25 @@ func TestRepository_AddCollaborator_IsBlocked(t *testing.T) { } func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // public non-organization repo repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) - assert.NoError(t, repo.LoadUnits(db.DefaultContext)) + require.NoError(t, repo.LoadUnits(db.DefaultContext)) // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) perm, err := access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.False(t, perm.CanWrite(unit.Type)) } // change to collaborator - assert.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) + require.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) @@ -88,7 +89,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { // collaborator collaborator := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, collaborator) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) @@ -97,7 +98,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { // owner owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, owner) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) @@ -106,7 +107,7 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { // admin admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, admin) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) @@ -114,33 +115,33 @@ func TestRepoPermissionPublicNonOrgRepo(t *testing.T) { } func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // private non-organization repo repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - assert.NoError(t, repo.LoadUnits(db.DefaultContext)) + require.NoError(t, repo.LoadUnits(db.DefaultContext)) // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4}) perm, err := access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.False(t, perm.CanRead(unit.Type)) assert.False(t, perm.CanWrite(unit.Type)) } // change to collaborator to default write access - assert.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) + require.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) } - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, user.ID, perm_model.AccessModeRead)) + require.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, user.ID, perm_model.AccessModeRead)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.False(t, perm.CanWrite(unit.Type)) @@ -149,7 +150,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { // owner owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, owner) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) @@ -158,7 +159,7 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { // admin admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, admin) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) @@ -166,33 +167,33 @@ func TestRepoPermissionPrivateNonOrgRepo(t *testing.T) { } func TestRepoPermissionPublicOrgRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // public organization repo repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 32}) - assert.NoError(t, repo.LoadUnits(db.DefaultContext)) + require.NoError(t, repo.LoadUnits(db.DefaultContext)) // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) perm, err := access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.False(t, perm.CanWrite(unit.Type)) } // change to collaborator to default write access - assert.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) + require.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) } - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, user.ID, perm_model.AccessModeRead)) + require.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, user.ID, perm_model.AccessModeRead)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.False(t, perm.CanWrite(unit.Type)) @@ -201,7 +202,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { // org member team owner owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, owner) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) @@ -210,7 +211,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { // org member team tester member := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 15}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, member) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) } @@ -220,7 +221,7 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { // admin admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, admin) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) @@ -228,33 +229,33 @@ func TestRepoPermissionPublicOrgRepo(t *testing.T) { } func TestRepoPermissionPrivateOrgRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // private organization repo repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 24}) - assert.NoError(t, repo.LoadUnits(db.DefaultContext)) + require.NoError(t, repo.LoadUnits(db.DefaultContext)) // plain user user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) perm, err := access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.False(t, perm.CanRead(unit.Type)) assert.False(t, perm.CanWrite(unit.Type)) } // change to collaborator to default write access - assert.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) + require.NoError(t, AddCollaborator(db.DefaultContext, repo, user)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) } - assert.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, user.ID, perm_model.AccessModeRead)) + require.NoError(t, repo_model.ChangeCollaborationAccessMode(db.DefaultContext, repo, user.ID, perm_model.AccessModeRead)) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, user) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.False(t, perm.CanWrite(unit.Type)) @@ -263,7 +264,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // org member team owner owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 15}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, owner) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) @@ -272,9 +273,9 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // update team information and then check permission team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 5}) err = organization.UpdateTeamUnits(db.DefaultContext, team, nil) - assert.NoError(t, err) + require.NoError(t, err) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, owner) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) @@ -283,7 +284,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // org member team tester tester := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, tester) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, perm.CanWrite(unit.TypeIssues)) assert.False(t, perm.CanWrite(unit.TypeCode)) assert.False(t, perm.CanRead(unit.TypeCode)) @@ -291,7 +292,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // org member team reviewer reviewer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 20}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, reviewer) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, perm.CanRead(unit.TypeIssues)) assert.False(t, perm.CanWrite(unit.TypeCode)) assert.True(t, perm.CanRead(unit.TypeCode)) @@ -299,7 +300,7 @@ func TestRepoPermissionPrivateOrgRepo(t *testing.T) { // admin admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) perm, err = access_model.GetUserRepoPermission(db.DefaultContext, repo, admin) - assert.NoError(t, err) + require.NoError(t, err) for _, unit := range repo.Units { assert.True(t, perm.CanRead(unit.Type)) assert.True(t, perm.CanWrite(unit.Type)) diff --git a/modules/repository/commits_test.go b/modules/repository/commits_test.go index 248673a907..82841b3268 100644 --- a/modules/repository/commits_test.go +++ b/modules/repository/commits_test.go @@ -17,10 +17,11 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPushCommits_ToAPIPayloadCommits(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pushCommits := NewPushCommits() pushCommits.Commits = []*PushCommit{ @@ -53,7 +54,7 @@ func TestPushCommits_ToAPIPayloadCommits(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 16}) payloadCommits, headCommit, err := pushCommits.ToAPIPayloadCommits(git.DefaultContext, repo.RepoPath(), "/user2/repo16") - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, payloadCommits, 3) assert.NotNil(t, headCommit) @@ -103,7 +104,7 @@ func TestPushCommits_ToAPIPayloadCommits(t *testing.T) { } func TestPushCommits_AvatarLink(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pushCommits := NewPushCommits() pushCommits.Commits = []*PushCommit{ @@ -146,7 +147,7 @@ func TestCommitToPushCommit(t *testing.T) { } const hexString = "0123456789abcdef0123456789abcdef01234567" sha1, err := git.NewIDFromString(hexString) - assert.NoError(t, err) + require.NoError(t, err) pushCommit := CommitToPushCommit(&git.Commit{ ID: sha1, Author: sig, @@ -172,10 +173,10 @@ func TestListToPushCommits(t *testing.T) { const hexString1 = "0123456789abcdef0123456789abcdef01234567" hash1, err := git.NewIDFromString(hexString1) - assert.NoError(t, err) + require.NoError(t, err) const hexString2 = "fedcba9876543210fedcba9876543210fedcba98" hash2, err := git.NewIDFromString(hexString2) - assert.NoError(t, err) + require.NoError(t, err) l := []*git.Commit{ { diff --git a/modules/repository/create_test.go b/modules/repository/create_test.go index 6a2f4deaff..c743271c26 100644 --- a/modules/repository/create_test.go +++ b/modules/repository/create_test.go @@ -12,34 +12,35 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUpdateRepositoryVisibilityChanged(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // Get sample repo and change visibility repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 9) - assert.NoError(t, err) + require.NoError(t, err) repo.IsPrivate = true // Update it err = UpdateRepository(db.DefaultContext, repo, true) - assert.NoError(t, err) + require.NoError(t, err) // Check visibility of action has become private act := activities_model.Action{} _, err = db.GetEngine(db.DefaultContext).ID(3).Get(&act) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, act.IsPrivate) } func TestGetDirectorySize(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) size, err := getDirectorySize(repo.RepoPath()) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, size, repo.Size) } diff --git a/modules/repository/license_test.go b/modules/repository/license_test.go index 3b0cfa1eed..a7d77743ac 100644 --- a/modules/repository/license_test.go +++ b/modules/repository/license_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_getLicense(t *testing.T) { @@ -19,7 +20,7 @@ func Test_getLicense(t *testing.T) { name string args args want string - wantErr assert.ErrorAssertionFunc + wantErr require.ErrorAssertionFunc }{ { name: "regular", @@ -37,22 +38,21 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. `, - wantErr: assert.NoError, + wantErr: require.NoError, }, { name: "license not found", args: args{ name: "notfound", }, - wantErr: assert.Error, + wantErr: require.Error, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { got, err := GetLicense(tt.args.name, tt.args.values) - if !tt.wantErr(t, err, fmt.Sprintf("GetLicense(%v, %v)", tt.args.name, tt.args.values)) { - return - } + tt.wantErr(t, err, fmt.Sprintf("GetLicense(%v, %v)", tt.args.name, tt.args.values)) + assert.Equalf(t, tt.want, string(got), "GetLicense(%v, %v)", tt.args.name, tt.args.values) }) } diff --git a/modules/repository/repo_test.go b/modules/repository/repo_test.go index 68980f92f9..f3e7be6d7d 100644 --- a/modules/repository/repo_test.go +++ b/modules/repository/repo_test.go @@ -62,15 +62,15 @@ func Test_calcSync(t *testing.T) { } inserts, deletes, updates := calcSync(gitTags, dbReleases) - if assert.EqualValues(t, 1, len(inserts), "inserts") { + if assert.Len(t, inserts, 1, "inserts") { assert.EqualValues(t, *gitTags[2], *inserts[0], "inserts equal") } - if assert.EqualValues(t, 1, len(deletes), "deletes") { + if assert.Len(t, deletes, 1, "deletes") { assert.EqualValues(t, 1, deletes[0], "deletes equal") } - if assert.EqualValues(t, 1, len(updates), "updates") { + if assert.Len(t, updates, 1, "updates") { assert.EqualValues(t, *gitTags[1], *updates[0], "updates equal") } } diff --git a/modules/secret/secret_test.go b/modules/secret/secret_test.go index d4fb46955b..ba23718fd0 100644 --- a/modules/secret/secret_test.go +++ b/modules/secret/secret_test.go @@ -7,25 +7,26 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestEncryptDecrypt(t *testing.T) { hex, err := EncryptSecret("foo", "baz") - assert.NoError(t, err) + require.NoError(t, err) str, _ := DecryptSecret("foo", hex) assert.Equal(t, "baz", str) hex, err = EncryptSecret("bar", "baz") - assert.NoError(t, err) + require.NoError(t, err) str, _ = DecryptSecret("foo", hex) assert.NotEqual(t, "baz", str) _, err = DecryptSecret("a", "b") - assert.ErrorContains(t, err, "invalid hex string") + require.ErrorContains(t, err, "invalid hex string") _, err = DecryptSecret("a", "bb") - assert.ErrorContains(t, err, "the key (maybe SECRET_KEY?) might be incorrect: AesDecrypt ciphertext too short") + require.ErrorContains(t, err, "the key (maybe SECRET_KEY?) might be incorrect: AesDecrypt ciphertext too short") _, err = DecryptSecret("a", "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") - assert.ErrorContains(t, err, "the key (maybe SECRET_KEY?) might be incorrect: AesDecrypt invalid decrypted base64 string") + require.ErrorContains(t, err, "the key (maybe SECRET_KEY?) might be incorrect: AesDecrypt invalid decrypted base64 string") } diff --git a/modules/setting/actions_test.go b/modules/setting/actions_test.go index 01f5bf74a5..afd76d3bee 100644 --- a/modules/setting/actions_test.go +++ b/modules/setting/actions_test.go @@ -17,8 +17,8 @@ func Test_getStorageInheritNameSectionTypeForActions(t *testing.T) { STORAGE_TYPE = minio ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadActionsFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadActionsFrom(cfg)) assert.EqualValues(t, "minio", Actions.LogStorage.Type) assert.EqualValues(t, "actions_log/", Actions.LogStorage.MinioConfig.BasePath) @@ -30,8 +30,8 @@ func Test_getStorageInheritNameSectionTypeForActions(t *testing.T) { STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadActionsFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadActionsFrom(cfg)) assert.EqualValues(t, "minio", Actions.LogStorage.Type) assert.EqualValues(t, "actions_log/", Actions.LogStorage.MinioConfig.BasePath) @@ -46,8 +46,8 @@ STORAGE_TYPE = my_storage STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadActionsFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadActionsFrom(cfg)) assert.EqualValues(t, "minio", Actions.LogStorage.Type) assert.EqualValues(t, "actions_log/", Actions.LogStorage.MinioConfig.BasePath) @@ -62,8 +62,8 @@ STORAGE_TYPE = my_storage STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadActionsFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadActionsFrom(cfg)) assert.EqualValues(t, "local", Actions.LogStorage.Type) assert.EqualValues(t, "actions_log", filepath.Base(Actions.LogStorage.Path)) @@ -78,8 +78,8 @@ STORAGE_TYPE = my_storage STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadActionsFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadActionsFrom(cfg)) assert.EqualValues(t, "local", Actions.LogStorage.Type) assert.EqualValues(t, "actions_log", filepath.Base(Actions.LogStorage.Path)) @@ -88,8 +88,8 @@ STORAGE_TYPE = minio iniStr = `` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadActionsFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadActionsFrom(cfg)) assert.EqualValues(t, "local", Actions.LogStorage.Type) assert.EqualValues(t, "actions_log", filepath.Base(Actions.LogStorage.Path)) @@ -149,9 +149,8 @@ DEFAULT_ACTIONS_URL = https://example.com t.Run(tt.name, func(t *testing.T) { cfg, err := NewConfigProviderFromData(tt.iniStr) require.NoError(t, err) - if !assert.NoError(t, loadActionsFrom(cfg)) { - return - } + require.NoError(t, loadActionsFrom(cfg)) + assert.EqualValues(t, tt.wantURL, Actions.DefaultActionsURL.URL()) }) } diff --git a/modules/setting/admin_test.go b/modules/setting/admin_test.go index c0b4dfff69..0c6c24b038 100644 --- a/modules/setting/admin_test.go +++ b/modules/setting/admin_test.go @@ -9,6 +9,7 @@ import ( "code.gitea.io/gitea/modules/container" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_loadAdminFrom(t *testing.T) { @@ -21,12 +22,12 @@ func Test_loadAdminFrom(t *testing.T) { EXTERNAL_USER_DISABLE_FEATURES = x,y ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) loadAdminFrom(cfg) - assert.EqualValues(t, true, Admin.DisableRegularOrgCreation) + assert.True(t, Admin.DisableRegularOrgCreation) assert.EqualValues(t, "z", Admin.DefaultEmailNotification) - assert.EqualValues(t, true, Admin.SendNotificationEmailOnNewUser) + assert.True(t, Admin.SendNotificationEmailOnNewUser) assert.EqualValues(t, container.SetOf("a", "b"), Admin.UserDisabledFeatures) assert.EqualValues(t, container.SetOf("x", "y"), Admin.ExternalUserDisableFeatures) } diff --git a/modules/setting/attachment_test.go b/modules/setting/attachment_test.go index 3e8d2da4d9..f8085c1657 100644 --- a/modules/setting/attachment_test.go +++ b/modules/setting/attachment_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_getStorageCustomType(t *testing.T) { @@ -20,9 +21,9 @@ STORAGE_TYPE = minio MINIO_ENDPOINT = my_minio:9000 ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadAttachmentFrom(cfg)) + require.NoError(t, loadAttachmentFrom(cfg)) assert.EqualValues(t, "minio", Attachment.Storage.Type) assert.EqualValues(t, "my_minio:9000", Attachment.Storage.MinioConfig.Endpoint) @@ -42,9 +43,9 @@ MINIO_BUCKET = gitea-minio MINIO_BUCKET = gitea ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadAttachmentFrom(cfg)) + require.NoError(t, loadAttachmentFrom(cfg)) assert.EqualValues(t, "minio", Attachment.Storage.Type) assert.EqualValues(t, "gitea-minio", Attachment.Storage.MinioConfig.Bucket) @@ -64,9 +65,9 @@ MINIO_BUCKET = gitea STORAGE_TYPE = local ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadAttachmentFrom(cfg)) + require.NoError(t, loadAttachmentFrom(cfg)) assert.EqualValues(t, "minio", Attachment.Storage.Type) assert.EqualValues(t, "gitea-attachment", Attachment.Storage.MinioConfig.Bucket) @@ -75,9 +76,9 @@ STORAGE_TYPE = local func Test_getStorageGetDefaults(t *testing.T) { cfg, err := NewConfigProviderFromData("") - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadAttachmentFrom(cfg)) + require.NoError(t, loadAttachmentFrom(cfg)) // default storage is local, so bucket is empty assert.EqualValues(t, "", Attachment.Storage.MinioConfig.Bucket) @@ -89,9 +90,9 @@ func Test_getStorageInheritNameSectionType(t *testing.T) { STORAGE_TYPE = minio ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadAttachmentFrom(cfg)) + require.NoError(t, loadAttachmentFrom(cfg)) assert.EqualValues(t, "minio", Attachment.Storage.Type) } @@ -109,9 +110,9 @@ MINIO_ACCESS_KEY_ID = correct_key MINIO_SECRET_ACCESS_KEY = correct_key ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadAttachmentFrom(cfg)) + require.NoError(t, loadAttachmentFrom(cfg)) storage := Attachment.Storage assert.EqualValues(t, "minio", storage.Type) @@ -124,9 +125,9 @@ func Test_AttachmentStorage1(t *testing.T) { STORAGE_TYPE = minio ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadAttachmentFrom(cfg)) + require.NoError(t, loadAttachmentFrom(cfg)) assert.EqualValues(t, "minio", Attachment.Storage.Type) assert.EqualValues(t, "gitea", Attachment.Storage.MinioConfig.Bucket) assert.EqualValues(t, "attachments/", Attachment.Storage.MinioConfig.BasePath) diff --git a/modules/setting/config_env_test.go b/modules/setting/config_env_test.go index 572486aec2..bec3e584ef 100644 --- a/modules/setting/config_env_test.go +++ b/modules/setting/config_env_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDecodeEnvSectionKey(t *testing.T) { @@ -92,7 +93,7 @@ func TestEnvironmentToConfig(t *testing.T) { [sec] key = old `) - assert.NoError(t, err) + require.NoError(t, err) changed = EnvironmentToConfig(cfg, []string{"GITEA__sec__key=new"}) assert.True(t, changed) @@ -130,7 +131,7 @@ func TestEnvironmentToConfigSubSecKey(t *testing.T) { [sec] key = some `) - assert.NoError(t, err) + require.NoError(t, err) changed := EnvironmentToConfig(cfg, []string{"GITEA__sec_0X2E_sub__key=some"}) assert.True(t, changed) @@ -138,9 +139,9 @@ key = some tmpFile := t.TempDir() + "/test-sub-sec-key.ini" defer os.Remove(tmpFile) err = cfg.SaveTo(tmpFile) - assert.NoError(t, err) + require.NoError(t, err) bs, err := os.ReadFile(tmpFile) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, `[sec] key = some diff --git a/modules/setting/config_provider_test.go b/modules/setting/config_provider_test.go index a666d124c7..702be80861 100644 --- a/modules/setting/config_provider_test.go +++ b/modules/setting/config_provider_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestConfigProviderBehaviors(t *testing.T) { @@ -78,38 +79,38 @@ key = 123 func TestNewConfigProviderFromFile(t *testing.T) { cfg, err := NewConfigProviderFromFile("no-such.ini") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, cfg.IsLoadedFromEmpty()) // load non-existing file and save testFile := t.TempDir() + "/test.ini" testFile1 := t.TempDir() + "/test1.ini" cfg, err = NewConfigProviderFromFile(testFile) - assert.NoError(t, err) + require.NoError(t, err) sec, _ := cfg.NewSection("foo") _, _ = sec.NewKey("k1", "a") - assert.NoError(t, cfg.Save()) + require.NoError(t, cfg.Save()) _, _ = sec.NewKey("k2", "b") - assert.NoError(t, cfg.SaveTo(testFile1)) + require.NoError(t, cfg.SaveTo(testFile1)) bs, err := os.ReadFile(testFile) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "[foo]\nk1 = a\n", string(bs)) bs, err = os.ReadFile(testFile1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "[foo]\nk1 = a\nk2 = b\n", string(bs)) // load existing file and save cfg, err = NewConfigProviderFromFile(testFile) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "a", cfg.Section("foo").Key("k1").String()) sec, _ = cfg.NewSection("bar") _, _ = sec.NewKey("k1", "b") - assert.NoError(t, cfg.Save()) + require.NoError(t, cfg.Save()) bs, err = os.ReadFile(testFile) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "[foo]\nk1 = a\n\n[bar]\nk1 = b\n", string(bs)) } @@ -118,15 +119,15 @@ func TestNewConfigProviderForLocale(t *testing.T) { localeFile := t.TempDir() + "/locale.ini" _ = os.WriteFile(localeFile, []byte(`k1=a`), 0o644) cfg, err := NewConfigProviderForLocale(localeFile) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "a", cfg.Section("").Key("k1").String()) // load locale from bytes cfg, err = NewConfigProviderForLocale([]byte("k1=foo\nk2=bar")) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "foo", cfg.Section("").Key("k1").String()) cfg, err = NewConfigProviderForLocale([]byte("k1=foo\nk2=bar"), []byte("k2=xxx")) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "foo", cfg.Section("").Key("k1").String()) assert.Equal(t, "xxx", cfg.Section("").Key("k2").String()) } @@ -135,22 +136,22 @@ func TestDisableSaving(t *testing.T) { testFile := t.TempDir() + "/test.ini" _ = os.WriteFile(testFile, []byte("k1=a\nk2=b"), 0o644) cfg, err := NewConfigProviderFromFile(testFile) - assert.NoError(t, err) + require.NoError(t, err) cfg.DisableSaving() err = cfg.Save() - assert.ErrorIs(t, err, errDisableSaving) + require.ErrorIs(t, err, errDisableSaving) saveCfg, err := cfg.PrepareSaving() - assert.NoError(t, err) + require.NoError(t, err) saveCfg.Section("").Key("k1").MustString("x") saveCfg.Section("").Key("k2").SetValue("y") saveCfg.Section("").Key("k3").SetValue("z") err = saveCfg.Save() - assert.NoError(t, err) + require.NoError(t, err) bs, err := os.ReadFile(testFile) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "k1 = a\nk2 = y\nk3 = z\n", string(bs)) } diff --git a/modules/setting/cron_test.go b/modules/setting/cron_test.go index 3187ab18a2..32f8ecffd2 100644 --- a/modules/setting/cron_test.go +++ b/modules/setting/cron_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_getCronSettings(t *testing.T) { @@ -27,7 +28,7 @@ SECOND = white rabbit EXTEND = true ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) extended := &Extended{ BaseStruct: BaseStruct{ @@ -36,8 +37,8 @@ EXTEND = true } _, err = getCronSettings(cfg, "test", extended) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, extended.Base) - assert.EqualValues(t, extended.Second, "white rabbit") + assert.EqualValues(t, "white rabbit", extended.Second) assert.True(t, extended.Extend) } diff --git a/modules/setting/forgejo_storage_test.go b/modules/setting/forgejo_storage_test.go index 9071067cde..d91bff59e9 100644 --- a/modules/setting/forgejo_storage_test.go +++ b/modules/setting/forgejo_storage_test.go @@ -14,6 +14,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestForgejoDocs_StorageTypes(t *testing.T) { @@ -256,8 +257,8 @@ STORAGE_TYPE = %s func testStoragePathMatch(t *testing.T, iniStr string, storageType StorageType, testSectionToPath testSectionToPathFun, section string, storage **Storage) { cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err, iniStr) - assert.NoError(t, loadCommonSettingsFrom(cfg), iniStr) + require.NoError(t, err, iniStr) + require.NoError(t, loadCommonSettingsFrom(cfg), iniStr) assert.EqualValues(t, testSectionToPath(storageType, section), testStorageGetPath(*storage), iniStr) assert.EqualValues(t, storageType, (*storage).Type, iniStr) } diff --git a/modules/setting/git_test.go b/modules/setting/git_test.go index 441c514d8c..34427f908f 100644 --- a/modules/setting/git_test.go +++ b/modules/setting/git_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGitConfig(t *testing.T) { @@ -21,7 +22,7 @@ func TestGitConfig(t *testing.T) { [git.config] a.b = 1 `) - assert.NoError(t, err) + require.NoError(t, err) loadGitFrom(cfg) assert.EqualValues(t, "1", GitConfig.Options["a.b"]) assert.EqualValues(t, "histogram", GitConfig.Options["diff.algorithm"]) @@ -30,7 +31,7 @@ a.b = 1 [git.config] diff.algorithm = other `) - assert.NoError(t, err) + require.NoError(t, err) loadGitFrom(cfg) assert.EqualValues(t, "other", GitConfig.Options["diff.algorithm"]) } @@ -45,7 +46,7 @@ func TestGitReflog(t *testing.T) { // default reflog config without legacy options cfg, err := NewConfigProviderFromData(``) - assert.NoError(t, err) + require.NoError(t, err) loadGitFrom(cfg) assert.EqualValues(t, "true", GitConfig.GetOption("core.logAllRefUpdates")) @@ -57,7 +58,7 @@ func TestGitReflog(t *testing.T) { ENABLED = false EXPIRATION = 123 `) - assert.NoError(t, err) + require.NoError(t, err) loadGitFrom(cfg) assert.EqualValues(t, "false", GitConfig.GetOption("core.logAllRefUpdates")) diff --git a/modules/setting/lfs_test.go b/modules/setting/lfs_test.go index 10c54fec0a..c7f16379b2 100644 --- a/modules/setting/lfs_test.go +++ b/modules/setting/lfs_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_getStorageInheritNameSectionTypeForLFS(t *testing.T) { @@ -15,8 +16,8 @@ func Test_getStorageInheritNameSectionTypeForLFS(t *testing.T) { STORAGE_TYPE = minio ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "minio", LFS.Storage.Type) assert.EqualValues(t, "lfs/", LFS.Storage.MinioConfig.BasePath) @@ -28,8 +29,8 @@ LFS_CONTENT_PATH = path_ignored PATH = path_used ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "local", LFS.Storage.Type) assert.Contains(t, LFS.Storage.Path, "path_used") @@ -39,8 +40,8 @@ PATH = path_used LFS_CONTENT_PATH = deprecatedpath ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "local", LFS.Storage.Type) assert.Contains(t, LFS.Storage.Path, "deprecatedpath") @@ -50,8 +51,8 @@ LFS_CONTENT_PATH = deprecatedpath STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "minio", LFS.Storage.Type) assert.EqualValues(t, "lfs/", LFS.Storage.MinioConfig.BasePath) @@ -64,8 +65,8 @@ STORAGE_TYPE = my_minio STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "minio", LFS.Storage.Type) assert.EqualValues(t, "lfs/", LFS.Storage.MinioConfig.BasePath) @@ -79,8 +80,8 @@ MINIO_BASE_PATH = my_lfs/ STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "minio", LFS.Storage.Type) assert.EqualValues(t, "my_lfs/", LFS.Storage.MinioConfig.BasePath) @@ -92,9 +93,9 @@ func Test_LFSStorage1(t *testing.T) { STORAGE_TYPE = minio ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "minio", LFS.Storage.Type) assert.EqualValues(t, "gitea", LFS.Storage.MinioConfig.Bucket) assert.EqualValues(t, "lfs/", LFS.Storage.MinioConfig.BasePath) diff --git a/modules/setting/log_test.go b/modules/setting/log_test.go index 87b14f0b1d..3134d3e75c 100644 --- a/modules/setting/log_test.go +++ b/modules/setting/log_test.go @@ -11,7 +11,6 @@ import ( "code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/log" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -23,7 +22,7 @@ func initLoggersByConfig(t *testing.T, config string) (*log.LoggerManager, func( }() cfg, err := NewConfigProviderFromData(config) - assert.NoError(t, err) + require.NoError(t, err) manager := log.NewManager() initManagedLoggers(manager, cfg) diff --git a/modules/setting/oauth2_test.go b/modules/setting/oauth2_test.go index 1951c4c0a2..18252b2447 100644 --- a/modules/setting/oauth2_test.go +++ b/modules/setting/oauth2_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetGeneralSigningSecret(t *testing.T) { @@ -55,6 +56,6 @@ func TestGetGeneralSigningSecretSave(t *testing.T) { assert.Equal(t, generated, again) iniContent, err := os.ReadFile(tmpFile) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, string(iniContent), "JWT_SECRET = ") } diff --git a/modules/setting/packages_test.go b/modules/setting/packages_test.go index 87de276041..78eb4b4bbc 100644 --- a/modules/setting/packages_test.go +++ b/modules/setting/packages_test.go @@ -7,12 +7,13 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMustBytes(t *testing.T) { test := func(value string) int64 { cfg, err := NewConfigProviderFromData("[test]") - assert.NoError(t, err) + require.NoError(t, err) sec := cfg.Section("test") sec.NewKey("VALUE", value) @@ -37,8 +38,8 @@ func Test_getStorageInheritNameSectionTypeForPackages(t *testing.T) { STORAGE_TYPE = minio ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadPackagesFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadPackagesFrom(cfg)) assert.EqualValues(t, "minio", Packages.Storage.Type) assert.EqualValues(t, "packages/", Packages.Storage.MinioConfig.BasePath) @@ -49,8 +50,8 @@ STORAGE_TYPE = minio STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadPackagesFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadPackagesFrom(cfg)) assert.EqualValues(t, "minio", Packages.Storage.Type) assert.EqualValues(t, "packages/", Packages.Storage.MinioConfig.BasePath) @@ -64,8 +65,8 @@ STORAGE_TYPE = my_minio STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadPackagesFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadPackagesFrom(cfg)) assert.EqualValues(t, "minio", Packages.Storage.Type) assert.EqualValues(t, "packages/", Packages.Storage.MinioConfig.BasePath) @@ -80,8 +81,8 @@ MINIO_BASE_PATH = my_packages/ STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadPackagesFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadPackagesFrom(cfg)) assert.EqualValues(t, "minio", Packages.Storage.Type) assert.EqualValues(t, "my_packages/", Packages.Storage.MinioConfig.BasePath) @@ -103,9 +104,9 @@ MINIO_ACCESS_KEY_ID = correct_key MINIO_SECRET_ACCESS_KEY = correct_key ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadPackagesFrom(cfg)) + require.NoError(t, loadPackagesFrom(cfg)) storage := Packages.Storage assert.EqualValues(t, "minio", storage.Type) @@ -130,9 +131,9 @@ MINIO_ACCESS_KEY_ID = correct_key MINIO_SECRET_ACCESS_KEY = correct_key ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadPackagesFrom(cfg)) + require.NoError(t, loadPackagesFrom(cfg)) storage := Packages.Storage assert.EqualValues(t, "minio", storage.Type) @@ -158,9 +159,9 @@ MINIO_ACCESS_KEY_ID = correct_key MINIO_SECRET_ACCESS_KEY = correct_key ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadPackagesFrom(cfg)) + require.NoError(t, loadPackagesFrom(cfg)) storage := Packages.Storage assert.EqualValues(t, "minio", storage.Type) @@ -186,9 +187,9 @@ MINIO_ACCESS_KEY_ID = correct_key MINIO_SECRET_ACCESS_KEY = correct_key ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadPackagesFrom(cfg)) + require.NoError(t, loadPackagesFrom(cfg)) storage := Packages.Storage assert.EqualValues(t, "minio", storage.Type) diff --git a/modules/setting/repository_archive_test.go b/modules/setting/repository_archive_test.go index a0f91f0da1..d3901b6e47 100644 --- a/modules/setting/repository_archive_test.go +++ b/modules/setting/repository_archive_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_getStorageInheritNameSectionTypeForRepoArchive(t *testing.T) { @@ -16,8 +17,8 @@ func Test_getStorageInheritNameSectionTypeForRepoArchive(t *testing.T) { STORAGE_TYPE = minio ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadRepoArchiveFrom(cfg)) assert.EqualValues(t, "minio", RepoArchive.Storage.Type) assert.EqualValues(t, "repo-archive/", RepoArchive.Storage.MinioConfig.BasePath) @@ -28,8 +29,8 @@ STORAGE_TYPE = minio STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadRepoArchiveFrom(cfg)) assert.EqualValues(t, "minio", RepoArchive.Storage.Type) assert.EqualValues(t, "repo-archive/", RepoArchive.Storage.MinioConfig.BasePath) @@ -43,8 +44,8 @@ STORAGE_TYPE = my_minio STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadRepoArchiveFrom(cfg)) assert.EqualValues(t, "minio", RepoArchive.Storage.Type) assert.EqualValues(t, "repo-archive/", RepoArchive.Storage.MinioConfig.BasePath) @@ -59,8 +60,8 @@ MINIO_BASE_PATH = my_archive/ STORAGE_TYPE = minio ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadRepoArchiveFrom(cfg)) assert.EqualValues(t, "minio", RepoArchive.Storage.Type) assert.EqualValues(t, "my_archive/", RepoArchive.Storage.MinioConfig.BasePath) @@ -79,9 +80,9 @@ MINIO_ACCESS_KEY_ID = correct_key MINIO_SECRET_ACCESS_KEY = correct_key ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, loadRepoArchiveFrom(cfg)) storage := RepoArchive.Storage assert.EqualValues(t, "minio", storage.Type) @@ -101,9 +102,9 @@ MINIO_ACCESS_KEY_ID = correct_key MINIO_SECRET_ACCESS_KEY = correct_key ` cfg, err = NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, loadRepoArchiveFrom(cfg)) storage = RepoArchive.Storage assert.EqualValues(t, "minio", storage.Type) diff --git a/modules/setting/service_test.go b/modules/setting/service_test.go index 1647bcec16..7a13e39238 100644 --- a/modules/setting/service_test.go +++ b/modules/setting/service_test.go @@ -10,6 +10,7 @@ import ( "github.com/gobwas/glob" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLoadServices(t *testing.T) { @@ -24,7 +25,7 @@ EMAIL_DOMAIN_WHITELIST = d1, *.w EMAIL_DOMAIN_ALLOWLIST = d2, *.a EMAIL_DOMAIN_BLOCKLIST = d3, *.b `) - assert.NoError(t, err) + require.NoError(t, err) loadServiceFrom(cfg) match := func(globs []glob.Glob, s string) bool { @@ -119,7 +120,7 @@ ALLOWED_USER_VISIBILITY_MODES = public, limit, privated for kase, fun := range kases { t.Run(kase, func(t *testing.T) { cfg, err := NewConfigProviderFromData(kase) - assert.NoError(t, err) + require.NoError(t, err) loadServiceFrom(cfg) fun() // reset diff --git a/modules/setting/storage_test.go b/modules/setting/storage_test.go index 6f38bf1d55..271607914c 100644 --- a/modules/setting/storage_test.go +++ b/modules/setting/storage_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_getStorageMultipleName(t *testing.T) { @@ -23,17 +24,17 @@ STORAGE_TYPE = minio MINIO_BUCKET = gitea-storage ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadAttachmentFrom(cfg)) + require.NoError(t, loadAttachmentFrom(cfg)) assert.EqualValues(t, "gitea-attachment", Attachment.Storage.MinioConfig.Bucket) assert.EqualValues(t, "attachments/", Attachment.Storage.MinioConfig.BasePath) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "gitea-lfs", LFS.Storage.MinioConfig.Bucket) assert.EqualValues(t, "lfs/", LFS.Storage.MinioConfig.BasePath) - assert.NoError(t, loadAvatarsFrom(cfg)) + require.NoError(t, loadAvatarsFrom(cfg)) assert.EqualValues(t, "gitea-storage", Avatar.Storage.MinioConfig.Bucket) assert.EqualValues(t, "avatars/", Avatar.Storage.MinioConfig.BasePath) } @@ -48,13 +49,13 @@ STORAGE_TYPE = minio MINIO_BUCKET = gitea-storage ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadAttachmentFrom(cfg)) + require.NoError(t, loadAttachmentFrom(cfg)) assert.EqualValues(t, "gitea-storage", Attachment.Storage.MinioConfig.Bucket) assert.EqualValues(t, "attachments/", Attachment.Storage.MinioConfig.BasePath) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "gitea-storage", LFS.Storage.MinioConfig.Bucket) assert.EqualValues(t, "lfs/", LFS.Storage.MinioConfig.BasePath) } @@ -65,19 +66,19 @@ func Test_getStorageInheritStorageType(t *testing.T) { STORAGE_TYPE = minio ` cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, loadPackagesFrom(cfg)) + require.NoError(t, loadPackagesFrom(cfg)) assert.EqualValues(t, "minio", Packages.Storage.Type) assert.EqualValues(t, "gitea", Packages.Storage.MinioConfig.Bucket) assert.EqualValues(t, "packages/", Packages.Storage.MinioConfig.BasePath) - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, loadRepoArchiveFrom(cfg)) assert.EqualValues(t, "minio", RepoArchive.Storage.Type) assert.EqualValues(t, "gitea", RepoArchive.Storage.MinioConfig.Bucket) assert.EqualValues(t, "repo-archive/", RepoArchive.Storage.MinioConfig.BasePath) - assert.NoError(t, loadActionsFrom(cfg)) + require.NoError(t, loadActionsFrom(cfg)) assert.EqualValues(t, "minio", Actions.LogStorage.Type) assert.EqualValues(t, "gitea", Actions.LogStorage.MinioConfig.Bucket) assert.EqualValues(t, "actions_log/", Actions.LogStorage.MinioConfig.BasePath) @@ -86,12 +87,12 @@ STORAGE_TYPE = minio assert.EqualValues(t, "gitea", Actions.ArtifactStorage.MinioConfig.Bucket) assert.EqualValues(t, "actions_artifacts/", Actions.ArtifactStorage.MinioConfig.BasePath) - assert.NoError(t, loadAvatarsFrom(cfg)) + require.NoError(t, loadAvatarsFrom(cfg)) assert.EqualValues(t, "minio", Avatar.Storage.Type) assert.EqualValues(t, "gitea", Avatar.Storage.MinioConfig.Bucket) assert.EqualValues(t, "avatars/", Avatar.Storage.MinioConfig.BasePath) - assert.NoError(t, loadRepoAvatarFrom(cfg)) + require.NoError(t, loadRepoAvatarFrom(cfg)) assert.EqualValues(t, "minio", RepoAvatar.Storage.Type) assert.EqualValues(t, "gitea", RepoAvatar.Storage.MinioConfig.Bucket) assert.EqualValues(t, "repo-avatars/", RepoAvatar.Storage.MinioConfig.BasePath) @@ -105,10 +106,10 @@ type testLocalStoragePathCase struct { func testLocalStoragePath(t *testing.T, appDataPath, iniStr string, cases []testLocalStoragePathCase) { cfg, err := NewConfigProviderFromData(iniStr) - assert.NoError(t, err) + require.NoError(t, err) AppDataPath = appDataPath for _, c := range cases { - assert.NoError(t, c.loader(cfg)) + require.NoError(t, c.loader(cfg)) storage := *c.storagePtr assert.EqualValues(t, "local", storage.Type) @@ -315,9 +316,9 @@ func Test_getStorageConfiguration20(t *testing.T) { STORAGE_TYPE = my_storage PATH = archives `) - assert.NoError(t, err) + require.NoError(t, err) - assert.Error(t, loadRepoArchiveFrom(cfg)) + require.Error(t, loadRepoArchiveFrom(cfg)) } func Test_getStorageConfiguration21(t *testing.T) { @@ -344,12 +345,12 @@ STORAGE_TYPE = minio MINIO_ACCESS_KEY_ID = my_access_key MINIO_SECRET_ACCESS_KEY = my_secret_key `) - assert.NoError(t, err) + require.NoError(t, err) _, err = getStorage(cfg, "", "", nil) - assert.Error(t, err) + require.Error(t, err) - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, loadRepoArchiveFrom(cfg)) cp := RepoArchive.Storage.ToShadowCopy() assert.EqualValues(t, "******", cp.MinioConfig.AccessKeyID) assert.EqualValues(t, "******", cp.MinioConfig.SecretAccessKey) @@ -364,8 +365,8 @@ STORAGE_TYPE = my_archive ; unsupported, storage type should be defined explicitly PATH = archives `) - assert.NoError(t, err) - assert.Error(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, err) + require.Error(t, loadRepoArchiveFrom(cfg)) } func Test_getStorageConfiguration25(t *testing.T) { @@ -378,8 +379,8 @@ STORAGE_TYPE = my_archive STORAGE_TYPE = unknown // should be local or minio PATH = archives `) - assert.NoError(t, err) - assert.Error(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, err) + require.Error(t, loadRepoArchiveFrom(cfg)) } func Test_getStorageConfiguration26(t *testing.T) { @@ -391,10 +392,10 @@ MINIO_SECRET_ACCESS_KEY = my_secret_key ; wrong configuration MINIO_USE_SSL = abc `) - assert.NoError(t, err) - // assert.Error(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, err) + // require.Error(t, loadRepoArchiveFrom(cfg)) // FIXME: this should return error but now ini package's MapTo() doesn't check type - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, loadRepoArchiveFrom(cfg)) } func Test_getStorageConfiguration27(t *testing.T) { @@ -405,11 +406,11 @@ MINIO_ACCESS_KEY_ID = my_access_key MINIO_SECRET_ACCESS_KEY = my_secret_key MINIO_USE_SSL = true `) - assert.NoError(t, err) - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadRepoArchiveFrom(cfg)) assert.EqualValues(t, "my_access_key", RepoArchive.Storage.MinioConfig.AccessKeyID) assert.EqualValues(t, "my_secret_key", RepoArchive.Storage.MinioConfig.SecretAccessKey) - assert.EqualValues(t, true, RepoArchive.Storage.MinioConfig.UseSSL) + assert.True(t, RepoArchive.Storage.MinioConfig.UseSSL) assert.EqualValues(t, "repo-archive/", RepoArchive.Storage.MinioConfig.BasePath) } @@ -422,11 +423,11 @@ MINIO_SECRET_ACCESS_KEY = my_secret_key MINIO_USE_SSL = true MINIO_BASE_PATH = /prefix `) - assert.NoError(t, err) - assert.NoError(t, loadRepoArchiveFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadRepoArchiveFrom(cfg)) assert.EqualValues(t, "my_access_key", RepoArchive.Storage.MinioConfig.AccessKeyID) assert.EqualValues(t, "my_secret_key", RepoArchive.Storage.MinioConfig.SecretAccessKey) - assert.EqualValues(t, true, RepoArchive.Storage.MinioConfig.UseSSL) + assert.True(t, RepoArchive.Storage.MinioConfig.UseSSL) assert.EqualValues(t, "/prefix/repo-archive/", RepoArchive.Storage.MinioConfig.BasePath) cfg, err = NewConfigProviderFromData(` @@ -440,11 +441,11 @@ MINIO_BASE_PATH = /prefix [lfs] MINIO_BASE_PATH = /lfs `) - assert.NoError(t, err) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "my_access_key", LFS.Storage.MinioConfig.AccessKeyID) assert.EqualValues(t, "my_secret_key", LFS.Storage.MinioConfig.SecretAccessKey) - assert.EqualValues(t, true, LFS.Storage.MinioConfig.UseSSL) + assert.True(t, true, LFS.Storage.MinioConfig.UseSSL) assert.EqualValues(t, "/lfs", LFS.Storage.MinioConfig.BasePath) cfg, err = NewConfigProviderFromData(` @@ -458,10 +459,10 @@ MINIO_BASE_PATH = /prefix [storage.lfs] MINIO_BASE_PATH = /lfs `) - assert.NoError(t, err) - assert.NoError(t, loadLFSFrom(cfg)) + require.NoError(t, err) + require.NoError(t, loadLFSFrom(cfg)) assert.EqualValues(t, "my_access_key", LFS.Storage.MinioConfig.AccessKeyID) assert.EqualValues(t, "my_secret_key", LFS.Storage.MinioConfig.SecretAccessKey) - assert.EqualValues(t, true, LFS.Storage.MinioConfig.UseSSL) + assert.True(t, LFS.Storage.MinioConfig.UseSSL) assert.EqualValues(t, "/lfs", LFS.Storage.MinioConfig.BasePath) } diff --git a/modules/sitemap/sitemap_test.go b/modules/sitemap/sitemap_test.go index 1180463cd7..39a2178c09 100644 --- a/modules/sitemap/sitemap_test.go +++ b/modules/sitemap/sitemap_test.go @@ -11,6 +11,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewSitemap(t *testing.T) { @@ -82,7 +83,7 @@ func TestNewSitemap(t *testing.T) { if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equalf(t, tt.want, buf.String(), "NewSitemap()") } }) @@ -158,7 +159,7 @@ func TestNewSitemapIndex(t *testing.T) { if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equalf(t, tt.want, buf.String(), "NewSitemapIndex()") } }) diff --git a/modules/storage/helper_test.go b/modules/storage/helper_test.go index f1f9791044..60a7c61289 100644 --- a/modules/storage/helper_test.go +++ b/modules/storage/helper_test.go @@ -8,6 +8,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_discardStorage(t *testing.T) { @@ -20,30 +21,30 @@ func Test_discardStorage(t *testing.T) { { got, err := tt.Open("path") assert.Nil(t, got) - assert.Error(t, err, string(tt)) + require.Error(t, err, string(tt)) } { got, err := tt.Save("path", bytes.NewReader([]byte{0}), 1) assert.Equal(t, int64(0), got) - assert.Error(t, err, string(tt)) + require.Error(t, err, string(tt)) } { got, err := tt.Stat("path") assert.Nil(t, got) - assert.Error(t, err, string(tt)) + require.Error(t, err, string(tt)) } { err := tt.Delete("path") - assert.Error(t, err, string(tt)) + require.Error(t, err, string(tt)) } { got, err := tt.URL("path", "name") assert.Nil(t, got) - assert.Errorf(t, err, string(tt)) + require.Errorf(t, err, string(tt)) } { err := tt.IterateObjects("", func(_ string, _ Object) error { return nil }) - assert.Error(t, err, string(tt)) + require.Error(t, err, string(tt)) } }) } diff --git a/modules/storage/minio_test.go b/modules/storage/minio_test.go index 3fe01825e9..9ce1dbc7b4 100644 --- a/modules/storage/minio_test.go +++ b/modules/storage/minio_test.go @@ -14,6 +14,7 @@ import ( "github.com/minio/minio-go/v7" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMinioStorageIterator(t *testing.T) { @@ -108,7 +109,7 @@ func TestS3StorageBadRequest(t *testing.T) { } } _, err := NewStorage(setting.MinioStorageType, cfg) - assert.ErrorContains(t, err, message) + require.ErrorContains(t, err, message) } func TestMinioCredentials(t *testing.T) { @@ -128,7 +129,7 @@ func TestMinioCredentials(t *testing.T) { creds := buildMinioCredentials(cfg, FakeEndpoint) v, err := creds.Get() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ExpectedAccessKey, v.AccessKeyID) assert.Equal(t, ExpectedSecretAccessKey, v.SecretAccessKey) }) @@ -143,7 +144,7 @@ func TestMinioCredentials(t *testing.T) { creds := buildMinioCredentials(cfg, FakeEndpoint) v, err := creds.Get() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ExpectedAccessKey+"Minio", v.AccessKeyID) assert.Equal(t, ExpectedSecretAccessKey+"Minio", v.SecretAccessKey) }) @@ -155,7 +156,7 @@ func TestMinioCredentials(t *testing.T) { creds := buildMinioCredentials(cfg, FakeEndpoint) v, err := creds.Get() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ExpectedAccessKey+"AWS", v.AccessKeyID) assert.Equal(t, ExpectedSecretAccessKey+"AWS", v.SecretAccessKey) }) @@ -168,7 +169,7 @@ func TestMinioCredentials(t *testing.T) { creds := buildMinioCredentials(cfg, FakeEndpoint) v, err := creds.Get() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ExpectedAccessKey+"MinioFile", v.AccessKeyID) assert.Equal(t, ExpectedSecretAccessKey+"MinioFile", v.SecretAccessKey) }) @@ -181,7 +182,7 @@ func TestMinioCredentials(t *testing.T) { creds := buildMinioCredentials(cfg, FakeEndpoint) v, err := creds.Get() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ExpectedAccessKey+"AWSFile", v.AccessKeyID) assert.Equal(t, ExpectedSecretAccessKey+"AWSFile", v.SecretAccessKey) }) @@ -207,7 +208,7 @@ func TestMinioCredentials(t *testing.T) { creds := buildMinioCredentials(cfg, server.URL) v, err := creds.Get() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ExpectedAccessKey+"IAM", v.AccessKeyID) assert.Equal(t, ExpectedSecretAccessKey+"IAM", v.SecretAccessKey) }) diff --git a/modules/storage/storage_test.go b/modules/storage/storage_test.go index 5e3e9c7dba..70bcd3155a 100644 --- a/modules/storage/storage_test.go +++ b/modules/storage/storage_test.go @@ -10,11 +10,12 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testStorageIterator(t *testing.T, typStr Type, cfg *setting.Storage) { l, err := NewStorage(typStr, cfg) - assert.NoError(t, err) + require.NoError(t, err) testFiles := [][]string{ {"a/1.txt", "a1"}, @@ -27,7 +28,7 @@ func testStorageIterator(t *testing.T, typStr Type, cfg *setting.Storage) { } for _, f := range testFiles { _, err = l.Save(f[0], bytes.NewBufferString(f[1]), -1) - assert.NoError(t, err) + require.NoError(t, err) } expectedList := map[string][]string{ @@ -45,7 +46,7 @@ func testStorageIterator(t *testing.T, typStr Type, cfg *setting.Storage) { count++ return nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, expected, count) } } diff --git a/modules/structs/issue_test.go b/modules/structs/issue_test.go index fa7a20db8b..2003e22e0a 100644 --- a/modules/structs/issue_test.go +++ b/modules/structs/issue_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) @@ -97,7 +98,7 @@ labels: if tt.wantErr != "" { assert.EqualError(t, err, tt.wantErr) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.want, tt.tmpl) } }) diff --git a/modules/system/appstate_test.go b/modules/system/appstate_test.go index d4b9e167c2..2f44c7b845 100644 --- a/modules/system/appstate_test.go +++ b/modules/system/appstate_test.go @@ -10,6 +10,7 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -36,30 +37,30 @@ func (*testItem2) Name() string { } func TestAppStateDB(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) as := &DBStore{} item1 := new(testItem1) - assert.NoError(t, as.Get(db.DefaultContext, item1)) + require.NoError(t, as.Get(db.DefaultContext, item1)) assert.Equal(t, "", item1.Val1) assert.EqualValues(t, 0, item1.Val2) item1 = new(testItem1) item1.Val1 = "a" item1.Val2 = 2 - assert.NoError(t, as.Set(db.DefaultContext, item1)) + require.NoError(t, as.Set(db.DefaultContext, item1)) item2 := new(testItem2) item2.K = "V" - assert.NoError(t, as.Set(db.DefaultContext, item2)) + require.NoError(t, as.Set(db.DefaultContext, item2)) item1 = new(testItem1) - assert.NoError(t, as.Get(db.DefaultContext, item1)) + require.NoError(t, as.Get(db.DefaultContext, item1)) assert.Equal(t, "a", item1.Val1) assert.EqualValues(t, 2, item1.Val2) item2 = new(testItem2) - assert.NoError(t, as.Get(db.DefaultContext, item2)) + require.NoError(t, as.Get(db.DefaultContext, item2)) assert.Equal(t, "V", item2.K) } diff --git a/modules/templates/eval/eval_test.go b/modules/templates/eval/eval_test.go index c9e514b5eb..3e68203638 100644 --- a/modules/templates/eval/eval_test.go +++ b/modules/templates/eval/eval_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func tokens(s string) (a []any) { @@ -20,15 +21,15 @@ func tokens(s string) (a []any) { func TestEval(t *testing.T) { n, err := Expr(0, "/", 0.0) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, math.IsNaN(n.Value.(float64))) _, err = Expr(nil) - assert.ErrorContains(t, err, "unsupported token type") + require.ErrorContains(t, err, "unsupported token type") _, err = Expr([]string{}) - assert.ErrorContains(t, err, "unsupported token type") + require.ErrorContains(t, err, "unsupported token type") _, err = Expr(struct{}{}) - assert.ErrorContains(t, err, "unsupported token type") + require.ErrorContains(t, err, "unsupported token type") cases := []struct { expr string @@ -69,9 +70,8 @@ func TestEval(t *testing.T) { for _, c := range cases { n, err := Expr(tokens(c.expr)...) - if assert.NoError(t, err, "expr: %s", c.expr) { - assert.Equal(t, c.want, n.Value) - } + require.NoError(t, err, "expr: %s", c.expr) + assert.Equal(t, c.want, n.Value) } bads := []struct { @@ -89,6 +89,6 @@ func TestEval(t *testing.T) { } for _, c := range bads { _, err = Expr(tokens(c.expr)...) - assert.ErrorContains(t, err, c.errMsg, "expr: %s", c.expr) + require.ErrorContains(t, err, c.errMsg, "expr: %s", c.expr) } } diff --git a/modules/templates/htmlrenderer_test.go b/modules/templates/htmlrenderer_test.go index 2a74b74c23..a1d3783a75 100644 --- a/modules/templates/htmlrenderer_test.go +++ b/modules/templates/htmlrenderer_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/assetfs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestExtractErrorLine(t *testing.T) { @@ -60,10 +61,10 @@ func TestHandleError(t *testing.T) { test := func(s string, h func(error) string, expect string) { err := os.WriteFile(dir+"/test.tmpl", []byte(s), 0o644) - assert.NoError(t, err) + require.NoError(t, err) tmpl := template.New("test") _, err = tmpl.Parse(s) - assert.Error(t, err) + require.Error(t, err) msg := h(err) assert.EqualValues(t, strings.TrimSpace(expect), strings.TrimSpace(msg)) } @@ -93,7 +94,7 @@ template error: tmp:test:1 : unexpected "3" in operand // no idea about how to trigger such strange error, so mock an error to test it err := os.WriteFile(dir+"/test.tmpl", []byte("god knows XXX"), 0o644) - assert.NoError(t, err) + require.NoError(t, err) expectedMsg := ` template error: tmp:test:1 : expected end; found XXX ---------------------------------------------------------------------- diff --git a/modules/templates/scopedtmpl/scopedtmpl_test.go b/modules/templates/scopedtmpl/scopedtmpl_test.go index 774b8c7d42..9bbd0c7c70 100644 --- a/modules/templates/scopedtmpl/scopedtmpl_test.go +++ b/modules/templates/scopedtmpl/scopedtmpl_test.go @@ -12,6 +12,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestScopedTemplateSetFuncMap(t *testing.T) { @@ -22,7 +23,7 @@ func TestScopedTemplateSetFuncMap(t *testing.T) { }}) _, err := all.New("base").Parse(`{{CtxFunc "base"}}`) - assert.NoError(t, err) + require.NoError(t, err) _, err = all.New("test").Parse(strings.TrimSpace(` {{template "base"}} @@ -30,10 +31,10 @@ func TestScopedTemplateSetFuncMap(t *testing.T) { {{template "base"}} {{CtxFunc "test"}} `)) - assert.NoError(t, err) + require.NoError(t, err) ts, err := newScopedTemplateSet(all, "test") - assert.NoError(t, err) + require.NoError(t, err) // try to use different CtxFunc to render concurrently @@ -57,12 +58,12 @@ func TestScopedTemplateSetFuncMap(t *testing.T) { wg.Add(2) go func() { err := ts.newExecutor(funcMap1).Execute(&out1, nil) - assert.NoError(t, err) + require.NoError(t, err) wg.Done() }() go func() { err := ts.newExecutor(funcMap2).Execute(&out2, nil) - assert.NoError(t, err) + require.NoError(t, err) wg.Done() }() wg.Wait() @@ -73,17 +74,17 @@ func TestScopedTemplateSetFuncMap(t *testing.T) { func TestScopedTemplateSetEscape(t *testing.T) { all := template.New("") _, err := all.New("base").Parse(`{{.text}}`) - assert.NoError(t, err) + require.NoError(t, err) _, err = all.New("test").Parse(`{{template "base" .}}
{{.text}}
`) - assert.NoError(t, err) + require.NoError(t, err) ts, err := newScopedTemplateSet(all, "test") - assert.NoError(t, err) + require.NoError(t, err) out := bytes.Buffer{} err = ts.newExecutor(nil).Execute(&out, map[string]string{"param": "/", "text": "<"}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, `<
<
`, out.String()) } @@ -91,8 +92,8 @@ func TestScopedTemplateSetEscape(t *testing.T) { func TestScopedTemplateSetUnsafe(t *testing.T) { all := template.New("") _, err := all.New("test").Parse(``) - assert.NoError(t, err) + require.NoError(t, err) _, err = newScopedTemplateSet(all, "test") - assert.ErrorContains(t, err, "appears in an ambiguous context within a URL") + require.ErrorContains(t, err, "appears in an ambiguous context within a URL") } diff --git a/modules/templates/util_test.go b/modules/templates/util_test.go index febaf7fa88..79aaba4a0e 100644 --- a/modules/templates/util_test.go +++ b/modules/templates/util_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDict(t *testing.T) { @@ -27,9 +28,8 @@ func TestDict(t *testing.T) { for _, c := range cases { got, err := dict(c.args...) - if assert.NoError(t, err) { - assert.EqualValues(t, c.want, got) - } + require.NoError(t, err) + assert.EqualValues(t, c.want, got) } bads := []struct { @@ -41,7 +41,7 @@ func TestDict(t *testing.T) { } for _, c := range bads { _, err := dict(c.args...) - assert.Error(t, err) + require.Error(t, err) } } @@ -51,7 +51,7 @@ func TestUtils(t *testing.T) { tmpl.Funcs(template.FuncMap{"SliceUtils": NewSliceUtils, "StringUtils": NewStringUtils}) template.Must(tmpl.Parse(code)) w := &strings.Builder{} - assert.NoError(t, tmpl.Execute(w, data)) + require.NoError(t, tmpl.Execute(w, data)) return w.String() } @@ -75,5 +75,5 @@ func TestUtils(t *testing.T) { template.Must(tmpl.Parse("{{SliceUtils.Contains .Slice .Value}}")) // error is like this: `template: test:1:12: executing "test" at : error calling Contains: ...` err := tmpl.Execute(io.Discard, map[string]any{"Slice": struct{}{}}) - assert.ErrorContains(t, err, "invalid type, expected slice or array") + require.ErrorContains(t, err, "invalid type, expected slice or array") } diff --git a/modules/templates/vars/vars_test.go b/modules/templates/vars/vars_test.go index 8f421d9e4b..c54342204d 100644 --- a/modules/templates/vars/vars_test.go +++ b/modules/templates/vars/vars_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestExpandVars(t *testing.T) { @@ -62,9 +63,9 @@ func TestExpandVars(t *testing.T) { res, err := Expand(kase.tmpl, kase.data) assert.EqualValues(t, kase.out, res) if kase.error { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } diff --git a/modules/translation/i18n/i18n_test.go b/modules/translation/i18n/i18n_test.go index b364992dfe..244f6ffbb3 100644 --- a/modules/translation/i18n/i18n_test.go +++ b/modules/translation/i18n/i18n_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLocaleStore(t *testing.T) { @@ -29,8 +30,8 @@ sub = Changed Sub String `) ls := NewLocaleStore() - assert.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", testData1, nil)) - assert.NoError(t, ls.AddLocaleByIni("lang2", "Lang2", testData2, nil)) + require.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", testData1, nil)) + require.NoError(t, ls.AddLocaleByIni("lang2", "Lang2", testData2, nil)) ls.SetDefaultLang("lang1") lang1, _ := ls.Locale("lang1") @@ -61,7 +62,7 @@ sub = Changed Sub String found := lang1.HasKey("no-such") assert.False(t, found) - assert.NoError(t, ls.Close()) + require.NoError(t, ls.Close()) } func TestLocaleStoreMoreSource(t *testing.T) { @@ -76,7 +77,7 @@ c=22 `) ls := NewLocaleStore() - assert.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", testData1, testData2)) + require.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", testData1, testData2)) lang1, _ := ls.Locale("lang1") assert.Equal(t, "11", lang1.TrString("a")) assert.Equal(t, "21", lang1.TrString("b")) @@ -117,7 +118,7 @@ func (e *errorPointerReceiver) Error() string { func TestLocaleWithTemplate(t *testing.T) { ls := NewLocaleStore() - assert.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", []byte(`key=%s`), nil)) + require.NoError(t, ls.AddLocaleByIni("lang1", "Lang1", []byte(`key=%s`), nil)) lang1, _ := ls.Locale("lang1") tmpl := template.New("test").Funcs(template.FuncMap{"tr": lang1.TrHTML}) @@ -143,7 +144,7 @@ func TestLocaleWithTemplate(t *testing.T) { buf := &strings.Builder{} for _, c := range cases { buf.Reset() - assert.NoError(t, tmpl.Execute(buf, map[string]any{"var": c.in})) + require.NoError(t, tmpl.Execute(buf, map[string]any{"var": c.in})) assert.Equal(t, c.want, buf.String()) } } @@ -182,9 +183,9 @@ func TestLocaleStoreQuirks(t *testing.T) { ls := NewLocaleStore() err := ls.AddLocaleByIni("lang1", "Lang1", []byte("a="+testData.in), nil) lang1, _ := ls.Locale("lang1") - assert.NoError(t, err, testData.hint) + require.NoError(t, err, testData.hint) assert.Equal(t, testData.out, lang1.TrString("a"), testData.hint) - assert.NoError(t, ls.Close()) + require.NoError(t, ls.Close()) } // TODO: Crowdin needs the strings to be quoted correctly and doesn't like incomplete quotes diff --git a/modules/typesniffer/typesniffer_test.go b/modules/typesniffer/typesniffer_test.go index da662ab99d..f6fa07ee7f 100644 --- a/modules/typesniffer/typesniffer_test.go +++ b/modules/typesniffer/typesniffer_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDetectContentTypeLongerThanSniffLen(t *testing.T) { @@ -119,18 +120,18 @@ func TestIsAudio(t *testing.T) { func TestDetectContentTypeFromReader(t *testing.T) { mp3, _ := base64.StdEncoding.DecodeString("SUQzBAAAAAABAFRYWFgAAAASAAADbWFqb3JfYnJhbmQAbXA0MgBUWFhYAAAAEQAAA21pbm9yX3Zl") st, err := DetectContentTypeFromReader(bytes.NewReader(mp3)) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, st.IsAudio()) } func TestDetectContentTypeOgg(t *testing.T) { oggAudio, _ := hex.DecodeString("4f67675300020000000000000000352f0000000000007dc39163011e01766f72626973000000000244ac0000000000000071020000000000b8014f6767530000") st, err := DetectContentTypeFromReader(bytes.NewReader(oggAudio)) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, st.IsAudio()) oggVideo, _ := hex.DecodeString("4f676753000200000000000000007d9747ef000000009b59daf3012a807468656f7261030201001e00110001e000010e00020000001e00000001000001000001") st, err = DetectContentTypeFromReader(bytes.NewReader(oggVideo)) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, st.IsVideo()) } diff --git a/modules/updatechecker/update_checker_test.go b/modules/updatechecker/update_checker_test.go index 301afd95e4..5ac2603ca1 100644 --- a/modules/updatechecker/update_checker_test.go +++ b/modules/updatechecker/update_checker_test.go @@ -7,10 +7,11 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDNSUpdate(t *testing.T) { version, err := getVersionDNS("release.forgejo.org") - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, version) } diff --git a/modules/uri/uri_test.go b/modules/uri/uri_test.go index 11b915c261..71a8985cd7 100644 --- a/modules/uri/uri_test.go +++ b/modules/uri/uri_test.go @@ -7,13 +7,13 @@ import ( "path/filepath" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestReadURI(t *testing.T) { p, err := filepath.Abs("./uri.go") - assert.NoError(t, err) + require.NoError(t, err) f, err := Open("file://" + p) - assert.NoError(t, err) + require.NoError(t, err) defer f.Close() } diff --git a/modules/util/color_test.go b/modules/util/color_test.go index be6e6b122a..abd5551218 100644 --- a/modules/util/color_test.go +++ b/modules/util/color_test.go @@ -27,9 +27,9 @@ func Test_HexToRBGColor(t *testing.T) { } for n, c := range cases { r, g, b := HexToRBGColor(c.colorString) - assert.Equal(t, c.expectedR, r, "case %d: error R should match: expected %f, but get %f", n, c.expectedR, r) - assert.Equal(t, c.expectedG, g, "case %d: error G should match: expected %f, but get %f", n, c.expectedG, g) - assert.Equal(t, c.expectedB, b, "case %d: error B should match: expected %f, but get %f", n, c.expectedB, b) + assert.InDelta(t, c.expectedR, r, 0, "case %d: error R should match: expected %f, but get %f", n, c.expectedR, r) + assert.InDelta(t, c.expectedG, g, 0, "case %d: error G should match: expected %f, but get %f", n, c.expectedG, g) + assert.InDelta(t, c.expectedB, b, 0, "case %d: error B should match: expected %f, but get %f", n, c.expectedB, b) } } diff --git a/modules/util/file_unix_test.go b/modules/util/file_unix_test.go index 87d6c2f09a..d60082a034 100644 --- a/modules/util/file_unix_test.go +++ b/modules/util/file_unix_test.go @@ -10,16 +10,17 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestApplyUmask(t *testing.T) { f, err := os.CreateTemp(t.TempDir(), "test-filemode-") - assert.NoError(t, err) + require.NoError(t, err) err = os.Chmod(f.Name(), 0o777) - assert.NoError(t, err) + require.NoError(t, err) st, err := os.Stat(f.Name()) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0o777, st.Mode().Perm()&0o777) oldDefaultUmask := defaultUmask @@ -28,8 +29,8 @@ func TestApplyUmask(t *testing.T) { defaultUmask = oldDefaultUmask }() err = ApplyUmask(f.Name(), os.ModePerm) - assert.NoError(t, err) + require.NoError(t, err) st, err = os.Stat(f.Name()) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0o740, st.Mode().Perm()&0o777) } diff --git a/modules/util/filebuffer/file_backed_buffer_test.go b/modules/util/filebuffer/file_backed_buffer_test.go index 16d5a1965f..c56c1c64e9 100644 --- a/modules/util/filebuffer/file_backed_buffer_test.go +++ b/modules/util/filebuffer/file_backed_buffer_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestFileBackedBuffer(t *testing.T) { @@ -22,14 +23,14 @@ func TestFileBackedBuffer(t *testing.T) { for _, c := range cases { buf, err := CreateFromReader(strings.NewReader(c.Data), c.MaxMemorySize) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, len(c.Data), buf.Size()) data, err := io.ReadAll(buf) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, c.Data, string(data)) - assert.NoError(t, buf.Close()) + require.NoError(t, buf.Close()) } } diff --git a/modules/util/io_test.go b/modules/util/io_test.go index 275575463a..870e713646 100644 --- a/modules/util/io_test.go +++ b/modules/util/io_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type readerWithError struct { @@ -27,40 +28,40 @@ func TestReadWithLimit(t *testing.T) { // normal test buf, err := readWithLimit(bytes.NewBuffer(bs), 5, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("01"), buf) buf, err = readWithLimit(bytes.NewBuffer(bs), 5, 5) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("01234"), buf) buf, err = readWithLimit(bytes.NewBuffer(bs), 5, 6) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("012345"), buf) buf, err = readWithLimit(bytes.NewBuffer(bs), 5, len(bs)) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("0123456789abcdef"), buf) buf, err = readWithLimit(bytes.NewBuffer(bs), 5, 100) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("0123456789abcdef"), buf) // test with error buf, err = readWithLimit(&readerWithError{bytes.NewBuffer(bs)}, 5, 10) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("0123456789"), buf) buf, err = readWithLimit(&readerWithError{bytes.NewBuffer(bs)}, 5, 100) - assert.ErrorContains(t, err, "test error") + require.ErrorContains(t, err, "test error") assert.Empty(t, buf) // test public function buf, err = ReadWithLimit(bytes.NewBuffer(bs), 2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("01"), buf) buf, err = ReadWithLimit(bytes.NewBuffer(bs), 9999999) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []byte("0123456789abcdef"), buf) } diff --git a/modules/util/keypair_test.go b/modules/util/keypair_test.go index c6f68c845a..ec9bca7efa 100644 --- a/modules/util/keypair_test.go +++ b/modules/util/keypair_test.go @@ -14,11 +14,12 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestKeygen(t *testing.T) { priv, pub, err := GenerateKeyPair(2048) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, priv) assert.NotEmpty(t, pub) @@ -29,7 +30,7 @@ func TestKeygen(t *testing.T) { func TestSignUsingKeys(t *testing.T) { priv, pub, err := GenerateKeyPair(2048) - assert.NoError(t, err) + require.NoError(t, err) privPem, _ := pem.Decode([]byte(priv)) if privPem == nil || privPem.Type != "RSA PRIVATE KEY" { @@ -37,7 +38,7 @@ func TestSignUsingKeys(t *testing.T) { } privParsed, err := x509.ParsePKCS1PrivateKey(privPem.Bytes) - assert.NoError(t, err) + require.NoError(t, err) pubPem, _ := pem.Decode([]byte(pub)) if pubPem == nil || pubPem.Type != "PUBLIC KEY" { @@ -45,7 +46,7 @@ func TestSignUsingKeys(t *testing.T) { } pubParsed, err := x509.ParsePKIXPublicKey(pubPem.Bytes) - assert.NoError(t, err) + require.NoError(t, err) // Sign msg := "activity pub is great!" @@ -53,9 +54,9 @@ func TestSignUsingKeys(t *testing.T) { h.Write([]byte(msg)) d := h.Sum(nil) sig, err := rsa.SignPKCS1v15(rand.Reader, privParsed, crypto.SHA256, d) - assert.NoError(t, err) + require.NoError(t, err) // Verify err = rsa.VerifyPKCS1v15(pubParsed.(*rsa.PublicKey), crypto.SHA256, d, sig) - assert.NoError(t, err) + require.NoError(t, err) } diff --git a/modules/util/legacy_test.go b/modules/util/legacy_test.go index b7991bd365..62c2f8af16 100644 --- a/modules/util/legacy_test.go +++ b/modules/util/legacy_test.go @@ -10,6 +10,7 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCopyFile(t *testing.T) { @@ -28,10 +29,10 @@ func TestCopyFile(t *testing.T) { }() err := os.WriteFile(srcFile, testContent, 0o777) - assert.NoError(t, err) + require.NoError(t, err) err = CopyFile(srcFile, dstFile) - assert.NoError(t, err) + require.NoError(t, err) dstContent, err := os.ReadFile(dstFile) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, testContent, dstContent) } diff --git a/modules/util/pack_test.go b/modules/util/pack_test.go index 592c69cd0a..42ada89b81 100644 --- a/modules/util/pack_test.go +++ b/modules/util/pack_test.go @@ -6,7 +6,7 @@ package util import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackAndUnpackData(t *testing.T) { @@ -19,10 +19,10 @@ func TestPackAndUnpackData(t *testing.T) { var f2 float32 data, err := PackData(s, i, f) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, UnpackData(data, &s2, &i2, &f2)) - assert.NoError(t, UnpackData(data, &s2)) - assert.Error(t, UnpackData(data, &i2)) - assert.Error(t, UnpackData(data, &s2, &f2)) + require.NoError(t, UnpackData(data, &s2, &i2, &f2)) + require.NoError(t, UnpackData(data, &s2)) + require.Error(t, UnpackData(data, &i2)) + require.Error(t, UnpackData(data, &s2, &f2)) } diff --git a/modules/util/path_test.go b/modules/util/path_test.go index 6a38bf4ace..3699f052d1 100644 --- a/modules/util/path_test.go +++ b/modules/util/path_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestFileURLToPath(t *testing.T) { @@ -48,9 +49,9 @@ func TestFileURLToPath(t *testing.T) { u, _ := url.Parse(c.url) p, err := FileURLToPath(u) if c.haserror { - assert.Error(t, err, "case %d: should return error", n) + require.Error(t, err, "case %d: should return error", n) } else { - assert.NoError(t, err, "case %d: should not return error", n) + require.NoError(t, err, "case %d: should not return error", n) assert.Equal(t, c.expected, p, "case %d: should be equal", n) } } diff --git a/modules/util/rotatingfilewriter/writer_test.go b/modules/util/rotatingfilewriter/writer_test.go index 88392797b3..5b3b351667 100644 --- a/modules/util/rotatingfilewriter/writer_test.go +++ b/modules/util/rotatingfilewriter/writer_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCompressOldFile(t *testing.T) { @@ -19,9 +20,9 @@ func TestCompressOldFile(t *testing.T) { nonGzip := filepath.Join(tmpDir, "test-nonGzip") f, err := os.OpenFile(fname, os.O_CREATE|os.O_WRONLY, 0o660) - assert.NoError(t, err) + require.NoError(t, err) ng, err := os.OpenFile(nonGzip, os.O_CREATE|os.O_WRONLY, 0o660) - assert.NoError(t, err) + require.NoError(t, err) for i := 0; i < 999; i++ { f.WriteString("This is a test file\n") @@ -31,18 +32,18 @@ func TestCompressOldFile(t *testing.T) { ng.Close() err = compressOldFile(fname, gzip.DefaultCompression) - assert.NoError(t, err) + require.NoError(t, err) _, err = os.Lstat(fname + ".gz") - assert.NoError(t, err) + require.NoError(t, err) f, err = os.Open(fname + ".gz") - assert.NoError(t, err) + require.NoError(t, err) zr, err := gzip.NewReader(f) - assert.NoError(t, err) + require.NoError(t, err) data, err := io.ReadAll(zr) - assert.NoError(t, err) + require.NoError(t, err) original, err := os.ReadFile(nonGzip) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, original, data) } diff --git a/modules/util/util_test.go b/modules/util/util_test.go index de8f065cad..8ed1e32078 100644 --- a/modules/util/util_test.go +++ b/modules/util/util_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/optional" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestURLJoin(t *testing.T) { @@ -122,36 +123,36 @@ func Test_NormalizeEOL(t *testing.T) { func Test_RandomInt(t *testing.T) { randInt, err := CryptoRandomInt(255) - assert.True(t, randInt >= 0) - assert.True(t, randInt <= 255) - assert.NoError(t, err) + assert.GreaterOrEqual(t, randInt, int64(0)) + assert.LessOrEqual(t, randInt, int64(255)) + require.NoError(t, err) } func Test_RandomString(t *testing.T) { str1, err := CryptoRandomString(32) - assert.NoError(t, err) + require.NoError(t, err) matches, err := regexp.MatchString(`^[a-zA-Z0-9]{32}$`, str1) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, matches) str2, err := CryptoRandomString(32) - assert.NoError(t, err) + require.NoError(t, err) matches, err = regexp.MatchString(`^[a-zA-Z0-9]{32}$`, str1) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, matches) assert.NotEqual(t, str1, str2) str3, err := CryptoRandomString(256) - assert.NoError(t, err) + require.NoError(t, err) matches, err = regexp.MatchString(`^[a-zA-Z0-9]{256}$`, str3) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, matches) str4, err := CryptoRandomString(256) - assert.NoError(t, err) + require.NoError(t, err) matches, err = regexp.MatchString(`^[a-zA-Z0-9]{256}$`, str4) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, matches) assert.NotEqual(t, str3, str4) @@ -159,18 +160,18 @@ func Test_RandomString(t *testing.T) { func Test_RandomBytes(t *testing.T) { bytes1, err := CryptoRandomBytes(32) - assert.NoError(t, err) + require.NoError(t, err) bytes2, err := CryptoRandomBytes(32) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, bytes1, bytes2) bytes3, err := CryptoRandomBytes(256) - assert.NoError(t, err) + require.NoError(t, err) bytes4, err := CryptoRandomBytes(256) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, bytes3, bytes4) } @@ -223,20 +224,20 @@ func BenchmarkToUpper(b *testing.B) { } func TestToTitleCase(t *testing.T) { - assert.Equal(t, ToTitleCase(`foo bar baz`), `Foo Bar Baz`) - assert.Equal(t, ToTitleCase(`FOO BAR BAZ`), `Foo Bar Baz`) + assert.Equal(t, `Foo Bar Baz`, ToTitleCase(`foo bar baz`)) + assert.Equal(t, `Foo Bar Baz`, ToTitleCase(`FOO BAR BAZ`)) } func TestToPointer(t *testing.T) { assert.Equal(t, "abc", *ToPointer("abc")) assert.Equal(t, 123, *ToPointer(123)) abc := "abc" - assert.False(t, &abc == ToPointer(abc)) + assert.NotSame(t, &abc, ToPointer(abc)) val123 := 123 - assert.False(t, &val123 == ToPointer(val123)) + assert.NotSame(t, &val123, ToPointer(val123)) } func TestReserveLineBreakForTextarea(t *testing.T) { - assert.Equal(t, ReserveLineBreakForTextarea("test\r\ndata"), "test\ndata") - assert.Equal(t, ReserveLineBreakForTextarea("test\r\ndata\r\n"), "test\ndata\n") + assert.Equal(t, "test\ndata", ReserveLineBreakForTextarea("test\r\ndata")) + assert.Equal(t, "test\ndata\n", ReserveLineBreakForTextarea("test\r\ndata\r\n")) } diff --git a/modules/web/route_test.go b/modules/web/route_test.go index cc0e26a12e..d8015d6e0d 100644 --- a/modules/web/route_test.go +++ b/modules/web/route_test.go @@ -12,6 +12,7 @@ import ( chi "github.com/go-chi/chi/v5" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRoute1(t *testing.T) { @@ -30,7 +31,7 @@ func TestRoute1(t *testing.T) { }) req, err := http.NewRequest("GET", "http://localhost:8000/gitea/gitea/issues", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.EqualValues(t, http.StatusOK, recorder.Code) } @@ -87,25 +88,25 @@ func TestRoute2(t *testing.T) { }) req, err := http.NewRequest("GET", "http://localhost:8000/gitea/gitea/issues", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.EqualValues(t, http.StatusOK, recorder.Code) assert.EqualValues(t, 0, hit) req, err = http.NewRequest("GET", "http://localhost:8000/gitea/gitea/issues/1", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.EqualValues(t, http.StatusOK, recorder.Code) assert.EqualValues(t, 1, hit) req, err = http.NewRequest("GET", "http://localhost:8000/gitea/gitea/issues/1?stop=100", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.EqualValues(t, http.StatusOK, recorder.Code) assert.EqualValues(t, 100, hit) req, err = http.NewRequest("GET", "http://localhost:8000/gitea/gitea/issues/1/view", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.EqualValues(t, http.StatusOK, recorder.Code) assert.EqualValues(t, 2, hit) @@ -147,31 +148,31 @@ func TestRoute3(t *testing.T) { }) req, err := http.NewRequest("GET", "http://localhost:8000/api/v1/repos/gitea/gitea/branch_protections", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.EqualValues(t, http.StatusOK, recorder.Code) assert.EqualValues(t, 0, hit) req, err = http.NewRequest("POST", "http://localhost:8000/api/v1/repos/gitea/gitea/branch_protections", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.EqualValues(t, http.StatusOK, recorder.Code, http.StatusOK) assert.EqualValues(t, 1, hit) req, err = http.NewRequest("GET", "http://localhost:8000/api/v1/repos/gitea/gitea/branch_protections/master", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.EqualValues(t, http.StatusOK, recorder.Code) assert.EqualValues(t, 2, hit) req, err = http.NewRequest("PATCH", "http://localhost:8000/api/v1/repos/gitea/gitea/branch_protections/master", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.EqualValues(t, http.StatusOK, recorder.Code) assert.EqualValues(t, 3, hit) req, err = http.NewRequest("DELETE", "http://localhost:8000/api/v1/repos/gitea/gitea/branch_protections/master", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.EqualValues(t, http.StatusOK, recorder.Code) assert.EqualValues(t, 4, hit) diff --git a/modules/web/routemock_test.go b/modules/web/routemock_test.go index 04c6d1d82e..cd99b99323 100644 --- a/modules/web/routemock_test.go +++ b/modules/web/routemock_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRouteMock(t *testing.T) { @@ -31,7 +32,7 @@ func TestRouteMock(t *testing.T) { // normal request recorder := httptest.NewRecorder() req, err := http.NewRequest("GET", "http://localhost:8000/foo", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.Len(t, recorder.Header(), 3) assert.EqualValues(t, "m1", recorder.Header().Get("X-Test-Middleware1")) @@ -46,7 +47,7 @@ func TestRouteMock(t *testing.T) { }) recorder = httptest.NewRecorder() req, err = http.NewRequest("GET", "http://localhost:8000/foo", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.Len(t, recorder.Header(), 2) assert.EqualValues(t, "m1", recorder.Header().Get("X-Test-Middleware1")) @@ -60,7 +61,7 @@ func TestRouteMock(t *testing.T) { }) recorder = httptest.NewRecorder() req, err = http.NewRequest("GET", "http://localhost:8000/foo", nil) - assert.NoError(t, err) + require.NoError(t, err) r.ServeHTTP(recorder, req) assert.Len(t, recorder.Header(), 3) assert.EqualValues(t, "m1", recorder.Header().Get("X-Test-Middleware1")) diff --git a/routers/private/hook_post_receive_test.go b/routers/private/hook_post_receive_test.go index 658557d3cf..bfd647e365 100644 --- a/routers/private/hook_post_receive_test.go +++ b/routers/private/hook_post_receive_test.go @@ -17,18 +17,19 @@ import ( "code.gitea.io/gitea/services/contexttest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestHandlePullRequestMerging(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) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) + require.NoError(t, err) + require.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) err = pull_model.ScheduleAutoMerge(db.DefaultContext, user1, pr.ID, repo_model.MergeStyleSquash, "squash merge a pr") - assert.NoError(t, err) + require.NoError(t, err) autoMerge := unittest.AssertExistsAndLoadBean(t, &pull_model.AutoMerge{PullID: pr.ID}) @@ -39,9 +40,9 @@ func TestHandlePullRequestMerging(t *testing.T) { }, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, []*repo_module.PushUpdateOptions{ {NewCommitID: "01234567"}, }) - assert.Equal(t, 0, len(resp.Body.String())) + assert.Empty(t, resp.Body.String()) pr, err = issues_model.GetPullRequestByID(db.DefaultContext, pr.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, pr.HasMerged) assert.EqualValues(t, "01234567", pr.MergedCommitID) diff --git a/routers/private/hook_verification_test.go b/routers/private/hook_verification_test.go index 04445b8eaf..5f0d1d0f4f 100644 --- a/routers/private/hook_verification_test.go +++ b/routers/private/hook_verification_test.go @@ -10,7 +10,7 @@ import ( "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var testReposDir = "tests/repos/" @@ -20,10 +20,10 @@ func TestVerifyCommits(t *testing.T) { gitRepo, err := git.OpenRepository(context.Background(), testReposDir+"repo1_hook_verification") defer gitRepo.Close() - assert.NoError(t, err) + require.NoError(t, err) objectFormat, err := gitRepo.GetObjectFormat() - assert.NoError(t, err) + require.NoError(t, err) testCases := []struct { base, head string @@ -38,9 +38,9 @@ func TestVerifyCommits(t *testing.T) { for _, tc := range testCases { err = verifyCommits(tc.base, tc.head, gitRepo, nil) if tc.verified { - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.Error(t, err) + require.Error(t, err) } } } diff --git a/routers/web/admin/users_test.go b/routers/web/admin/users_test.go index f6f9237858..ae3b130101 100644 --- a/routers/web/admin/users_test.go +++ b/routers/web/admin/users_test.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/services/forms" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewUserPost_MustChangePassword(t *testing.T) { @@ -48,7 +49,7 @@ func TestNewUserPost_MustChangePassword(t *testing.T) { u, err := user_model.GetUserByName(ctx, username) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, username, u.Name) assert.Equal(t, email, u.Email) assert.True(t, u.MustChangePassword) @@ -85,7 +86,7 @@ func TestNewUserPost_MustChangePasswordFalse(t *testing.T) { u, err := user_model.GetUserByName(ctx, username) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, username, u.Name) assert.Equal(t, email, u.Email) assert.False(t, u.MustChangePassword) @@ -152,7 +153,7 @@ func TestNewUserPost_VisibilityDefaultPublic(t *testing.T) { u, err := user_model.GetUserByName(ctx, username) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, username, u.Name) assert.Equal(t, email, u.Email) // As default user visibility @@ -191,7 +192,7 @@ func TestNewUserPost_VisibilityPrivate(t *testing.T) { u, err := user_model.GetUserByName(ctx, username) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, username, u.Name) assert.Equal(t, email, u.Email) // As default user visibility diff --git a/routers/web/auth/oauth_test.go b/routers/web/auth/oauth_test.go index 3726daee93..5a4a646577 100644 --- a/routers/web/auth/oauth_test.go +++ b/routers/web/auth/oauth_test.go @@ -15,11 +15,12 @@ import ( "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func createAndParseToken(t *testing.T, grant *auth.OAuth2Grant) *oauth2.OIDCToken { signingKey, err := oauth2.CreateJWTSigningKey("HS256", make([]byte, 32)) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, signingKey) response, terr := newAccessTokenResponse(db.DefaultContext, grant, signingKey, signingKey) @@ -31,7 +32,7 @@ func createAndParseToken(t *testing.T, grant *auth.OAuth2Grant) *oauth2.OIDCToke assert.Equal(t, signingKey.SigningMethod().Alg(), token.Method.Alg()) return signingKey.VerifyKey(), nil }) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, parsedToken.Valid) oidcToken, ok := parsedToken.Claims.(*oauth2.OIDCToken) @@ -42,10 +43,10 @@ func createAndParseToken(t *testing.T, grant *auth.OAuth2Grant) *oauth2.OIDCToke } func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) grants, err := auth.GetOAuth2GrantsByUserID(db.DefaultContext, 3) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, grants, 1) // Scopes: openid @@ -61,7 +62,7 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) grants, err = auth.GetOAuth2GrantsByUserID(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, grants, 1) // Scopes: openid profile email @@ -97,6 +98,6 @@ func TestNewAccessTokenResponse_OIDCToken(t *testing.T) { func TestEncodeCodeChallenge(t *testing.T) { // test vector from https://datatracker.ietf.org/doc/html/rfc7636#page-18 codeChallenge, err := encodeCodeChallenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", codeChallenge) } diff --git a/routers/web/repo/issue_label_test.go b/routers/web/repo/issue_label_test.go index 93fc72300b..2b4915e855 100644 --- a/routers/web/repo/issue_label_test.go +++ b/routers/web/repo/issue_label_test.go @@ -17,6 +17,7 @@ import ( "code.gitea.io/gitea/services/forms" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func int64SliceToCommaSeparated(a []int64) string { @@ -32,7 +33,7 @@ func int64SliceToCommaSeparated(a []int64) string { func TestInitializeLabels(t *testing.T) { unittest.PrepareTestEnv(t) - assert.NoError(t, repository.LoadRepoConfig()) + require.NoError(t, repository.LoadRepoConfig()) ctx, _ := contexttest.MockContext(t, "user2/repo1/labels/initialize") contexttest.LoadUser(t, ctx, 2) contexttest.LoadRepo(t, ctx, 2) diff --git a/routers/web/repo/pull_review_test.go b/routers/web/repo/pull_review_test.go index 70f6a0e055..329e83fe4b 100644 --- a/routers/web/repo/pull_review_test.go +++ b/routers/web/repo/pull_review_test.go @@ -17,6 +17,7 @@ import ( "code.gitea.io/gitea/services/pull" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRenderConversation(t *testing.T) { @@ -42,14 +43,12 @@ func TestRenderConversation(t *testing.T) { var preparedComment *issues_model.Comment run("prepare", func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) { comment, err := pull.CreateCodeComment(ctx, pr.Issue.Poster, ctx.Repo.GitRepo, pr.Issue, 1, "content", "", false, 0, pr.HeadCommitID, nil) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + comment.Invalidated = true err = issues_model.UpdateCommentInvalidate(ctx, comment) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + preparedComment = comment }) if !assert.NotNil(t, preparedComment) { @@ -80,9 +79,9 @@ func TestRenderConversation(t *testing.T) { reviews, err := issues_model.FindReviews(db.DefaultContext, issues_model.FindReviewOptions{ IssueID: 2, }) - assert.NoError(t, err) + require.NoError(t, err) for _, r := range reviews { - assert.NoError(t, issues_model.DeleteReview(db.DefaultContext, r)) + require.NoError(t, issues_model.DeleteReview(db.DefaultContext, r)) } ctx.Data["ShowOutdatedComments"] = true renderConversation(ctx, preparedComment, "diff") @@ -93,9 +92,9 @@ func TestRenderConversation(t *testing.T) { reviews, err := issues_model.FindReviews(db.DefaultContext, issues_model.FindReviewOptions{ IssueID: 2, }) - assert.NoError(t, err) + require.NoError(t, err) for _, r := range reviews { - assert.NoError(t, issues_model.DeleteReview(db.DefaultContext, r)) + require.NoError(t, issues_model.DeleteReview(db.DefaultContext, r)) } ctx.Data["ShowOutdatedComments"] = true renderConversation(ctx, preparedComment, "timeline") diff --git a/routers/web/repo/release_test.go b/routers/web/repo/release_test.go index 7ebea4c3fb..5c7b6e2e8f 100644 --- a/routers/web/repo/release_test.go +++ b/routers/web/repo/release_test.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/services/forms" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNewReleasePost(t *testing.T) { @@ -79,12 +80,12 @@ func TestCalReleaseNumCommitsBehind(t *testing.T) { IncludeDrafts: ctx.Repo.CanWrite(unit.TypeReleases), RepoID: ctx.Repo.Repository.ID, }) - assert.NoError(t, err) + require.NoError(t, err) countCache := make(map[string]int64) for _, release := range releases { err := calReleaseNumCommitsBehind(ctx.Repo, release, countCache) - assert.NoError(t, err) + require.NoError(t, err) } type computedFields struct { diff --git a/routers/web/repo/setting/settings_test.go b/routers/web/repo/setting/settings_test.go index b771113841..0c8553faea 100644 --- a/routers/web/repo/setting/settings_test.go +++ b/routers/web/repo/setting/settings_test.go @@ -22,6 +22,7 @@ import ( repo_service "code.gitea.io/gitea/services/repository" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func createSSHAuthorizedKeysTmpPath(t *testing.T) func() { @@ -126,7 +127,7 @@ func TestCollaborationPost(t *testing.T) { assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) exists, err := repo_model.IsCollaborator(ctx, re.ID, 4) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exists) } @@ -186,7 +187,7 @@ func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) { assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) exists, err := repo_model.IsCollaborator(ctx, re.ID, 4) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exists) // Try adding the same collaborator again diff --git a/routers/web/repo/wiki_test.go b/routers/web/repo/wiki_test.go index 719cca3049..00a35a5da0 100644 --- a/routers/web/repo/wiki_test.go +++ b/routers/web/repo/wiki_test.go @@ -19,6 +19,7 @@ import ( wiki_service "code.gitea.io/gitea/services/wiki" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -28,12 +29,12 @@ const ( func wikiEntry(t *testing.T, repo *repo_model.Repository, wikiName wiki_service.WebPath) *git.TreeEntry { wikiRepo, err := gitrepo.OpenWikiRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer wikiRepo.Close() commit, err := wikiRepo.GetBranchCommit("master") - assert.NoError(t, err) + require.NoError(t, err) entries, err := commit.ListEntries() - assert.NoError(t, err) + require.NoError(t, err) for _, entry := range entries { if entry.Name() == wiki_service.WebPathToGitPath(wikiName) { return entry @@ -48,10 +49,10 @@ func wikiContent(t *testing.T, repo *repo_model.Repository, wikiName wiki_servic return "" } reader, err := entry.Blob().DataAsync() - assert.NoError(t, err) + require.NoError(t, err) defer reader.Close() bytes, err := io.ReadAll(reader) - assert.NoError(t, err) + require.NoError(t, err) return string(bytes) } @@ -127,7 +128,7 @@ func TestNewWikiPost(t *testing.T) { NewWikiPost(ctx) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assertWikiExists(t, ctx.Repo.Repository, wiki_service.UserTitleToWebPath("", title)) - assert.Equal(t, wikiContent(t, ctx.Repo.Repository, wiki_service.UserTitleToWebPath("", title)), content) + assert.Equal(t, content, wikiContent(t, ctx.Repo.Repository, wiki_service.UserTitleToWebPath("", title))) } } @@ -179,7 +180,7 @@ func TestEditWikiPost(t *testing.T) { EditWikiPost(ctx) assert.EqualValues(t, http.StatusSeeOther, ctx.Resp.Status()) assertWikiExists(t, ctx.Repo.Repository, wiki_service.UserTitleToWebPath("", title)) - assert.Equal(t, wikiContent(t, ctx.Repo.Repository, wiki_service.UserTitleToWebPath("", title)), content) + assert.Equal(t, content, wikiContent(t, ctx.Repo.Repository, wiki_service.UserTitleToWebPath("", title))) if title != "Home" { assertWikiNotExists(t, ctx.Repo.Repository, "Home") } diff --git a/routers/web/user/home_test.go b/routers/web/user/home_test.go index a59afce12c..f6e91b6219 100644 --- a/routers/web/user/home_test.go +++ b/routers/web/user/home_test.go @@ -17,12 +17,13 @@ import ( "code.gitea.io/gitea/services/contexttest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestArchivedIssues(t *testing.T) { // Arrange setting.UI.IssuePagingNum = 1 - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) ctx, _ := contexttest.MockContext(t, "issues") contexttest.LoadUser(t, ctx, 30) @@ -53,7 +54,7 @@ func TestArchivedIssues(t *testing.T) { func TestIssues(t *testing.T) { setting.UI.IssuePagingNum = 1 - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) ctx, _ := contexttest.MockContext(t, "issues") contexttest.LoadUser(t, ctx, 2) @@ -67,7 +68,7 @@ func TestIssues(t *testing.T) { func TestPulls(t *testing.T) { setting.UI.IssuePagingNum = 20 - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) ctx, _ := contexttest.MockContext(t, "pulls") contexttest.LoadUser(t, ctx, 2) @@ -80,7 +81,7 @@ func TestPulls(t *testing.T) { func TestMilestones(t *testing.T) { setting.UI.IssuePagingNum = 1 - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) ctx, _ := contexttest.MockContext(t, "milestones") contexttest.LoadUser(t, ctx, 2) @@ -99,7 +100,7 @@ func TestMilestones(t *testing.T) { func TestMilestonesForSpecificRepo(t *testing.T) { setting.UI.IssuePagingNum = 1 - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) ctx, _ := contexttest.MockContext(t, "milestones") contexttest.LoadUser(t, ctx, 2) @@ -123,17 +124,17 @@ func TestDashboardPagination(t *testing.T) { setting.AppSubURL = "/SubPath" out, err := ctx.RenderToHTML("base/paginate", map[string]any{"Link": setting.AppSubURL, "Page": page}) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, out, ``) setting.AppSubURL = "" out, err = ctx.RenderToHTML("base/paginate", map[string]any{"Link": setting.AppSubURL, "Page": page}) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, out, ``) } func TestOrgLabels(t *testing.T) { - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) ctx, _ := contexttest.MockContext(t, "org/org3/issues") contexttest.LoadUser(t, ctx, 2) diff --git a/services/actions/auth_test.go b/services/actions/auth_test.go index 12db2bae56..1400e61f47 100644 --- a/services/actions/auth_test.go +++ b/services/actions/auth_test.go @@ -12,45 +12,46 @@ import ( "github.com/golang-jwt/jwt/v5" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCreateAuthorizationToken(t *testing.T) { var taskID int64 = 23 token, err := CreateAuthorizationToken(taskID, 1, 2) - assert.Nil(t, err) + require.NoError(t, err) assert.NotEqual(t, "", token) claims := jwt.MapClaims{} _, err = jwt.ParseWithClaims(token, claims, func(t *jwt.Token) (any, error) { return setting.GetGeneralTokenSigningSecret(), nil }) - assert.Nil(t, err) + require.NoError(t, err) scp, ok := claims["scp"] assert.True(t, ok, "Has scp claim in jwt token") assert.Contains(t, scp, "Actions.Results:1:2") taskIDClaim, ok := claims["TaskID"] assert.True(t, ok, "Has TaskID claim in jwt token") - assert.Equal(t, float64(taskID), taskIDClaim, "Supplied taskid must match stored one") + assert.InDelta(t, float64(taskID), taskIDClaim, 0, "Supplied taskid must match stored one") acClaim, ok := claims["ac"] assert.True(t, ok, "Has ac claim in jwt token") ac, ok := acClaim.(string) assert.True(t, ok, "ac claim is a string for buildx gha cache") scopes := []actionsCacheScope{} err = json.Unmarshal([]byte(ac), &scopes) - assert.NoError(t, err, "ac claim is a json list for buildx gha cache") + require.NoError(t, err, "ac claim is a json list for buildx gha cache") assert.GreaterOrEqual(t, len(scopes), 1, "Expected at least one action cache scope for buildx gha cache") } func TestParseAuthorizationToken(t *testing.T) { var taskID int64 = 23 token, err := CreateAuthorizationToken(taskID, 1, 2) - assert.Nil(t, err) + require.NoError(t, err) assert.NotEqual(t, "", token) headers := http.Header{} headers.Set("Authorization", "Bearer "+token) rTaskID, err := ParseAuthorizationToken(&http.Request{ Header: headers, }) - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, taskID, rTaskID) } @@ -59,6 +60,6 @@ func TestParseAuthorizationTokenNoAuthHeader(t *testing.T) { rTaskID, err := ParseAuthorizationToken(&http.Request{ Header: headers, }) - assert.Nil(t, err) + require.NoError(t, err) assert.Equal(t, int64(0), rTaskID) } diff --git a/services/actions/notifier_helper_test.go b/services/actions/notifier_helper_test.go index 3c23414b8e..0fa40c0168 100644 --- a/services/actions/notifier_helper_test.go +++ b/services/actions/notifier_helper_test.go @@ -12,10 +12,11 @@ import ( webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_SkipPullRequestEvent(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repoID := int64(1) commitSHA := "1234" diff --git a/services/asymkey/ssh_key_test.go b/services/asymkey/ssh_key_test.go index fbd5d13ab2..d667a02557 100644 --- a/services/asymkey/ssh_key_test.go +++ b/services/asymkey/ssh_key_test.go @@ -13,10 +13,11 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAddLdapSSHPublicKeys(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) s := &auth.Source{ID: 1} @@ -71,7 +72,7 @@ ssh-dss AAAAB3NzaC1kc3MAAACBAOChCC7lf6Uo9n7BmZ6M8St19PZf4Tn59NriyboW2x/DZuYAz3ib OwnerID: user.ID, LoginSourceID: s.ID, }) - assert.NoError(t, err) + require.NoError(t, err) if err != nil { continue } diff --git a/services/attachment/attachment_test.go b/services/attachment/attachment_test.go index 142bcfe629..fe861c6dc8 100644 --- a/services/attachment/attachment_test.go +++ b/services/attachment/attachment_test.go @@ -16,6 +16,7 @@ import ( _ "code.gitea.io/gitea/models/actions" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -23,13 +24,13 @@ func TestMain(m *testing.M) { } func TestUploadAttachment(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) fPath := "./attachment_test.go" f, err := os.Open(fPath) - assert.NoError(t, err) + require.NoError(t, err) defer f.Close() attach, err := NewAttachment(db.DefaultContext, &repo_model.Attachment{ @@ -37,10 +38,10 @@ func TestUploadAttachment(t *testing.T) { UploaderID: user.ID, Name: filepath.Base(fPath), }, f, -1) - assert.NoError(t, err) + require.NoError(t, err) attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, attach.UUID) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, user.ID, attachment.UploaderID) assert.Equal(t, int64(0), attachment.DownloadCount) } diff --git a/services/auth/source/oauth2/source_sync_test.go b/services/auth/source/oauth2/source_sync_test.go index e2f04bcb25..746df82055 100644 --- a/services/auth/source/oauth2/source_sync_test.go +++ b/services/auth/source/oauth2/source_sync_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 TestSource(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) source := &Source{ Provider: "fake", @@ -37,7 +38,7 @@ func TestSource(t *testing.T) { } err := user_model.CreateUser(context.Background(), user, &user_model.CreateUserOverwriteOptions{}) - assert.NoError(t, err) + require.NoError(t, err) e := &user_model.ExternalLoginUser{ ExternalID: "external", @@ -46,15 +47,15 @@ func TestSource(t *testing.T) { RefreshToken: "valid", } err = user_model.LinkExternalToUser(context.Background(), user, e) - assert.NoError(t, err) + require.NoError(t, err) provider, err := createProvider(source.authSource.Name, source) - assert.NoError(t, err) + require.NoError(t, err) t.Run("refresh", func(t *testing.T) { t.Run("valid", func(t *testing.T) { err := source.refresh(context.Background(), provider, e) - assert.NoError(t, err) + require.NoError(t, err) e := &user_model.ExternalLoginUser{ ExternalID: e.ExternalID, @@ -62,13 +63,13 @@ func TestSource(t *testing.T) { } ok, err := user_model.GetExternalLogin(context.Background(), e) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, ok) - assert.Equal(t, e.RefreshToken, "refresh") - assert.Equal(t, e.AccessToken, "token") + assert.Equal(t, "refresh", e.RefreshToken) + assert.Equal(t, "token", e.AccessToken) u, err := user_model.GetUserByID(context.Background(), user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, u.IsActive) }) @@ -79,7 +80,7 @@ func TestSource(t *testing.T) { LoginSourceID: user.LoginSource, RefreshToken: "expired", }) - assert.NoError(t, err) + require.NoError(t, err) e := &user_model.ExternalLoginUser{ ExternalID: e.ExternalID, @@ -87,13 +88,13 @@ func TestSource(t *testing.T) { } ok, err := user_model.GetExternalLogin(context.Background(), e) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, ok) - assert.Equal(t, e.RefreshToken, "") - assert.Equal(t, e.AccessToken, "") + assert.Equal(t, "", e.RefreshToken) + assert.Equal(t, "", e.AccessToken) u, err := user_model.GetUserByID(context.Background(), user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, u.IsActive) }) }) diff --git a/services/context/api_test.go b/services/context/api_test.go index 911a49949e..6064fee1c3 100644 --- a/services/context/api_test.go +++ b/services/context/api_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGenAPILinks(t *testing.T) { @@ -38,7 +39,7 @@ func TestGenAPILinks(t *testing.T) { for req, response := range kases { u, err := url.Parse(setting.AppURL + req) - assert.NoError(t, err) + require.NoError(t, err) p := u.Query().Get("page") curPage, _ := strconv.Atoi(p) diff --git a/services/contexttest/context_tests.go b/services/contexttest/context_tests.go index 073af213a2..a4cc967a57 100644 --- a/services/contexttest/context_tests.go +++ b/services/contexttest/context_tests.go @@ -28,6 +28,7 @@ import ( "github.com/go-chi/chi/v5" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func mockRequest(t *testing.T, reqPath string) *http.Request { @@ -37,7 +38,7 @@ func mockRequest(t *testing.T, reqPath string) *http.Request { path = reqPath } requestURL, err := url.Parse(path) - assert.NoError(t, err) + require.NoError(t, err) req := &http.Request{Method: method, URL: requestURL, Form: maps.Clone(requestURL.Query()), Header: http.Header{}} req = req.WithContext(middleware.WithContextData(req.Context())) return req @@ -117,10 +118,10 @@ func LoadRepo(t *testing.T, ctx gocontext.Context, repoID int64) { repo.Repository = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) var err error repo.Owner, err = user_model.GetUserByID(ctx, repo.Repository.OwnerID) - assert.NoError(t, err) + require.NoError(t, err) repo.RepoLink = repo.Repository.Link() repo.Permission, err = access_model.GetUserRepoPermission(ctx, repo.Repository, doer) - assert.NoError(t, err) + require.NoError(t, err) } // LoadRepoCommit loads a repo's commit into a test context. @@ -136,14 +137,14 @@ func LoadRepoCommit(t *testing.T, ctx gocontext.Context) { } gitRepo, err := gitrepo.OpenRepository(ctx, repo.Repository) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() branch, err := gitRepo.GetHEADBranch() - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, branch) if branch != nil { repo.Commit, err = gitRepo.GetBranchCommit(branch.Name) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -176,10 +177,10 @@ func LoadOrganization(t *testing.T, ctx gocontext.Context, orgID int64) { // LoadGitRepo load a git repo into a test context. Requires that ctx.Repo has // already been populated. func LoadGitRepo(t *testing.T, ctx *context.Context) { - assert.NoError(t, ctx.Repo.Repository.LoadOwner(ctx)) + require.NoError(t, ctx.Repo.Repository.LoadOwner(ctx)) var err error ctx.Repo.GitRepo, err = gitrepo.OpenRepository(ctx, ctx.Repo.Repository) - assert.NoError(t, err) + require.NoError(t, err) } type MockRender struct{} diff --git a/services/convert/git_commit_test.go b/services/convert/git_commit_test.go index 73cb5e8c71..68d1b05168 100644 --- a/services/convert/git_commit_test.go +++ b/services/convert/git_commit_test.go @@ -14,10 +14,11 @@ import ( "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestToCommitMeta(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) headRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) sha1 := git.Sha1ObjectFormat signature := &git.Signature{Name: "Test Signature", Email: "test@email.com", When: time.Unix(0, 0)} diff --git a/services/convert/issue_test.go b/services/convert/issue_test.go index 4d780f3f00..0aeb3e5612 100644 --- a/services/convert/issue_test.go +++ b/services/convert/issue_test.go @@ -16,10 +16,11 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLabel_ToLabel(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: label.RepoID}) assert.Equal(t, &api.Label{ diff --git a/services/convert/pull_test.go b/services/convert/pull_test.go index 66c7313f7d..1339ed5cc0 100644 --- a/services/convert/pull_test.go +++ b/services/convert/pull_test.go @@ -17,15 +17,16 @@ import ( "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPullRequest_APIFormat(t *testing.T) { // with HeadRepo - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) headRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadAttributes(db.DefaultContext)) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + require.NoError(t, pr.LoadAttributes(db.DefaultContext)) + require.NoError(t, pr.LoadIssue(db.DefaultContext)) apiPullRequest := ToAPIPullRequest(git.DefaultContext, pr, nil) assert.NotNil(t, apiPullRequest) assert.EqualValues(t, &structs.PRBranchInfo{ @@ -38,8 +39,8 @@ func TestPullRequest_APIFormat(t *testing.T) { // withOut HeadRepo pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) - assert.NoError(t, pr.LoadAttributes(db.DefaultContext)) + require.NoError(t, pr.LoadIssue(db.DefaultContext)) + require.NoError(t, pr.LoadAttributes(db.DefaultContext)) // simulate fork deletion pr.HeadRepo = nil pr.HeadRepoID = 100000 @@ -50,7 +51,7 @@ func TestPullRequest_APIFormat(t *testing.T) { } func TestPullReviewList(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) t.Run("Pending review", func(t *testing.T) { reviewer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -59,18 +60,18 @@ func TestPullReviewList(t *testing.T) { t.Run("Anonymous", func(t *testing.T) { prList, err := ToPullReviewList(db.DefaultContext, rl, nil) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, prList) }) t.Run("Reviewer", func(t *testing.T) { prList, err := ToPullReviewList(db.DefaultContext, rl, reviewer) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, prList, 1) }) t.Run("Admin", func(t *testing.T) { adminUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{IsAdmin: true}, unittest.Cond("id != ?", reviewer.ID)) prList, err := ToPullReviewList(db.DefaultContext, rl, adminUser) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, prList, 1) }) }) diff --git a/services/convert/release_test.go b/services/convert/release_test.go index 201b27e16d..2e40bb9cdd 100644 --- a/services/convert/release_test.go +++ b/services/convert/release_test.go @@ -11,10 +11,11 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRelease_ToRelease(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) release1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Release{ID: 1}) diff --git a/services/convert/user_test.go b/services/convert/user_test.go index 4b1effc7aa..0f0b520c9b 100644 --- a/services/convert/user_test.go +++ b/services/convert/user_test.go @@ -12,10 +12,11 @@ import ( api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUser_ToUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1, IsAdmin: true}) diff --git a/services/cron/tasks_test.go b/services/cron/tasks_test.go index 979371a022..9b969a69a9 100644 --- a/services/cron/tasks_test.go +++ b/services/cron/tasks_test.go @@ -9,10 +9,11 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAddTaskToScheduler(t *testing.T) { - assert.Len(t, scheduler.Jobs(), 0) + assert.Empty(t, scheduler.Jobs()) defer scheduler.Clear() // no seconds @@ -22,7 +23,7 @@ func TestAddTaskToScheduler(t *testing.T) { Schedule: "5 4 * * *", }, }) - assert.NoError(t, err) + require.NoError(t, err) jobs := scheduler.Jobs() assert.Len(t, jobs, 1) assert.Equal(t, "task 1", jobs[0].Tags()[0]) @@ -35,7 +36,7 @@ func TestAddTaskToScheduler(t *testing.T) { Schedule: "30 5 4 * * *", }, }) - assert.NoError(t, err) + require.NoError(t, err) jobs = scheduler.Jobs() // the item order is not guaranteed, so we need to sort it before "assert" sort.Slice(jobs, func(i, j int) bool { return jobs[i].Tags()[0] < jobs[j].Tags()[0] diff --git a/services/f3/driver/main_test.go b/services/f3/driver/main_test.go index 0d3d3d3cec..8505b69b7e 100644 --- a/services/f3/driver/main_test.go +++ b/services/f3/driver/main_test.go @@ -17,11 +17,11 @@ import ( _ "code.gitea.io/gitea/services/f3/driver/tests" tests_f3 "code.forgejo.org/f3/gof3/v3/tree/tests/f3" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestF3(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) tests_f3.ForgeCompliance(t, driver_options.Name) } diff --git a/services/f3/util/logger_test.go b/services/f3/util/logger_test.go index d16c688bb0..db880aa439 100644 --- a/services/f3/util/logger_test.go +++ b/services/f3/util/logger_test.go @@ -78,12 +78,12 @@ func testLoggerCase(t *testing.T, level logger.Level, loggerFunc func(logger.Mes assert.True(t, logFiltered[i], filtered[i]) if moreVerbose != nil { i++ - require.True(t, len(logFiltered) > i) + require.Greater(t, len(logFiltered), i) assert.False(t, logFiltered[i], filtered[i]) } if lessVerbose != nil { i++ - require.True(t, len(logFiltered) > i) + require.Greater(t, len(logFiltered), i) assert.True(t, logFiltered[i], filtered[i]) } } diff --git a/services/feed/action_test.go b/services/feed/action_test.go index e1b071d8f6..404d89c7b8 100644 --- a/services/feed/action_test.go +++ b/services/feed/action_test.go @@ -15,7 +15,7 @@ import ( _ "code.gitea.io/gitea/models/actions" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -23,7 +23,7 @@ func TestMain(m *testing.M) { } func TestRenameRepoAction(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID}) diff --git a/services/forgejo/sanity_test.go b/services/forgejo/sanity_test.go index 29ed3bbfff..657f7e2720 100644 --- a/services/forgejo/sanity_test.go +++ b/services/forgejo/sanity_test.go @@ -11,21 +11,21 @@ import ( "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/setting" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestForgejo_PreMigrationSanityChecks(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ctx := db.DefaultContext e := db.GetEngine(ctx) - assert.NoError(t, PreMigrationSanityChecks(e, ForgejoV4DatabaseVersion, configFixture(t, ""))) + require.NoError(t, PreMigrationSanityChecks(e, ForgejoV4DatabaseVersion, configFixture(t, ""))) } func configFixture(t *testing.T, content string) setting.ConfigProvider { config := filepath.Join(t.TempDir(), "app.ini") - assert.NoError(t, os.WriteFile(config, []byte(content), 0o777)) + require.NoError(t, os.WriteFile(config, []byte(content), 0o777)) cfg, err := setting.NewConfigProviderFromFile(config) - assert.NoError(t, err) + require.NoError(t, err) return cfg } diff --git a/services/forgejo/sanity_v1TOv5_0_1Included_test.go b/services/forgejo/sanity_v1TOv5_0_1Included_test.go index 93bca0d2fb..56618ebd5f 100644 --- a/services/forgejo/sanity_v1TOv5_0_1Included_test.go +++ b/services/forgejo/sanity_v1TOv5_0_1Included_test.go @@ -11,11 +11,11 @@ import ( "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/log" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestForgejo_v1TOv5_0_1Included(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) logFatal = func(string, ...any) {} defer func() { @@ -71,7 +71,7 @@ func verifyForgejoV1TOv5_0_1Included(t *testing.T, config, message string) { } { cfg := configFixture(t, testCase.config) semver.SetVersionString(ctx, testCase.semver) - assert.NoError(t, v1TOv5_0_1Included(e, testCase.dbVersion, cfg)) + require.NoError(t, v1TOv5_0_1Included(e, testCase.dbVersion, cfg)) } for _, testCase := range []struct { @@ -110,6 +110,6 @@ func verifyForgejoV1TOv5_0_1Included(t *testing.T, config, message string) { } { cfg := configFixture(t, testCase.config) semver.SetVersionString(ctx, testCase.semver) - assert.ErrorContains(t, v1TOv5_0_1Included(e, testCase.dbVersion, cfg), message) + require.ErrorContains(t, v1TOv5_0_1Included(e, testCase.dbVersion, cfg), message) } } diff --git a/services/gitdiff/csv_test.go b/services/gitdiff/csv_test.go index c006a7c2bd..1dbe616374 100644 --- a/services/gitdiff/csv_test.go +++ b/services/gitdiff/csv_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCSVDiff(t *testing.T) { @@ -212,7 +213,7 @@ c,d,e`, } result, err := CreateCsvDiff(diff.Files[0], baseReader, headReader) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, result, 1, "case %d: should be one section", n) section := result[0] diff --git a/services/gitdiff/gitdiff_test.go b/services/gitdiff/gitdiff_test.go index 8d6c376dce..40285f8119 100644 --- a/services/gitdiff/gitdiff_test.go +++ b/services/gitdiff/gitdiff_test.go @@ -20,6 +20,7 @@ import ( dmp "github.com/sergi/go-diff/diffmatchpatch" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDiffToHTML(t *testing.T) { @@ -595,22 +596,22 @@ func setupDefaultDiff() *Diff { } func TestDiff_LoadCommentsNoOutdated(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}) diff := setupDefaultDiff() - assert.NoError(t, diff.LoadComments(db.DefaultContext, issue, user, false)) + require.NoError(t, diff.LoadComments(db.DefaultContext, issue, user, false)) assert.Len(t, diff.Files[0].Sections[0].Lines[0].Conversations, 2) } func TestDiff_LoadCommentsWithOutdated(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}) diff := setupDefaultDiff() - assert.NoError(t, diff.LoadComments(db.DefaultContext, issue, user, true)) + require.NoError(t, diff.LoadComments(db.DefaultContext, issue, user, true)) assert.Len(t, diff.Files[0].Sections[0].Lines[0].Conversations, 2) assert.Len(t, diff.Files[0].Sections[0].Lines[0].Conversations[0], 2) assert.Len(t, diff.Files[0].Sections[0].Lines[0].Conversations[1], 1) @@ -631,9 +632,8 @@ func TestDiffLine_GetCommentSide(t *testing.T) { func TestGetDiffRangeWithWhitespaceBehavior(t *testing.T) { gitRepo, err := git.OpenRepository(git.DefaultContext, "./testdata/academic-module") - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() for _, behavior := range []git.TrustedCmdArgs{{"-w"}, {"--ignore-space-at-eol"}, {"-b"}, nil} { diffs, err := GetDiff(db.DefaultContext, gitRepo, @@ -645,9 +645,9 @@ func TestGetDiffRangeWithWhitespaceBehavior(t *testing.T) { MaxFiles: setting.Git.MaxGitDiffFiles, WhitespaceBehavior: behavior, }) - assert.NoError(t, err, fmt.Sprintf("Error when diff with %s", behavior)) + require.NoError(t, err, fmt.Sprintf("Error when diff with %s", behavior)) for _, f := range diffs.Files { - assert.True(t, len(f.Sections) > 0, fmt.Sprintf("%s should have sections", f.Name)) + assert.Positive(t, len(f.Sections), fmt.Sprintf("%s should have sections", f.Name)) } } } diff --git a/services/issue/assignee_test.go b/services/issue/assignee_test.go index 38d56f9d9d..2b70b8c8ce 100644 --- a/services/issue/assignee_test.go +++ b/services/issue/assignee_test.go @@ -12,36 +12,37 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDeleteNotPassedAssignee(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) assert.Len(t, issue.Assignees, 1) 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) // Check if he got removed isAssigned, err := issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user1) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isAssigned) // Clean everyone err = DeleteNotPassedAssignee(db.DefaultContext, issue, user1, []*user_model.User{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, issue.Assignees) // Reload to check they're gone issue.ResetAttributesLoaded() - assert.NoError(t, issue.LoadAssignees(db.DefaultContext)) + require.NoError(t, issue.LoadAssignees(db.DefaultContext)) assert.Empty(t, issue.Assignees) assert.Empty(t, issue.Assignee) } diff --git a/services/issue/commit_test.go b/services/issue/commit_test.go index 0518803683..c3c3e4c042 100644 --- a/services/issue/commit_test.go +++ b/services/issue/commit_test.go @@ -15,11 +15,11 @@ import ( "code.gitea.io/gitea/modules/repository" "code.gitea.io/gitea/modules/setting" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUpdateIssuesCommit(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pushCommits := []*repository.PushCommit{ { Sha1: "abcdef1", @@ -61,7 +61,7 @@ func TestUpdateIssuesCommit(t *testing.T) { unittest.AssertNotExistsBean(t, commentBean) unittest.AssertNotExistsBean(t, &issues_model.Issue{RepoID: repo.ID, Index: 2}, "is_closed=1") - assert.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) + require.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") unittest.CheckConsistencyFor(t, &activities_model.Action{}) @@ -88,7 +88,7 @@ func TestUpdateIssuesCommit(t *testing.T) { unittest.AssertNotExistsBean(t, commentBean) unittest.AssertNotExistsBean(t, &issues_model.Issue{RepoID: repo.ID, Index: 1}, "is_closed=1") - assert.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, "non-existing-branch")) + require.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, "non-existing-branch")) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertNotExistsBean(t, issueBean, "is_closed=1") unittest.CheckConsistencyFor(t, &activities_model.Action{}) @@ -114,14 +114,14 @@ func TestUpdateIssuesCommit(t *testing.T) { unittest.AssertNotExistsBean(t, commentBean) unittest.AssertNotExistsBean(t, &issues_model.Issue{RepoID: repo.ID, Index: 1}, "is_closed=1") - assert.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) + require.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestUpdateIssuesCommit_Colon(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pushCommits := []*repository.PushCommit{ { Sha1: "abcdef2", @@ -140,13 +140,13 @@ func TestUpdateIssuesCommit_Colon(t *testing.T) { issueBean := &issues_model.Issue{RepoID: repo.ID, Index: 4} unittest.AssertNotExistsBean(t, &issues_model.Issue{RepoID: repo.ID, Index: 2}, "is_closed=1") - assert.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) + require.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestUpdateIssuesCommit_Issue5957(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Test that push to a non-default branch closes an issue. @@ -173,14 +173,14 @@ func TestUpdateIssuesCommit_Issue5957(t *testing.T) { unittest.AssertNotExistsBean(t, commentBean) unittest.AssertNotExistsBean(t, issueBean, "is_closed=1") - assert.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, "non-existing-branch")) + require.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, "non-existing-branch")) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestUpdateIssuesCommit_AnotherRepo(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Test that a push to default branch closes issue in another repo @@ -208,14 +208,14 @@ func TestUpdateIssuesCommit_AnotherRepo(t *testing.T) { unittest.AssertNotExistsBean(t, commentBean) unittest.AssertNotExistsBean(t, issueBean, "is_closed=1") - assert.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) + require.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestUpdateIssuesCommit_AnotherRepo_FullAddress(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Test that a push to default branch closes issue in another repo @@ -243,14 +243,14 @@ func TestUpdateIssuesCommit_AnotherRepo_FullAddress(t *testing.T) { unittest.AssertNotExistsBean(t, commentBean) unittest.AssertNotExistsBean(t, issueBean, "is_closed=1") - assert.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) + require.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertExistsAndLoadBean(t, commentBean) unittest.AssertExistsAndLoadBean(t, issueBean, "is_closed=1") unittest.CheckConsistencyFor(t, &activities_model.Action{}) } func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 10}) // Test that a push with close reference *can not* close issue @@ -293,7 +293,7 @@ func TestUpdateIssuesCommit_AnotherRepoNoPermission(t *testing.T) { unittest.AssertNotExistsBean(t, commentBean) unittest.AssertNotExistsBean(t, commentBean2) unittest.AssertNotExistsBean(t, issueBean, "is_closed=1") - assert.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) + require.NoError(t, UpdateIssuesCommit(db.DefaultContext, user, repo, pushCommits, repo.DefaultBranch)) unittest.AssertNotExistsBean(t, commentBean) unittest.AssertNotExistsBean(t, commentBean2) unittest.AssertNotExistsBean(t, issueBean, "is_closed=1") diff --git a/services/issue/issue_test.go b/services/issue/issue_test.go index 8806cec0e7..a0bb88e387 100644 --- a/services/issue/issue_test.go +++ b/services/issue/issue_test.go @@ -13,6 +13,7 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetRefEndNamesAndURLs(t *testing.T) { @@ -33,10 +34,10 @@ func TestGetRefEndNamesAndURLs(t *testing.T) { } func TestIssue_DeleteIssue(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issueIDs, err := issues_model.GetIssueIDsByRepoID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, issueIDs, 5) issue := &issues_model.Issue{ @@ -45,42 +46,42 @@ func TestIssue_DeleteIssue(t *testing.T) { } err = deleteIssue(db.DefaultContext, issue) - assert.NoError(t, err) + require.NoError(t, err) issueIDs, err = issues_model.GetIssueIDsByRepoID(db.DefaultContext, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, issueIDs, 4) // check attachment removal attachments, err := repo_model.GetAttachmentsByIssueID(db.DefaultContext, 4) - assert.NoError(t, err) + require.NoError(t, err) issue, err = issues_model.GetIssueByID(db.DefaultContext, 4) - assert.NoError(t, err) + require.NoError(t, err) err = deleteIssue(db.DefaultContext, issue) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, attachments, 2) for i := range attachments { attachment, err := repo_model.GetAttachmentByUUID(db.DefaultContext, attachments[i].UUID) - assert.Error(t, err) + require.Error(t, err) assert.True(t, repo_model.IsErrAttachmentNotExist(err)) assert.Nil(t, attachment) } // check issue dependencies user, 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.CreateIssueDependency(db.DefaultContext, user, issue1, issue2) - 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.False(t, left) err = deleteIssue(db.DefaultContext, issue2) - 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) } diff --git a/services/issue/label_test.go b/services/issue/label_test.go index 90608c9e26..b9d26345c1 100644 --- a/services/issue/label_test.go +++ b/services/issue/label_test.go @@ -11,7 +11,7 @@ import ( "code.gitea.io/gitea/models/unittest" user_model "code.gitea.io/gitea/models/user" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIssue_AddLabels(t *testing.T) { @@ -26,14 +26,14 @@ func TestIssue_AddLabels(t *testing.T) { {2, []int64{}, 1}, // pull-request, empty } for _, test := range tests { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID}) labels := make([]*issues_model.Label, len(test.labelIDs)) for i, labelID := range test.labelIDs { labels[i] = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID}) } doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID}) - assert.NoError(t, AddLabels(db.DefaultContext, issue, doer, labels)) + require.NoError(t, AddLabels(db.DefaultContext, issue, doer, labels)) for _, labelID := range test.labelIDs { unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: test.issueID, LabelID: labelID}) } @@ -52,11 +52,11 @@ func TestIssue_AddLabel(t *testing.T) { {2, 1, 2}, // pull-request, already-added label } for _, test := range tests { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID}) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: test.labelID}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID}) - assert.NoError(t, AddLabel(db.DefaultContext, issue, doer, label)) + require.NoError(t, AddLabel(db.DefaultContext, issue, doer, label)) unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: test.issueID, LabelID: test.labelID}) } } diff --git a/services/issue/milestone_test.go b/services/issue/milestone_test.go index 42b910166f..1c06572f8e 100644 --- a/services/issue/milestone_test.go +++ b/services/issue/milestone_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 TestChangeMilestoneAssign(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: 1}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) assert.NotNil(t, issue) @@ -23,7 +24,7 @@ func TestChangeMilestoneAssign(t *testing.T) { oldMilestoneID := issue.MilestoneID issue.MilestoneID = 2 - assert.NoError(t, ChangeMilestoneAssign(db.DefaultContext, issue, doer, oldMilestoneID)) + require.NoError(t, ChangeMilestoneAssign(db.DefaultContext, issue, doer, oldMilestoneID)) unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ IssueID: issue.ID, Type: issues_model.CommentTypeMilestone, diff --git a/services/mailer/incoming/incoming_test.go b/services/mailer/incoming/incoming_test.go index 001374d371..1ff12d0e67 100644 --- a/services/mailer/incoming/incoming_test.go +++ b/services/mailer/incoming/incoming_test.go @@ -10,6 +10,7 @@ import ( "github.com/emersion/go-imap" "github.com/jhillyerd/enmime" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestNotHandleTwice(t *testing.T) { @@ -17,12 +18,12 @@ func TestNotHandleTwice(t *testing.T) { msg := imap.NewMessage(90, []imap.FetchItem{imap.FetchBody}) handled := isAlreadyHandled(handledSet, msg) - assert.Equal(t, false, handled) + assert.False(t, handled) handledSet.AddNum(msg.SeqNum) handled = isAlreadyHandled(handledSet, msg) - assert.Equal(t, true, handled) + assert.True(t, handled) } func TestIsAutomaticReply(t *testing.T) { @@ -74,9 +75,9 @@ func TestIsAutomaticReply(t *testing.T) { b = b.Header(k, v) } root, err := b.Build() - assert.NoError(t, err) + require.NoError(t, err) env, err := enmime.EnvelopeFromPart(root) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, c.Expected, isAutomaticReply(env)) } @@ -102,7 +103,7 @@ func TestGetContentFromMailReader(t *testing.T) { "--message-boundary--\r\n" env, err := enmime.ReadEnvelope(strings.NewReader(mailString)) - assert.NoError(t, err) + require.NoError(t, err) content := getContentFromMailReader(env) assert.Equal(t, "mail content", content.Content) assert.Len(t, content.Attachments, 1) @@ -139,7 +140,7 @@ func TestGetContentFromMailReader(t *testing.T) { "--message-boundary--\r\n" env, err = enmime.ReadEnvelope(strings.NewReader(mailString)) - assert.NoError(t, err) + require.NoError(t, err) content = getContentFromMailReader(env) assert.Equal(t, "mail content\n--\nattachment content", content.Content) assert.Len(t, content.Attachments, 2) @@ -161,7 +162,7 @@ func TestGetContentFromMailReader(t *testing.T) { "--message-boundary--\r\n" env, err = enmime.ReadEnvelope(strings.NewReader(mailString)) - assert.NoError(t, err) + require.NoError(t, err) content = getContentFromMailReader(env) assert.Equal(t, "mail content", content.Content) assert.Empty(t, content.Attachments) @@ -182,9 +183,9 @@ func TestGetContentFromMailReader(t *testing.T) { "--message-boundary--\r\n" env, err = enmime.ReadEnvelope(strings.NewReader(mailString)) - assert.NoError(t, err) + require.NoError(t, err) content = getContentFromMailReader(env) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "mail content without signature", content.Content) assert.Empty(t, content.Attachments) } diff --git a/services/mailer/mail_admin_new_user_test.go b/services/mailer/mail_admin_new_user_test.go index 6868e9eb20..54ffcac859 100644 --- a/services/mailer/mail_admin_new_user_test.go +++ b/services/mailer/mail_admin_new_user_test.go @@ -56,7 +56,7 @@ func TestAdminNotificationMail_test(t *testing.T) { called := false defer MockMailSettings(func(msgs ...*Message) { - assert.Equal(t, len(msgs), 1, "Test provides only one admin user, so only one email must be sent") + assert.Len(t, msgs, 1, "Test provides only one admin user, so only one email must be sent") assert.Equal(t, msgs[0].To, users[0].Email, "checks if the recipient is the admin of the instance") manageUserURL := setting.AppURL + "admin/users/" + strconv.FormatInt(users[1].ID, 10) assert.Contains(t, msgs[0].Body, manageUserURL) diff --git a/services/mailer/mail_test.go b/services/mailer/mail_test.go index 78798bb9f9..1a9bbc9f16 100644 --- a/services/mailer/mail_test.go +++ b/services/mailer/mail_test.go @@ -26,6 +26,7 @@ import ( "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const subjectTpl = ` @@ -51,12 +52,12 @@ const bodyTpl = ` ` func prepareMailerTest(t *testing.T) (doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) doer = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1, Owner: doer}) issue = unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1, Repo: repo, Poster: doer}) - assert.NoError(t, issue.LoadRepo(db.DefaultContext)) + require.NoError(t, issue.LoadRepo(db.DefaultContext)) comment = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 2, Issue: issue}) return doer, repo, issue, comment } @@ -83,7 +84,7 @@ func TestComposeIssueCommentMessage(t *testing.T) { Content: fmt.Sprintf("test @%s %s#%d body", doer.Name, issue.Repo.FullName(), issue.Index), Comment: comment, }, "en-US", recipients, false, "issue comment") - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, msgs, 2) gomailMsg := msgs[0].ToMessage() replyTo := gomailMsg.GetHeader("Reply-To")[0] @@ -105,7 +106,7 @@ func TestComposeIssueCommentMessage(t *testing.T) { gomailMsg.WriteTo(&buf) b, err := io.ReadAll(quotedprintable.NewReader(&buf)) - assert.NoError(t, err) + require.NoError(t, err) // text/plain assert.Contains(t, string(b), fmt.Sprintf(`( %s )`, doer.HTMLURL())) @@ -126,7 +127,7 @@ func TestComposeIssueMessage(t *testing.T) { Issue: issue, Doer: doer, ActionType: activities_model.ActionCreateIssue, Content: "test body", }, "en-US", recipients, false, "issue create") - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, msgs, 2) gomailMsg := msgs[0].ToMessage() @@ -147,7 +148,7 @@ func TestComposeIssueMessage(t *testing.T) { func TestMailerIssueTemplate(t *testing.T) { defer MockMailSettings(nil)() - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) @@ -170,13 +171,13 @@ func TestMailerIssueTemplate(t *testing.T) { ctx.Context = context.Background() fromMention := false msgs, err := composeIssueCommentMessages(ctx, "en-US", recipients, fromMention, "TestMailerIssueTemplate") - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, msgs, 1) return msgs[0] } issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) - assert.NoError(t, issue.LoadRepo(db.DefaultContext)) + require.NoError(t, issue.LoadRepo(db.DefaultContext)) msg := testCompose(t, &mailCommentContext{ Issue: issue, Doer: doer, ActionType: activities_model.ActionCreateIssue, @@ -205,7 +206,7 @@ func TestMailerIssueTemplate(t *testing.T) { expect(t, msg, issue, comment.Content) pull := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) - assert.NoError(t, pull.LoadAttributes(db.DefaultContext)) + require.NoError(t, pull.LoadAttributes(db.DefaultContext)) pullComment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 4, Issue: pull}) msg = testCompose(t, &mailCommentContext{ @@ -221,7 +222,7 @@ func TestMailerIssueTemplate(t *testing.T) { expect(t, msg, pull, pullComment.Content, pull.PullRequest.BaseBranch) reviewComment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 9}) - assert.NoError(t, reviewComment.LoadReview(db.DefaultContext)) + require.NoError(t, reviewComment.LoadReview(db.DefaultContext)) approveComment := reviewComment approveComment.Review.Type = issues_model.ReviewTypeApprove @@ -298,7 +299,7 @@ func TestTemplateSelection(t *testing.T) { func TestTemplateServices(t *testing.T) { defer MockMailSettings(nil)() doer, _, issue, comment := prepareMailerTest(t) - assert.NoError(t, issue.LoadRepo(db.DefaultContext)) + require.NoError(t, issue.LoadRepo(db.DefaultContext)) expect := func(t *testing.T, issue *issues_model.Issue, comment *issues_model.Comment, doer *user_model.User, actionType activities_model.ActionType, fromMention bool, tplSubject, tplBody, expSubject, expBody string, @@ -343,7 +344,7 @@ func TestTemplateServices(t *testing.T) { func testComposeIssueCommentMessage(t *testing.T, ctx *mailCommentContext, recipients []*user_model.User, fromMention bool, info string) *Message { msgs, err := composeIssueCommentMessages(ctx, "en-US", recipients, fromMention, info) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, msgs, 1) return msgs[0] } @@ -492,7 +493,7 @@ func Test_createReference(t *testing.T) { func TestFromDisplayName(t *testing.T) { template, err := texttmpl.New("mailFrom").Parse("{{ .DisplayName }}") - assert.NoError(t, err) + require.NoError(t, err) setting.MailService = &setting.Mailer{FromDisplayNameFormatTemplate: template} defer func() { setting.MailService = nil }() @@ -523,7 +524,7 @@ func TestFromDisplayName(t *testing.T) { t.Run("template with all available vars", func(t *testing.T) { template, err = texttmpl.New("mailFrom").Parse("{{ .DisplayName }} (by {{ .AppName }} on [{{ .Domain }}])") - assert.NoError(t, err) + require.NoError(t, err) setting.MailService = &setting.Mailer{FromDisplayNameFormatTemplate: template} oldAppName := setting.AppName setting.AppName = "Code IT" diff --git a/services/mailer/mailer_test.go b/services/mailer/mailer_test.go index b7b4c28a3c..045701f3a5 100644 --- a/services/mailer/mailer_test.go +++ b/services/mailer/mailer_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGenerateMessageID(t *testing.T) { @@ -69,7 +70,7 @@ func TestToMessage(t *testing.T) { buf := &strings.Builder{} _, err := m1.ToMessage().WriteTo(buf) - assert.NoError(t, err) + require.NoError(t, err) header, _ := extractMailHeaderAndContent(t, buf.String()) assert.EqualValues(t, map[string]string{ "Content-Type": "multipart/alternative;", @@ -89,7 +90,7 @@ func TestToMessage(t *testing.T) { buf = &strings.Builder{} _, err = m1.ToMessage().WriteTo(buf) - assert.NoError(t, err) + require.NoError(t, err) header, _ = extractMailHeaderAndContent(t, buf.String()) assert.EqualValues(t, map[string]string{ "Content-Type": "multipart/alternative;", diff --git a/services/markup/processorhelper_test.go b/services/markup/processorhelper_test.go index 170edae0e0..fafde746d2 100644 --- a/services/markup/processorhelper_test.go +++ b/services/markup/processorhelper_test.go @@ -16,10 +16,11 @@ import ( "code.gitea.io/gitea/services/contexttest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestProcessorHelper(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) userPublic := "user1" userPrivate := "user31" @@ -39,7 +40,7 @@ func TestProcessorHelper(t *testing.T) { // when using web context, use user.IsUserVisibleToViewer to check req, err := http.NewRequest("GET", "/", nil) - assert.NoError(t, err) + require.NoError(t, err) base, baseCleanUp := gitea_context.NewBaseContext(httptest.NewRecorder(), req) defer baseCleanUp() giteaCtx := gitea_context.NewWebContext(base, &contexttest.MockRender{}, nil) @@ -48,7 +49,7 @@ func TestProcessorHelper(t *testing.T) { assert.False(t, ProcessorHelper().IsUsernameMentionable(giteaCtx, userPrivate)) giteaCtx.Doer, err = user.GetUserByName(db.DefaultContext, userPrivate) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, ProcessorHelper().IsUsernameMentionable(giteaCtx, userPublic)) assert.True(t, ProcessorHelper().IsUsernameMentionable(giteaCtx, userPrivate)) } diff --git a/services/migrations/codebase_test.go b/services/migrations/codebase_test.go index 68721e0641..23626d16d7 100644 --- a/services/migrations/codebase_test.go +++ b/services/migrations/codebase_test.go @@ -13,6 +13,7 @@ import ( base "code.gitea.io/gitea/modules/migration" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCodebaseDownloadRepo(t *testing.T) { @@ -41,7 +42,7 @@ func TestCodebaseDownloadRepo(t *testing.T) { t.Fatalf("Error creating Codebase downloader: %v", err) } repo, err := downloader.GetRepoInfo() - assert.NoError(t, err) + require.NoError(t, err) assertRepositoryEqual(t, &base.Repository{ Name: "test", Owner: "", @@ -51,7 +52,7 @@ func TestCodebaseDownloadRepo(t *testing.T) { }, repo) milestones, err := downloader.GetMilestones() - assert.NoError(t, err) + require.NoError(t, err) assertMilestonesEqual(t, []*base.Milestone{ { Title: "Milestone1", @@ -66,11 +67,11 @@ func TestCodebaseDownloadRepo(t *testing.T) { }, milestones) labels, err := downloader.GetLabels() - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, labels, 4) issues, isEnd, err := downloader.GetIssues(1, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isEnd) assertIssuesEqual(t, []*base.Issue{ { @@ -107,7 +108,7 @@ func TestCodebaseDownloadRepo(t *testing.T) { }, issues) comments, _, err := downloader.GetComments(issues[0]) - assert.NoError(t, err) + require.NoError(t, err) assertCommentsEqual(t, []*base.Comment{ { IssueIndex: 2, @@ -120,7 +121,7 @@ func TestCodebaseDownloadRepo(t *testing.T) { }, comments) prs, _, err := downloader.GetPullRequests(1, 1) - assert.NoError(t, err) + require.NoError(t, err) assertPullRequestsEqual(t, []*base.PullRequest{ { Number: 3, @@ -145,6 +146,6 @@ func TestCodebaseDownloadRepo(t *testing.T) { }, prs) rvs, err := downloader.GetReviews(prs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, rvs) } diff --git a/services/migrations/gitea_downloader_test.go b/services/migrations/gitea_downloader_test.go index c37c70947e..28a52c202d 100644 --- a/services/migrations/gitea_downloader_test.go +++ b/services/migrations/gitea_downloader_test.go @@ -14,6 +14,7 @@ import ( base "code.gitea.io/gitea/modules/migration" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGiteaDownloadRepo(t *testing.T) { @@ -32,12 +33,10 @@ func TestGiteaDownloadRepo(t *testing.T) { if downloader == nil { t.Fatal("NewGitlabDownloader is nil") } - if !assert.NoError(t, err) { - t.Fatal("NewGitlabDownloader error occur") - } + require.NoError(t, err, "NewGitlabDownloader error occur") repo, err := downloader.GetRepoInfo() - assert.NoError(t, err) + require.NoError(t, err) assertRepositoryEqual(t, &base.Repository{ Name: "test_repo", Owner: "gitea", @@ -49,12 +48,12 @@ func TestGiteaDownloadRepo(t *testing.T) { }, repo) topics, err := downloader.GetTopics() - assert.NoError(t, err) + require.NoError(t, err) sort.Strings(topics) assert.EqualValues(t, []string{"ci", "gitea", "migration", "test"}, topics) labels, err := downloader.GetLabels() - assert.NoError(t, err) + require.NoError(t, err) assertLabelsEqual(t, []*base.Label{ { Name: "Bug", @@ -84,7 +83,7 @@ func TestGiteaDownloadRepo(t *testing.T) { }, labels) milestones, err := downloader.GetMilestones() - assert.NoError(t, err) + require.NoError(t, err) assertMilestonesEqual(t, []*base.Milestone{ { Title: "V2 Finalize", @@ -104,7 +103,7 @@ func TestGiteaDownloadRepo(t *testing.T) { }, milestones) releases, err := downloader.GetReleases() - assert.NoError(t, err) + require.NoError(t, err) assertReleasesEqual(t, []*base.Release{ { Name: "Second Release", @@ -135,13 +134,13 @@ func TestGiteaDownloadRepo(t *testing.T) { }, releases) issues, isEnd, err := downloader.GetIssues(1, 50) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isEnd) assert.Len(t, issues, 7) assert.EqualValues(t, "open", issues[0].State) issues, isEnd, err = downloader.GetIssues(3, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isEnd) assertIssuesEqual(t, []*base.Issue{ @@ -198,7 +197,7 @@ func TestGiteaDownloadRepo(t *testing.T) { }, issues) comments, _, err := downloader.GetComments(&base.Issue{Number: 4, ForeignIndex: 4}) - assert.NoError(t, err) + require.NoError(t, err) assertCommentsEqual(t, []*base.Comment{ { IssueIndex: 4, @@ -221,11 +220,11 @@ func TestGiteaDownloadRepo(t *testing.T) { }, comments) prs, isEnd, err := downloader.GetPullRequests(1, 50) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isEnd) assert.Len(t, prs, 6) prs, isEnd, err = downloader.GetPullRequests(1, 3) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isEnd) assert.Len(t, prs, 3) assertPullRequestEqual(t, &base.PullRequest{ @@ -263,7 +262,7 @@ func TestGiteaDownloadRepo(t *testing.T) { }, prs[1]) reviews, err := downloader.GetReviews(&base.Issue{Number: 7, ForeignIndex: 7}) - assert.NoError(t, err) + require.NoError(t, err) assertReviewsEqual(t, []*base.Review{ { ID: 1770, diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 35da8290c8..ad193b2253 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -28,6 +28,7 @@ import ( "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGiteaUploadRepo(t *testing.T) { @@ -60,7 +61,7 @@ func TestGiteaUploadRepo(t *testing.T) { Private: true, Mirror: false, }, nil) - assert.NoError(t, err) + require.NoError(t, err) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID, Name: repoName}) assert.True(t, repo.HasWiki()) @@ -70,18 +71,18 @@ func TestGiteaUploadRepo(t *testing.T) { RepoID: repo.ID, IsClosed: optional.Some(false), }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, milestones, 1) milestones, err = db.Find[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{ RepoID: repo.ID, IsClosed: optional.Some(true), }) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, milestones) labels, err := issues_model.GetLabelsByRepoID(ctx, repo.ID, "", db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, labels, 12) releases, err := db.Find[repo_model.Release](db.DefaultContext, repo_model.FindReleasesOptions{ @@ -92,7 +93,7 @@ func TestGiteaUploadRepo(t *testing.T) { IncludeTags: true, RepoID: repo.ID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, releases, 8) releases, err = db.Find[repo_model.Release](db.DefaultContext, repo_model.FindReleasesOptions{ @@ -103,7 +104,7 @@ func TestGiteaUploadRepo(t *testing.T) { IncludeTags: false, RepoID: repo.ID, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, releases, 1) issues, err := issues_model.Issues(db.DefaultContext, &issues_model.IssuesOptions{ @@ -111,18 +112,18 @@ func TestGiteaUploadRepo(t *testing.T) { IsPull: optional.Some(false), SortType: "oldest", }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, issues, 15) - assert.NoError(t, issues[0].LoadDiscussComments(db.DefaultContext)) + require.NoError(t, issues[0].LoadDiscussComments(db.DefaultContext)) assert.Empty(t, issues[0].Comments) pulls, _, err := issues_model.PullRequests(db.DefaultContext, repo.ID, &issues_model.PullRequestsOptions{ SortType: "oldest", }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pulls, 30) - assert.NoError(t, pulls[0].LoadIssue(db.DefaultContext)) - assert.NoError(t, pulls[0].Issue.LoadDiscussComments(db.DefaultContext)) + require.NoError(t, pulls[0].LoadIssue(db.DefaultContext)) + require.NoError(t, pulls[0].Issue.LoadDiscussComments(db.DefaultContext)) assert.Len(t, pulls[0].Issue.Comments, 2) } @@ -150,7 +151,7 @@ func TestGiteaUploadRemapLocalUser(t *testing.T) { target := repo_model.Release{} uploader.userMap = make(map[int64]int64) err := uploader.remapUser(&source, &target) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, user_model.GhostUserID, target.GetUserID()) // @@ -161,7 +162,7 @@ func TestGiteaUploadRemapLocalUser(t *testing.T) { target = repo_model.Release{} uploader.userMap = make(map[int64]int64) err = uploader.remapUser(&source, &target) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, user_model.GhostUserID, target.GetUserID()) // @@ -172,7 +173,7 @@ func TestGiteaUploadRemapLocalUser(t *testing.T) { target = repo_model.Release{} uploader.userMap = make(map[int64]int64) err = uploader.remapUser(&source, &target) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, user.ID, target.GetUserID()) } @@ -200,7 +201,7 @@ func TestGiteaUploadRemapExternalUser(t *testing.T) { uploader.userMap = make(map[int64]int64) target := repo_model.Release{} err := uploader.remapUser(&source, &target) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, user_model.GhostUserID, target.GetUserID()) // @@ -214,7 +215,7 @@ func TestGiteaUploadRemapExternalUser(t *testing.T) { Provider: structs.GiteaService.Name(), } err = user_model.LinkExternalToUser(db.DefaultContext, linkedUser, externalLoginUser) - assert.NoError(t, err) + require.NoError(t, err) // // When a user is linked to the external ID, it becomes the author of @@ -223,7 +224,7 @@ func TestGiteaUploadRemapExternalUser(t *testing.T) { uploader.userMap = make(map[int64]int64) target = repo_model.Release{} err = uploader.remapUser(&source, &target) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, linkedUser.ID, target.GetUserID()) } @@ -235,44 +236,44 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { // fromRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) baseRef := "master" - assert.NoError(t, git.InitRepository(git.DefaultContext, fromRepo.RepoPath(), false, fromRepo.ObjectFormatName)) + require.NoError(t, git.InitRepository(git.DefaultContext, fromRepo.RepoPath(), false, fromRepo.ObjectFormatName)) err := git.NewCommand(git.DefaultContext, "symbolic-ref").AddDynamicArguments("HEAD", git.BranchPrefix+baseRef).Run(&git.RunOpts{Dir: fromRepo.RepoPath()}) - assert.NoError(t, err) - assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", fromRepo.RepoPath())), 0o644)) - assert.NoError(t, git.AddChanges(fromRepo.RepoPath(), true)) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", fromRepo.RepoPath())), 0o644)) + require.NoError(t, git.AddChanges(fromRepo.RepoPath(), true)) signature := git.Signature{ Email: "test@example.com", Name: "test", When: time.Now(), } - assert.NoError(t, git.CommitChanges(fromRepo.RepoPath(), git.CommitChangesOptions{ + require.NoError(t, git.CommitChanges(fromRepo.RepoPath(), git.CommitChangesOptions{ Committer: &signature, Author: &signature, Message: "Initial Commit", })) fromGitRepo, err := gitrepo.OpenRepository(git.DefaultContext, fromRepo) - assert.NoError(t, err) + require.NoError(t, err) defer fromGitRepo.Close() baseSHA, err := fromGitRepo.GetBranchCommitID(baseRef) - assert.NoError(t, err) + require.NoError(t, err) // // fromRepo branch1 // headRef := "branch1" _, _, err = git.NewCommand(git.DefaultContext, "checkout", "-b").AddDynamicArguments(headRef).RunStdString(&git.RunOpts{Dir: fromRepo.RepoPath()}) - assert.NoError(t, err) - assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte("SOMETHING"), 0o644)) - assert.NoError(t, git.AddChanges(fromRepo.RepoPath(), true)) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte("SOMETHING"), 0o644)) + require.NoError(t, git.AddChanges(fromRepo.RepoPath(), true)) signature.When = time.Now() - assert.NoError(t, git.CommitChanges(fromRepo.RepoPath(), git.CommitChangesOptions{ + require.NoError(t, git.CommitChanges(fromRepo.RepoPath(), git.CommitChangesOptions{ Committer: &signature, Author: &signature, Message: "Pull request", })) - assert.NoError(t, err) + require.NoError(t, err) headSHA, err := fromGitRepo.GetBranchCommitID(headRef) - assert.NoError(t, err) + require.NoError(t, err) fromRepoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: fromRepo.OwnerID}) @@ -281,28 +282,28 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { // forkHeadRef := "branch2" forkRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 8}) - assert.NoError(t, git.CloneWithArgs(git.DefaultContext, nil, fromRepo.RepoPath(), forkRepo.RepoPath(), git.CloneRepoOptions{ + require.NoError(t, git.CloneWithArgs(git.DefaultContext, nil, fromRepo.RepoPath(), forkRepo.RepoPath(), git.CloneRepoOptions{ Branch: headRef, })) _, _, err = git.NewCommand(git.DefaultContext, "checkout", "-b").AddDynamicArguments(forkHeadRef).RunStdString(&git.RunOpts{Dir: forkRepo.RepoPath()}) - assert.NoError(t, err) - assert.NoError(t, os.WriteFile(filepath.Join(forkRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# branch2 %s", forkRepo.RepoPath())), 0o644)) - assert.NoError(t, git.AddChanges(forkRepo.RepoPath(), true)) - assert.NoError(t, git.CommitChanges(forkRepo.RepoPath(), git.CommitChangesOptions{ + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(forkRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# branch2 %s", forkRepo.RepoPath())), 0o644)) + require.NoError(t, git.AddChanges(forkRepo.RepoPath(), true)) + require.NoError(t, git.CommitChanges(forkRepo.RepoPath(), git.CommitChangesOptions{ Committer: &signature, Author: &signature, Message: "branch2 commit", })) forkGitRepo, err := gitrepo.OpenRepository(git.DefaultContext, forkRepo) - assert.NoError(t, err) + require.NoError(t, err) defer forkGitRepo.Close() forkHeadSHA, err := forkGitRepo.GetBranchCommitID(forkHeadRef) - assert.NoError(t, err) + require.NoError(t, err) toRepoName := "migrated" uploader := NewGiteaLocalUploader(context.Background(), fromRepoOwner, fromRepoOwner.Name, toRepoName) uploader.gitServiceType = structs.GiteaService - assert.NoError(t, uploader.CreateRepo(&base.Repository{ + require.NoError(t, uploader.CreateRepo(&base.Repository{ Description: "description", OriginalURL: fromRepo.RepoPath(), CloneURL: fromRepo.RepoPath(), @@ -503,7 +504,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { testCase.pr.EnsuredSafe = true head, err := uploader.updateGitForPullRequest(&testCase.pr) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, testCase.head, head) log.Info(stopMark) diff --git a/services/migrations/github_test.go b/services/migrations/github_test.go index 2b89e6dc0f..a2134f8bf2 100644 --- a/services/migrations/github_test.go +++ b/services/migrations/github_test.go @@ -13,6 +13,7 @@ import ( base "code.gitea.io/gitea/modules/migration" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGitHubDownloadRepo(t *testing.T) { @@ -23,10 +24,10 @@ func TestGitHubDownloadRepo(t *testing.T) { } downloader := NewGithubDownloaderV3(context.Background(), "https://github.com", "", "", token, "go-gitea", "test_repo") err := downloader.RefreshRate() - assert.NoError(t, err) + require.NoError(t, err) repo, err := downloader.GetRepoInfo() - assert.NoError(t, err) + require.NoError(t, err) assertRepositoryEqual(t, &base.Repository{ Name: "test_repo", Owner: "go-gitea", @@ -37,11 +38,11 @@ func TestGitHubDownloadRepo(t *testing.T) { }, repo) topics, err := downloader.GetTopics() - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, topics, "gitea") milestones, err := downloader.GetMilestones() - assert.NoError(t, err) + require.NoError(t, err) assertMilestonesEqual(t, []*base.Milestone{ { Title: "1.0.0", @@ -64,7 +65,7 @@ func TestGitHubDownloadRepo(t *testing.T) { }, milestones) labels, err := downloader.GetLabels() - assert.NoError(t, err) + require.NoError(t, err) assertLabelsEqual(t, []*base.Label{ { Name: "bug", @@ -114,7 +115,7 @@ func TestGitHubDownloadRepo(t *testing.T) { }, labels) releases, err := downloader.GetReleases() - assert.NoError(t, err) + require.NoError(t, err) assertReleasesEqual(t, []*base.Release{ { TagName: "v0.9.99", @@ -130,7 +131,7 @@ func TestGitHubDownloadRepo(t *testing.T) { // downloader.GetIssues() issues, isEnd, err := downloader.GetIssues(1, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isEnd) assertIssuesEqual(t, []*base.Issue{ { @@ -219,7 +220,7 @@ func TestGitHubDownloadRepo(t *testing.T) { // downloader.GetComments() comments, _, err := downloader.GetComments(&base.Issue{Number: 2, ForeignIndex: 2}) - assert.NoError(t, err) + require.NoError(t, err) assertCommentsEqual(t, []*base.Comment{ { IssueIndex: 2, @@ -249,7 +250,7 @@ func TestGitHubDownloadRepo(t *testing.T) { // downloader.GetPullRequests() prs, _, err := downloader.GetPullRequests(1, 2) - assert.NoError(t, err) + require.NoError(t, err) assertPullRequestsEqual(t, []*base.PullRequest{ { Number: 3, @@ -339,7 +340,7 @@ func TestGitHubDownloadRepo(t *testing.T) { }, prs) reviews, err := downloader.GetReviews(&base.PullRequest{Number: 3, ForeignIndex: 3}) - assert.NoError(t, err) + require.NoError(t, err) assertReviewsEqual(t, []*base.Review{ { ID: 315859956, @@ -371,7 +372,7 @@ func TestGitHubDownloadRepo(t *testing.T) { }, reviews) reviews, err = downloader.GetReviews(&base.PullRequest{Number: 4, ForeignIndex: 4}) - assert.NoError(t, err) + require.NoError(t, err) assertReviewsEqual(t, []*base.Review{ { ID: 338338740, diff --git a/services/migrations/gitlab_test.go b/services/migrations/gitlab_test.go index 6e5ab86720..0cae43d9b8 100644 --- a/services/migrations/gitlab_test.go +++ b/services/migrations/gitlab_test.go @@ -18,6 +18,7 @@ import ( base "code.gitea.io/gitea/modules/migration" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/xanzy/go-gitlab" ) @@ -35,7 +36,7 @@ func TestGitlabDownloadRepo(t *testing.T) { t.Fatalf("NewGitlabDownloader is nil: %v", err) } repo, err := downloader.GetRepoInfo() - assert.NoError(t, err) + require.NoError(t, err) // Repo Owner is blank in Gitlab Group repos assertRepositoryEqual(t, &base.Repository{ Name: "test_repo", @@ -47,12 +48,12 @@ func TestGitlabDownloadRepo(t *testing.T) { }, repo) topics, err := downloader.GetTopics() - assert.NoError(t, err) - assert.True(t, len(topics) == 2) + require.NoError(t, err) + assert.Len(t, topics, 2) assert.EqualValues(t, []string{"migration", "test"}, topics) milestones, err := downloader.GetMilestones() - assert.NoError(t, err) + require.NoError(t, err) assertMilestonesEqual(t, []*base.Milestone{ { Title: "1.1.0", @@ -70,7 +71,7 @@ func TestGitlabDownloadRepo(t *testing.T) { }, milestones) labels, err := downloader.GetLabels() - assert.NoError(t, err) + require.NoError(t, err) assertLabelsEqual(t, []*base.Label{ { Name: "bug", @@ -111,7 +112,7 @@ func TestGitlabDownloadRepo(t *testing.T) { }, labels) releases, err := downloader.GetReleases() - assert.NoError(t, err) + require.NoError(t, err) assertReleasesEqual(t, []*base.Release{ { TagName: "v0.9.99", @@ -125,7 +126,7 @@ func TestGitlabDownloadRepo(t *testing.T) { }, releases) issues, isEnd, err := downloader.GetIssues(1, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isEnd) assertIssuesEqual(t, []*base.Issue{ @@ -217,7 +218,7 @@ func TestGitlabDownloadRepo(t *testing.T) { ForeignIndex: 2, Context: gitlabIssueContext{IsMergeRequest: false}, }) - assert.NoError(t, err) + require.NoError(t, err) assertCommentsEqual(t, []*base.Comment{ { IssueIndex: 2, @@ -254,7 +255,7 @@ func TestGitlabDownloadRepo(t *testing.T) { }, comments) prs, _, err := downloader.GetPullRequests(1, 1) - assert.NoError(t, err) + require.NoError(t, err) assertPullRequestsEqual(t, []*base.PullRequest{ { Number: 4, @@ -303,7 +304,7 @@ func TestGitlabDownloadRepo(t *testing.T) { }, prs) rvs, err := downloader.GetReviews(&base.PullRequest{Number: 1, ForeignIndex: 1}) - assert.NoError(t, err) + require.NoError(t, err) assertReviewsEqual(t, []*base.Review{ { IssueIndex: 1, @@ -322,7 +323,7 @@ func TestGitlabDownloadRepo(t *testing.T) { }, rvs) rvs, err = downloader.GetReviews(&base.PullRequest{Number: 2, ForeignIndex: 2}) - assert.NoError(t, err) + require.NoError(t, err) assertReviewsEqual(t, []*base.Review{ { IssueIndex: 2, @@ -348,7 +349,7 @@ func TestGitlabSkippedIssueNumber(t *testing.T) { t.Fatalf("NewGitlabDownloader is nil: %v", err) } repo, err := downloader.GetRepoInfo() - assert.NoError(t, err) + require.NoError(t, err) assertRepositoryEqual(t, &base.Repository{ Name: "archbuild", Owner: "troyengel", @@ -359,20 +360,20 @@ func TestGitlabSkippedIssueNumber(t *testing.T) { }, repo) issues, isEnd, err := downloader.GetIssues(1, 10) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isEnd) // the only issue in this repository has number 2 - assert.EqualValues(t, 1, len(issues)) + assert.Len(t, issues, 1) assert.EqualValues(t, 2, issues[0].Number) assert.EqualValues(t, "vpn unlimited errors", issues[0].Title) prs, _, err := downloader.GetPullRequests(1, 10) - assert.NoError(t, err) + require.NoError(t, err) // the only merge request in this repository has number 1, // but we offset it by the maximum issue number so it becomes // pull request 3 in Forgejo - assert.EqualValues(t, 1, len(prs)) + assert.Len(t, prs, 1) assert.EqualValues(t, 3, prs[0].Number) assert.EqualValues(t, "Review", prs[0].Title) } @@ -507,7 +508,7 @@ func TestGitlabGetReviews(t *testing.T) { id := int64(testCase.prID) rvs, err := downloader.GetReviews(&base.Issue{Number: id, ForeignIndex: id}) - assert.NoError(t, err) + require.NoError(t, err) assertReviewsEqual(t, []*base.Review{&review}, rvs) } } @@ -541,7 +542,7 @@ func TestAwardsToReactions(t *testing.T) { ] ` var awards []*gitlab.AwardEmoji - assert.NoError(t, json.Unmarshal([]byte(testResponse), &awards)) + require.NoError(t, json.Unmarshal([]byte(testResponse), &awards)) reactions := downloader.awardsToReactions(awards) assert.EqualValues(t, []*base.Reaction{ diff --git a/services/migrations/gogs_test.go b/services/migrations/gogs_test.go index ca02b4317b..6c511a2bb5 100644 --- a/services/migrations/gogs_test.go +++ b/services/migrations/gogs_test.go @@ -13,6 +13,7 @@ import ( base "code.gitea.io/gitea/modules/migration" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGogsDownloadRepo(t *testing.T) { @@ -31,7 +32,7 @@ func TestGogsDownloadRepo(t *testing.T) { downloader := NewGogsDownloader(context.Background(), "https://try.gogs.io", "", "", gogsPersonalAccessToken, "lunnytest", "TESTREPO") repo, err := downloader.GetRepoInfo() - assert.NoError(t, err) + require.NoError(t, err) assertRepositoryEqual(t, &base.Repository{ Name: "TESTREPO", @@ -43,7 +44,7 @@ func TestGogsDownloadRepo(t *testing.T) { }, repo) milestones, err := downloader.GetMilestones() - assert.NoError(t, err) + require.NoError(t, err) assertMilestonesEqual(t, []*base.Milestone{ { Title: "1.0", @@ -52,7 +53,7 @@ func TestGogsDownloadRepo(t *testing.T) { }, milestones) labels, err := downloader.GetLabels() - assert.NoError(t, err) + require.NoError(t, err) assertLabelsEqual(t, []*base.Label{ { Name: "bug", @@ -86,7 +87,7 @@ func TestGogsDownloadRepo(t *testing.T) { // downloader.GetIssues() issues, isEnd, err := downloader.GetIssues(1, 8) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isEnd) assertIssuesEqual(t, []*base.Issue{ { @@ -111,7 +112,7 @@ func TestGogsDownloadRepo(t *testing.T) { // downloader.GetComments() comments, _, err := downloader.GetComments(&base.Issue{Number: 1, ForeignIndex: 1}) - assert.NoError(t, err) + require.NoError(t, err) assertCommentsEqual(t, []*base.Comment{ { IssueIndex: 1, @@ -135,7 +136,7 @@ func TestGogsDownloadRepo(t *testing.T) { // downloader.GetPullRequests() _, _, err = downloader.GetPullRequests(1, 3) - assert.Error(t, err) + require.Error(t, err) } func TestGogsDownloaderFactory_New(t *testing.T) { diff --git a/services/migrations/migrate_test.go b/services/migrations/migrate_test.go index 03efa6185b..109a092796 100644 --- a/services/migrations/migrate_test.go +++ b/services/migrations/migrate_test.go @@ -12,65 +12,65 @@ import ( user_model "code.gitea.io/gitea/models/user" "code.gitea.io/gitea/modules/setting" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMigrateWhiteBlocklist(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) adminUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user1"}) nonAdminUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user2"}) setting.Migrations.AllowedDomains = "github.com" setting.Migrations.AllowLocalNetworks = false - assert.NoError(t, Init()) + require.NoError(t, Init()) err := IsMigrateURLAllowed("https://gitlab.com/gitlab/gitlab.git", nonAdminUser) - assert.Error(t, err) + require.Error(t, err) err = IsMigrateURLAllowed("https://github.com/go-gitea/gitea.git", nonAdminUser) - assert.NoError(t, err) + require.NoError(t, err) err = IsMigrateURLAllowed("https://gITHUb.com/go-gitea/gitea.git", nonAdminUser) - assert.NoError(t, err) + require.NoError(t, err) setting.Migrations.AllowedDomains = "" setting.Migrations.BlockedDomains = "github.com" - assert.NoError(t, Init()) + require.NoError(t, Init()) err = IsMigrateURLAllowed("https://gitlab.com/gitlab/gitlab.git", nonAdminUser) - assert.NoError(t, err) + require.NoError(t, err) err = IsMigrateURLAllowed("https://github.com/go-gitea/gitea.git", nonAdminUser) - assert.Error(t, err) + require.Error(t, err) err = IsMigrateURLAllowed("https://10.0.0.1/go-gitea/gitea.git", nonAdminUser) - assert.Error(t, err) + require.Error(t, err) setting.Migrations.AllowLocalNetworks = true - assert.NoError(t, Init()) + require.NoError(t, Init()) err = IsMigrateURLAllowed("https://10.0.0.1/go-gitea/gitea.git", nonAdminUser) - assert.NoError(t, err) + require.NoError(t, err) old := setting.ImportLocalPaths setting.ImportLocalPaths = false err = IsMigrateURLAllowed("/home/foo/bar/goo", adminUser) - assert.Error(t, err) + require.Error(t, err) setting.ImportLocalPaths = true abs, err := filepath.Abs(".") - assert.NoError(t, err) + require.NoError(t, err) err = IsMigrateURLAllowed(abs, adminUser) - assert.NoError(t, err) + require.NoError(t, err) err = IsMigrateURLAllowed(abs, nonAdminUser) - assert.Error(t, err) + require.Error(t, err) nonAdminUser.AllowImportLocal = true err = IsMigrateURLAllowed(abs, nonAdminUser) - assert.NoError(t, err) + require.NoError(t, err) setting.ImportLocalPaths = old } @@ -80,35 +80,35 @@ func TestAllowBlockList(t *testing.T) { setting.Migrations.AllowedDomains = allow setting.Migrations.BlockedDomains = block setting.Migrations.AllowLocalNetworks = local - assert.NoError(t, Init()) + require.NoError(t, Init()) } // default, allow all external, block none, no local networks init("", "", false) - assert.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("1.2.3.4")})) - assert.Error(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("127.0.0.1")})) + require.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("1.2.3.4")})) + require.Error(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("127.0.0.1")})) // allow all including local networks (it could lead to SSRF in production) init("", "", true) - assert.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("1.2.3.4")})) - assert.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("127.0.0.1")})) + require.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("1.2.3.4")})) + require.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("127.0.0.1")})) // allow wildcard, block some subdomains. if the domain name is allowed, then the local network check is skipped init("*.domain.com", "blocked.domain.com", false) - assert.NoError(t, checkByAllowBlockList("sub.domain.com", []net.IP{net.ParseIP("1.2.3.4")})) - assert.NoError(t, checkByAllowBlockList("sub.domain.com", []net.IP{net.ParseIP("127.0.0.1")})) - assert.Error(t, checkByAllowBlockList("blocked.domain.com", []net.IP{net.ParseIP("1.2.3.4")})) - assert.Error(t, checkByAllowBlockList("sub.other.com", []net.IP{net.ParseIP("1.2.3.4")})) + require.NoError(t, checkByAllowBlockList("sub.domain.com", []net.IP{net.ParseIP("1.2.3.4")})) + require.NoError(t, checkByAllowBlockList("sub.domain.com", []net.IP{net.ParseIP("127.0.0.1")})) + require.Error(t, checkByAllowBlockList("blocked.domain.com", []net.IP{net.ParseIP("1.2.3.4")})) + require.Error(t, checkByAllowBlockList("sub.other.com", []net.IP{net.ParseIP("1.2.3.4")})) // allow wildcard (it could lead to SSRF in production) init("*", "", false) - assert.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("1.2.3.4")})) - assert.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("127.0.0.1")})) + require.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("1.2.3.4")})) + require.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("127.0.0.1")})) // local network can still be blocked init("*", "127.0.0.*", false) - assert.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("1.2.3.4")})) - assert.Error(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("127.0.0.1")})) + require.NoError(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("1.2.3.4")})) + require.Error(t, checkByAllowBlockList("domain.com", []net.IP{net.ParseIP("127.0.0.1")})) // reset init("", "", false) diff --git a/services/migrations/onedev_test.go b/services/migrations/onedev_test.go index 48412fec64..80c26130cc 100644 --- a/services/migrations/onedev_test.go +++ b/services/migrations/onedev_test.go @@ -13,6 +13,7 @@ import ( base "code.gitea.io/gitea/modules/migration" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestOneDevDownloadRepo(t *testing.T) { @@ -27,7 +28,7 @@ func TestOneDevDownloadRepo(t *testing.T) { t.Fatalf("NewOneDevDownloader is nil: %v", err) } repo, err := downloader.GetRepoInfo() - assert.NoError(t, err) + require.NoError(t, err) assertRepositoryEqual(t, &base.Repository{ Name: "go-gitea-test_repo", Owner: "", @@ -37,7 +38,7 @@ func TestOneDevDownloadRepo(t *testing.T) { }, repo) milestones, err := downloader.GetMilestones() - assert.NoError(t, err) + require.NoError(t, err) deadline := time.Unix(1620086400, 0) assertMilestonesEqual(t, []*base.Milestone{ { @@ -52,11 +53,11 @@ func TestOneDevDownloadRepo(t *testing.T) { }, milestones) labels, err := downloader.GetLabels() - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, labels, 6) issues, isEnd, err := downloader.GetIssues(1, 2) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isEnd) assertIssuesEqual(t, []*base.Issue{ { @@ -99,7 +100,7 @@ func TestOneDevDownloadRepo(t *testing.T) { ForeignIndex: 398, Context: onedevIssueContext{IsPullRequest: false}, }) - assert.NoError(t, err) + require.NoError(t, err) assertCommentsEqual(t, []*base.Comment{ { IssueIndex: 4, @@ -111,7 +112,7 @@ func TestOneDevDownloadRepo(t *testing.T) { }, comments) prs, _, err := downloader.GetPullRequests(1, 1) - assert.NoError(t, err) + require.NoError(t, err) assertPullRequestsEqual(t, []*base.PullRequest{ { Number: 5, @@ -137,7 +138,7 @@ func TestOneDevDownloadRepo(t *testing.T) { }, prs) rvs, err := downloader.GetReviews(&base.PullRequest{Number: 5, ForeignIndex: 186}) - assert.NoError(t, err) + require.NoError(t, err) assertReviewsEqual(t, []*base.Review{ { IssueIndex: 5, diff --git a/services/org/org_test.go b/services/org/org_test.go index e7d2a18ea9..07358438f6 100644 --- a/services/org/org_test.go +++ b/services/org/org_test.go @@ -13,6 +13,7 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -20,19 +21,19 @@ func TestMain(m *testing.M) { } func TestDeleteOrganization(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 6}) - assert.NoError(t, DeleteOrganization(db.DefaultContext, org, false)) + require.NoError(t, DeleteOrganization(db.DefaultContext, org, false)) unittest.AssertNotExistsBean(t, &organization.Organization{ID: 6}) unittest.AssertNotExistsBean(t, &organization.OrgUser{OrgID: 6}) unittest.AssertNotExistsBean(t, &organization.Team{OrgID: 6}) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) err := DeleteOrganization(db.DefaultContext, org, false) - assert.Error(t, err) + require.Error(t, err) assert.True(t, models.IsErrUserOwnRepos(err)) user := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 5}) - assert.Error(t, DeleteOrganization(db.DefaultContext, user, false)) + require.Error(t, DeleteOrganization(db.DefaultContext, user, false)) unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{}) } diff --git a/services/org/repo_test.go b/services/org/repo_test.go index 68c64a01ab..2ddb8f9045 100644 --- a/services/org/repo_test.go +++ b/services/org/repo_test.go @@ -11,16 +11,16 @@ 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 TestTeam_AddRepository(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, repoID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) - assert.NoError(t, TeamAddRepository(db.DefaultContext, team, repo)) + require.NoError(t, TeamAddRepository(db.DefaultContext, team, repo)) unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repoID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &repo_model.Repository{ID: repoID}) } @@ -29,6 +29,6 @@ func TestTeam_AddRepository(t *testing.T) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - assert.Error(t, TeamAddRepository(db.DefaultContext, team, repo)) + require.Error(t, TeamAddRepository(db.DefaultContext, team, repo)) unittest.CheckConsistencyFor(t, &organization.Team{ID: 1}, &repo_model.Repository{ID: 1}) } diff --git a/services/pull/check_test.go b/services/pull/check_test.go index dcf5f7b93a..b99cf01ee1 100644 --- a/services/pull/check_test.go +++ b/services/pull/check_test.go @@ -17,10 +17,11 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPullRequest_AddToTaskQueue(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) idChan := make(chan int64, 10) testHandler := func(items ...string) []string { @@ -32,9 +33,9 @@ func TestPullRequest_AddToTaskQueue(t *testing.T) { } cfg, err := setting.GetQueueSettings(setting.CfgProvider, "pr_patch_checker") - assert.NoError(t, err) + require.NoError(t, err) prPatchCheckerQueue, err = queue.NewWorkerPoolQueueWithContext(context.Background(), "pr_patch_checker", cfg, testHandler, true) - assert.NoError(t, err) + require.NoError(t, err) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) AddToTaskQueue(db.DefaultContext, pr) @@ -46,7 +47,7 @@ func TestPullRequest_AddToTaskQueue(t *testing.T) { has, err := prPatchCheckerQueue.Has(strconv.FormatInt(pr.ID, 10)) assert.True(t, has) - assert.NoError(t, err) + require.NoError(t, err) go prPatchCheckerQueue.Run() @@ -59,7 +60,7 @@ func TestPullRequest_AddToTaskQueue(t *testing.T) { has, err = prPatchCheckerQueue.Has(strconv.FormatInt(pr.ID, 10)) assert.False(t, has) - assert.NoError(t, err) + require.NoError(t, err) pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) assert.Equal(t, issues_model.PullRequestStatusChecking, pr.Status) diff --git a/services/pull/pull_test.go b/services/pull/pull_test.go index 787910bf76..ac67d03ee0 100644 --- a/services/pull/pull_test.go +++ b/services/pull/pull_test.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/modules/gitrepo" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // TODO TestPullRequest_PushToBaseRepo @@ -38,27 +39,27 @@ func TestPullRequest_CommitMessageTrailersPattern(t *testing.T) { } func TestPullRequest_GetDefaultMergeMessage_InternalTracker(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) + require.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, pr.BaseRepo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() mergeMessage, _, err := GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (#3) from branch2 into master", mergeMessage) pr.BaseRepoID = 1 pr.HeadRepoID = 2 mergeMessage, _, err = GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (#3) from user2/repo1:branch2 into master", mergeMessage) } func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) externalTracker := repo_model.RepoUnit{ Type: unit.TypeExternalTracker, @@ -71,13 +72,13 @@ func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) { pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2, BaseRepo: baseRepo}) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) + require.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, pr.BaseRepo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() mergeMessage, _, err := GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (!3) from branch2 into master", mergeMessage) @@ -86,7 +87,7 @@ func TestPullRequest_GetDefaultMergeMessage_ExternalTracker(t *testing.T) { pr.BaseRepo = nil pr.HeadRepo = nil mergeMessage, _, err = GetDefaultMergeMessage(db.DefaultContext, gitRepo, pr, "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "Merge pull request 'issue3' (#3) from user2/repo2:branch2 into master", mergeMessage) } diff --git a/services/pull/review_test.go b/services/pull/review_test.go index 3bce1e523d..4cb3ad007c 100644 --- a/services/pull/review_test.go +++ b/services/pull/review_test.go @@ -13,15 +13,16 @@ import ( pull_service "code.gitea.io/gitea/services/pull" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDismissReview(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) pull := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{}) - 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}) review, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{ Issue: issue, @@ -29,20 +30,20 @@ func TestDismissReview(t *testing.T) { Type: issues_model.ReviewTypeReject, }) - assert.NoError(t, err) + require.NoError(t, err) issue.IsClosed = true pull.HasMerged = false - assert.NoError(t, issues_model.UpdateIssueCols(db.DefaultContext, issue, "is_closed")) - assert.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) + require.NoError(t, issues_model.UpdateIssueCols(db.DefaultContext, issue, "is_closed")) + require.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) _, err = pull_service.DismissReview(db.DefaultContext, review.ID, issue.RepoID, "", &user_model.User{}, false, false) - assert.Error(t, err) + require.Error(t, err) assert.True(t, pull_service.IsErrDismissRequestOnClosedPR(err)) pull.HasMerged = true pull.Issue.IsClosed = false - assert.NoError(t, issues_model.UpdateIssueCols(db.DefaultContext, issue, "is_closed")) - assert.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) + require.NoError(t, issues_model.UpdateIssueCols(db.DefaultContext, issue, "is_closed")) + require.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) _, err = pull_service.DismissReview(db.DefaultContext, review.ID, issue.RepoID, "", &user_model.User{}, false, false) - assert.Error(t, err) + require.Error(t, err) assert.True(t, pull_service.IsErrDismissRequestOnClosedPR(err)) } diff --git a/services/release/release_test.go b/services/release/release_test.go index cf4421a17d..0cd655b317 100644 --- a/services/release/release_test.go +++ b/services/release/release_test.go @@ -19,6 +19,7 @@ import ( _ "code.gitea.io/gitea/models/actions" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -26,16 +27,16 @@ func TestMain(m *testing.M) { } func TestRelease_Create(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() - assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ + require.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -49,7 +50,7 @@ func TestRelease_Create(t *testing.T) { IsTag: false, }, "", []*AttachmentChange{})) - assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ + require.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -63,7 +64,7 @@ func TestRelease_Create(t *testing.T) { IsTag: false, }, "", []*AttachmentChange{})) - assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ + require.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -77,7 +78,7 @@ func TestRelease_Create(t *testing.T) { IsTag: false, }, "", []*AttachmentChange{})) - assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ + require.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -91,7 +92,7 @@ func TestRelease_Create(t *testing.T) { IsTag: false, }, "", []*AttachmentChange{})) - assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ + require.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -112,7 +113,7 @@ func TestRelease_Create(t *testing.T) { UploaderID: user.ID, Name: "test.txt", }, strings.NewReader(testPlayload), int64(len([]byte(testPlayload)))) - assert.NoError(t, err) + require.NoError(t, err) release := repo_model.Release{ RepoID: repo.ID, @@ -127,7 +128,7 @@ func TestRelease_Create(t *testing.T) { IsPrerelease: false, IsTag: true, } - assert.NoError(t, CreateRelease(gitRepo, &release, "test", []*AttachmentChange{ + require.NoError(t, CreateRelease(gitRepo, &release, "test", []*AttachmentChange{ { Action: "add", Type: "attachment", @@ -191,17 +192,17 @@ func TestRelease_Create(t *testing.T) { } func TestRelease_Update(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() // Test a changed release - assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ + require.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -215,17 +216,17 @@ func TestRelease_Update(t *testing.T) { IsTag: false, }, "", []*AttachmentChange{})) release, err := repo_model.GetRelease(db.DefaultContext, repo.ID, "v1.1.1") - assert.NoError(t, err) + require.NoError(t, err) releaseCreatedUnix := release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Note = "Changed note" - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{})) + require.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{})) release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) // Test a changed draft - assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ + require.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -239,17 +240,17 @@ func TestRelease_Update(t *testing.T) { IsTag: false, }, "", []*AttachmentChange{})) release, err = repo_model.GetRelease(db.DefaultContext, repo.ID, "v1.2.1") - assert.NoError(t, err) + require.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{})) + require.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{})) release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Less(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) // Test a changed pre-release - assert.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ + require.NoError(t, CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -263,14 +264,14 @@ func TestRelease_Update(t *testing.T) { IsTag: false, }, "", []*AttachmentChange{})) release, err = repo_model.GetRelease(db.DefaultContext, repo.ID, "v1.3.1") - assert.NoError(t, err) + require.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" release.Note = "Changed note" - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{})) + require.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{})) release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) // Test create release @@ -287,15 +288,15 @@ func TestRelease_Update(t *testing.T) { IsPrerelease: false, IsTag: false, } - assert.NoError(t, CreateRelease(gitRepo, release, "", []*AttachmentChange{})) + require.NoError(t, CreateRelease(gitRepo, release, "", []*AttachmentChange{})) assert.Greater(t, release.ID, int64(0)) release.IsDraft = false tagName := release.TagName - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{})) + require.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{})) release, err = repo_model.GetReleaseByID(db.DefaultContext, release.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tagName, release.TagName) // Add new attachments @@ -305,16 +306,16 @@ func TestRelease_Update(t *testing.T) { UploaderID: user.ID, Name: "test.txt", }, strings.NewReader(samplePayload), int64(len([]byte(samplePayload)))) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{ + require.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{ { Action: "add", Type: "attachment", UUID: attach.UUID, }, })) - assert.NoError(t, repo_model.GetReleaseAttachments(db.DefaultContext, release)) + require.NoError(t, repo_model.GetReleaseAttachments(db.DefaultContext, release)) assert.Len(t, release.Attachments, 1) assert.EqualValues(t, attach.UUID, release.Attachments[0].UUID) assert.EqualValues(t, release.ID, release.Attachments[0].ReleaseID) @@ -322,7 +323,7 @@ func TestRelease_Update(t *testing.T) { assert.EqualValues(t, attach.ExternalURL, release.Attachments[0].ExternalURL) // update the attachment name - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{ + require.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{ { Action: "update", Name: "test2.txt", @@ -330,7 +331,7 @@ func TestRelease_Update(t *testing.T) { }, })) release.Attachments = nil - assert.NoError(t, repo_model.GetReleaseAttachments(db.DefaultContext, release)) + require.NoError(t, repo_model.GetReleaseAttachments(db.DefaultContext, release)) assert.Len(t, release.Attachments, 1) assert.EqualValues(t, attach.UUID, release.Attachments[0].UUID) assert.EqualValues(t, release.ID, release.Attachments[0].ReleaseID) @@ -338,7 +339,7 @@ func TestRelease_Update(t *testing.T) { assert.EqualValues(t, attach.ExternalURL, release.Attachments[0].ExternalURL) // delete the attachment - assert.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{ + require.NoError(t, UpdateRelease(db.DefaultContext, user, gitRepo, release, false, []*AttachmentChange{ { Action: "delete", UUID: attach.UUID, @@ -383,13 +384,13 @@ func TestRelease_Update(t *testing.T) { } func TestRelease_createTag(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() // Test a changed release @@ -407,13 +408,13 @@ func TestRelease_createTag(t *testing.T) { IsTag: false, } _, err = createTag(db.DefaultContext, gitRepo, release, "") - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, release.CreatedUnix) releaseCreatedUnix := release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Note = "Changed note" _, err = createTag(db.DefaultContext, gitRepo, release, "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) // Test a changed draft @@ -431,12 +432,12 @@ func TestRelease_createTag(t *testing.T) { IsTag: false, } _, err = createTag(db.DefaultContext, gitRepo, release, "") - assert.NoError(t, err) + require.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" _, err = createTag(db.DefaultContext, gitRepo, release, "") - assert.NoError(t, err) + require.NoError(t, err) assert.Less(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) // Test a changed pre-release @@ -454,21 +455,21 @@ func TestRelease_createTag(t *testing.T) { IsTag: false, } _, err = createTag(db.DefaultContext, gitRepo, release, "") - assert.NoError(t, err) + require.NoError(t, err) releaseCreatedUnix = release.CreatedUnix time.Sleep(2 * time.Second) // sleep 2 seconds to ensure a different timestamp release.Title = "Changed title" release.Note = "Changed note" _, err = createTag(db.DefaultContext, gitRepo, release, "") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(releaseCreatedUnix), int64(release.CreatedUnix)) } func TestCreateNewTag(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - assert.NoError(t, CreateNewTag(git.DefaultContext, user, repo, "master", "v2.0", + require.NoError(t, CreateNewTag(git.DefaultContext, user, repo, "master", "v2.0", "v2.0 is released \n\n BUGFIX: .... \n\n 123")) } diff --git a/services/repository/adopt_test.go b/services/repository/adopt_test.go index 454d9a76b9..71fb1fc885 100644 --- a/services/repository/adopt_test.go +++ b/services/repository/adopt_test.go @@ -37,13 +37,13 @@ func TestCheckUnadoptedRepositories_Add(t *testing.T) { } func TestCheckUnadoptedRepositories(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // // Non existent user // unadopted := &unadoptedRepositories{start: 0, end: 100} err := checkUnadoptedRepositories(db.DefaultContext, "notauser", []string{"repo"}, unadopted) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, unadopted.repositories) // // Unadopted repository is returned @@ -54,20 +54,20 @@ func TestCheckUnadoptedRepositories(t *testing.T) { unadoptedRepoName := "unadopted" unadopted = &unadoptedRepositories{start: 0, end: 100} err = checkUnadoptedRepositories(db.DefaultContext, userName, []string{repoName, unadoptedRepoName}, unadopted) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, []string{path.Join(userName, unadoptedRepoName)}, unadopted.repositories) // // Existing (adopted) repository is not returned // unadopted = &unadoptedRepositories{start: 0, end: 100} err = checkUnadoptedRepositories(db.DefaultContext, userName, []string{repoName}, unadopted) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, unadopted.repositories) assert.Equal(t, 0, unadopted.index) } func TestListUnadoptedRepositories_ListOptions(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) username := "user2" unadoptedList := []string{path.Join(username, "unadopted1"), path.Join(username, "unadopted2")} for _, unadopted := range unadoptedList { @@ -76,23 +76,23 @@ func TestListUnadoptedRepositories_ListOptions(t *testing.T) { opts := db.ListOptions{Page: 1, PageSize: 1} repoNames, count, err := ListUnadoptedRepositories(db.DefaultContext, "", &opts) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 2, count) assert.Equal(t, unadoptedList[0], repoNames[0]) opts = db.ListOptions{Page: 2, PageSize: 1} repoNames, count, err = ListUnadoptedRepositories(db.DefaultContext, "", &opts) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 2, count) assert.Equal(t, unadoptedList[1], repoNames[0]) } func TestAdoptRepository(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) username := "user2" unadopted := "unadopted" - assert.NoError(t, unittest.CopyDir( + require.NoError(t, unittest.CopyDir( "../../modules/git/tests/repos/repo1_bare", path.Join(setting.RepoRootPath, username, unadopted+".git"), )) @@ -110,6 +110,6 @@ func TestAdoptRepository(t *testing.T) { IsPrivate: false, AutoInit: true, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, git.Sha1ObjectFormat.Name(), repo.ObjectFormatName) } diff --git a/services/repository/archiver/archiver_test.go b/services/repository/archiver/archiver_test.go index dbd4d9b3c7..9f822a31ce 100644 --- a/services/repository/archiver/archiver_test.go +++ b/services/repository/archiver/archiver_test.go @@ -4,7 +4,6 @@ package archiver import ( - "errors" "testing" "time" @@ -15,6 +14,7 @@ import ( _ "code.gitea.io/gitea/models/actions" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -22,7 +22,7 @@ func TestMain(m *testing.M) { } func TestArchive_Basic(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) ctx, _ := contexttest.MockContext(t, "user27/repo49") firstCommit, secondCommit := "51f84af23134", "aacbdfe9e1c4" @@ -32,47 +32,47 @@ func TestArchive_Basic(t *testing.T) { defer ctx.Repo.GitRepo.Close() bogusReq, err := NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, firstCommit+".zip") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, bogusReq) assert.EqualValues(t, firstCommit+".zip", bogusReq.GetArchiveName()) // Check a series of bogus requests. // Step 1, valid commit with a bad extension. bogusReq, err = NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, firstCommit+".dilbert") - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, bogusReq) // Step 2, missing commit. bogusReq, err = NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, "dbffff.zip") - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, bogusReq) // Step 3, doesn't look like branch/tag/commit. bogusReq, err = NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, "db.zip") - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, bogusReq) bogusReq, err = NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, "master.zip") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, bogusReq) assert.EqualValues(t, "master.zip", bogusReq.GetArchiveName()) bogusReq, err = NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, "test/archive.zip") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, bogusReq) assert.EqualValues(t, "test-archive.zip", bogusReq.GetArchiveName()) // Now two valid requests, firstCommit with valid extensions. zipReq, err := NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, firstCommit+".zip") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, zipReq) tgzReq, err := NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, firstCommit+".tar.gz") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, tgzReq) secondReq, err := NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, secondCommit+".zip") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, secondReq) inFlight := make([]*ArchiveRequest, 3) @@ -92,7 +92,7 @@ func TestArchive_Basic(t *testing.T) { time.Sleep(2 * time.Second) zipReq2, err := NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, firstCommit+".zip") - assert.NoError(t, err) + require.NoError(t, err) // This zipReq should match what's sitting in the queue, as we haven't // let it release yet. From the consumer's point of view, this looks like // a long-running archive task. @@ -107,12 +107,12 @@ func TestArchive_Basic(t *testing.T) { // after we release it. We should trigger both the timeout and non-timeout // cases. timedReq, err := NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, secondCommit+".tar.gz") - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, timedReq) ArchiveRepository(db.DefaultContext, timedReq) zipReq2, err = NewRequest(ctx, ctx.Repo.Repository.ID, ctx.Repo.GitRepo, firstCommit+".zip") - assert.NoError(t, err) + require.NoError(t, err) // Now, we're guaranteed to have released the original zipReq from the queue. // Ensure that we don't get handed back the released entry somehow, but they // should remain functionally equivalent in all fields. The exception here @@ -120,7 +120,7 @@ func TestArchive_Basic(t *testing.T) { // It's fine to go ahead and set it to nil now. assert.Equal(t, zipReq, zipReq2) - assert.False(t, zipReq == zipReq2) + assert.NotSame(t, zipReq, zipReq2) // Same commit, different compression formats should have different names. // Ideally, the extension would match what we originally requested. @@ -130,5 +130,5 @@ func TestArchive_Basic(t *testing.T) { func TestErrUnknownArchiveFormat(t *testing.T) { err := ErrUnknownArchiveFormat{RequestFormat: "master"} - assert.True(t, errors.Is(err, ErrUnknownArchiveFormat{})) + assert.ErrorIs(t, err, ErrUnknownArchiveFormat{}) } diff --git a/services/repository/avatar_test.go b/services/repository/avatar_test.go index 4a0ba61853..f0fe991de8 100644 --- a/services/repository/avatar_test.go +++ b/services/repository/avatar_test.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/modules/avatar" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUploadAvatar(t *testing.T) { @@ -23,11 +24,11 @@ func TestUploadAvatar(t *testing.T) { var buff bytes.Buffer png.Encode(&buff, myImage) - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}) err := UploadAvatar(db.DefaultContext, repo, buff.Bytes()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, avatar.HashAvatar(10, buff.Bytes()), repo.Avatar) } @@ -37,11 +38,11 @@ func TestUploadBigAvatar(t *testing.T) { var buff bytes.Buffer png.Encode(&buff, myImage) - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}) err := UploadAvatar(db.DefaultContext, repo, buff.Bytes()) - assert.Error(t, err) + require.Error(t, err) } func TestDeleteAvatar(t *testing.T) { @@ -50,14 +51,14 @@ func TestDeleteAvatar(t *testing.T) { var buff bytes.Buffer png.Encode(&buff, myImage) - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}) err := UploadAvatar(db.DefaultContext, repo, buff.Bytes()) - assert.NoError(t, err) + require.NoError(t, err) err = DeleteAvatar(db.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "", repo.Avatar) } diff --git a/services/repository/collaboration_test.go b/services/repository/collaboration_test.go index c3d006bfd8..c087018be4 100644 --- a/services/repository/collaboration_test.go +++ b/services/repository/collaboration_test.go @@ -10,18 +10,18 @@ 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 TestRepository_DeleteCollaboration(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.LoadOwner(db.DefaultContext)) - assert.NoError(t, DeleteCollaboration(db.DefaultContext, repo, 4)) + require.NoError(t, repo.LoadOwner(db.DefaultContext)) + require.NoError(t, DeleteCollaboration(db.DefaultContext, repo, 4)) unittest.AssertNotExistsBean(t, &repo_model.Collaboration{RepoID: repo.ID, UserID: 4}) - assert.NoError(t, DeleteCollaboration(db.DefaultContext, repo, 4)) + require.NoError(t, DeleteCollaboration(db.DefaultContext, repo, 4)) unittest.AssertNotExistsBean(t, &repo_model.Collaboration{RepoID: repo.ID, UserID: 4}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID}) diff --git a/services/repository/contributors_graph_test.go b/services/repository/contributors_graph_test.go index a04587e243..3caffa190c 100644 --- a/services/repository/contributors_graph_test.go +++ b/services/repository/contributors_graph_test.go @@ -17,17 +17,18 @@ import ( "gitea.com/go-chi/cache" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepository_ContributorsGraph(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - assert.NoError(t, repo.LoadOwner(db.DefaultContext)) + require.NoError(t, repo.LoadOwner(db.DefaultContext)) mockCache, err := cache.NewCacher(cache.Options{ Adapter: "memory", Interval: 24 * 60, }) - assert.NoError(t, err) + require.NoError(t, err) lc, cleanup := test.NewLogChecker(log.DEFAULT, log.INFO) lc.StopMark(`getExtendedCommitStats[repo="user2/repo2" revision="404ref"]: object does not exist [id: 404ref, rel_path: ]`) @@ -45,7 +46,7 @@ func TestRepository_ContributorsGraph(t *testing.T) { assert.EqualValues(t, `{"ethantkoenig@gmail.com":{"name":"Ethan Koenig","login":"","avatar_link":"https://secure.gravatar.com/avatar/b42fb195faa8c61b8d88abfefe30e9e3?d=identicon","home_link":"","total_commits":1,"weeks":{"1511654400000":{"week":1511654400000,"additions":3,"deletions":0,"commits":1}}},"jimmy.praet@telenet.be":{"name":"Jimmy Praet","login":"","avatar_link":"https://secure.gravatar.com/avatar/93c49b7c89eb156971d11161c9b52795?d=identicon","home_link":"","total_commits":1,"weeks":{"1624752000000":{"week":1624752000000,"additions":2,"deletions":0,"commits":1}}},"jon@allspice.io":{"name":"Jon","login":"","avatar_link":"https://secure.gravatar.com/avatar/00388ce725e6886f3e07c3733007289b?d=identicon","home_link":"","total_commits":1,"weeks":{"1607817600000":{"week":1607817600000,"additions":10,"deletions":0,"commits":1}}},"total":{"name":"Total","login":"","avatar_link":"","home_link":"","total_commits":3,"weeks":{"1511654400000":{"week":1511654400000,"additions":3,"deletions":0,"commits":1},"1607817600000":{"week":1607817600000,"additions":10,"deletions":0,"commits":1},"1624752000000":{"week":1624752000000,"additions":2,"deletions":0,"commits":1}}}}`, dataString) var data map[string]*ContributorData - assert.NoError(t, json.Unmarshal([]byte(dataString), &data)) + require.NoError(t, json.Unmarshal([]byte(dataString), &data)) var keys []string for k := range data { diff --git a/services/repository/create_test.go b/services/repository/create_test.go index 131249ad9c..9cde285181 100644 --- a/services/repository/create_test.go +++ b/services/repository/create_test.go @@ -16,14 +16,15 @@ import ( "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestIncludesAllRepositoriesTeams(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testTeamRepositories := func(teamID int64, repoIds []int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, team.LoadRepositories(db.DefaultContext), "%s: GetRepositories", team.Name) + require.NoError(t, team.LoadRepositories(db.DefaultContext), "%s: GetRepositories", team.Name) assert.Len(t, team.Repos, team.NumRepos, "%s: len repo", team.Name) assert.Len(t, team.Repos, len(repoIds), "%s: repo count", team.Name) for i, rid := range repoIds { @@ -35,7 +36,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { // Get an admin user. user, err := user_model.GetUserByID(db.DefaultContext, 1) - assert.NoError(t, err, "GetUserByID") + require.NoError(t, err, "GetUserByID") // Create org. org := &organization.Organization{ @@ -44,25 +45,25 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { Type: user_model.UserTypeOrganization, Visibility: structs.VisibleTypePublic, } - assert.NoError(t, organization.CreateOrganization(db.DefaultContext, org, user), "CreateOrganization") + require.NoError(t, organization.CreateOrganization(db.DefaultContext, org, user), "CreateOrganization") // Check Owner team. ownerTeam, err := org.GetOwnerTeam(db.DefaultContext) - assert.NoError(t, err, "GetOwnerTeam") + require.NoError(t, err, "GetOwnerTeam") assert.True(t, ownerTeam.IncludesAllRepositories, "Owner team includes all repositories") // Create repos. repoIDs := make([]int64, 0) for i := 0; i < 3; i++ { r, err := CreateRepositoryDirectly(db.DefaultContext, user, org.AsUser(), CreateRepoOptions{Name: fmt.Sprintf("repo-%d", i)}) - assert.NoError(t, err, "CreateRepository %d", i) + require.NoError(t, err, "CreateRepository %d", i) if r != nil { repoIDs = append(repoIDs, r.ID) } } // Get fresh copy of Owner team after creating repos. ownerTeam, err = org.GetOwnerTeam(db.DefaultContext) - assert.NoError(t, err, "GetOwnerTeam") + require.NoError(t, err, "GetOwnerTeam") // Create teams and check repositories. teams := []*organization.Team{ @@ -101,7 +102,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { } for i, team := range teams { if i > 0 { // first team is Owner. - assert.NoError(t, models.NewTeam(db.DefaultContext, team), "%s: NewTeam", team.Name) + require.NoError(t, models.NewTeam(db.DefaultContext, team), "%s: NewTeam", team.Name) } testTeamRepositories(team.ID, teamRepos[i]) } @@ -111,13 +112,13 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { teams[4].IncludesAllRepositories = true teamRepos[4] = repoIDs for i, team := range teams { - assert.NoError(t, models.UpdateTeam(db.DefaultContext, team, false, true), "%s: UpdateTeam", team.Name) + require.NoError(t, models.UpdateTeam(db.DefaultContext, team, false, true), "%s: UpdateTeam", team.Name) testTeamRepositories(team.ID, teamRepos[i]) } // Create repo and check teams repositories. r, err := CreateRepositoryDirectly(db.DefaultContext, user, org.AsUser(), CreateRepoOptions{Name: "repo-last"}) - assert.NoError(t, err, "CreateRepository last") + require.NoError(t, err, "CreateRepository last") if r != nil { repoIDs = append(repoIDs, r.ID) } @@ -129,7 +130,7 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { } // Remove repo and check teams repositories. - assert.NoError(t, DeleteRepositoryDirectly(db.DefaultContext, user, repoIDs[0]), "DeleteRepository") + require.NoError(t, DeleteRepositoryDirectly(db.DefaultContext, user, repoIDs[0]), "DeleteRepository") teamRepos[0] = repoIDs[1:] teamRepos[1] = repoIDs[1:] teamRepos[3] = repoIDs[1:3] @@ -141,8 +142,8 @@ func TestIncludesAllRepositoriesTeams(t *testing.T) { // Wipe created items. for i, rid := range repoIDs { if i > 0 { // first repo already deleted. - assert.NoError(t, DeleteRepositoryDirectly(db.DefaultContext, user, rid), "DeleteRepository %d", i) + require.NoError(t, DeleteRepositoryDirectly(db.DefaultContext, user, rid), "DeleteRepository %d", i) } } - assert.NoError(t, organization.DeleteOrganization(db.DefaultContext, org), "DeleteOrganization") + require.NoError(t, organization.DeleteOrganization(db.DefaultContext, org), "DeleteOrganization") } diff --git a/services/repository/files/content_test.go b/services/repository/files/content_test.go index 4811f9d327..768d6d2f39 100644 --- a/services/repository/files/content_test.go +++ b/services/repository/files/content_test.go @@ -14,6 +14,7 @@ import ( _ "code.gitea.io/gitea/models/actions" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -68,13 +69,13 @@ func TestGetContents(t *testing.T) { t.Run("Get README.md contents with GetContents(ctx, )", func(t *testing.T) { fileContentResponse, err := GetContents(ctx, ctx.Repo.Repository, treePath, ref, false) assert.EqualValues(t, expectedContentsResponse, fileContentResponse) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("Get README.md contents with ref as empty string (should then use the repo's default branch) with GetContents(ctx, )", func(t *testing.T) { fileContentResponse, err := GetContents(ctx, ctx.Repo.Repository, treePath, "", false) assert.EqualValues(t, expectedContentsResponse, fileContentResponse) - assert.NoError(t, err) + require.NoError(t, err) }) } @@ -103,13 +104,13 @@ func TestGetContentsOrListForDir(t *testing.T) { t.Run("Get root dir contents with GetContentsOrList(ctx, )", func(t *testing.T) { fileContentResponse, err := GetContentsOrList(ctx, ctx.Repo.Repository, treePath, ref) assert.EqualValues(t, expectedContentsListResponse, fileContentResponse) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("Get root dir contents with ref as empty string (should then use the repo's default branch) with GetContentsOrList(ctx, )", func(t *testing.T) { fileContentResponse, err := GetContentsOrList(ctx, ctx.Repo.Repository, treePath, "") assert.EqualValues(t, expectedContentsListResponse, fileContentResponse) - assert.NoError(t, err) + require.NoError(t, err) }) } @@ -131,13 +132,13 @@ func TestGetContentsOrListForFile(t *testing.T) { t.Run("Get README.md contents with GetContentsOrList(ctx, )", func(t *testing.T) { fileContentResponse, err := GetContentsOrList(ctx, ctx.Repo.Repository, treePath, ref) assert.EqualValues(t, expectedContentsResponse, fileContentResponse) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("Get README.md contents with ref as empty string (should then use the repo's default branch) with GetContentsOrList(ctx, )", func(t *testing.T) { fileContentResponse, err := GetContentsOrList(ctx, ctx.Repo.Repository, treePath, "") assert.EqualValues(t, expectedContentsResponse, fileContentResponse) - assert.NoError(t, err) + require.NoError(t, err) }) } @@ -158,16 +159,14 @@ func TestGetContentsErrors(t *testing.T) { t.Run("bad treePath", func(t *testing.T) { badTreePath := "bad/tree.md" fileContentResponse, err := GetContents(ctx, repo, badTreePath, ref, false) - assert.Error(t, err) - assert.EqualError(t, err, "object does not exist [id: , rel_path: bad]") + require.EqualError(t, err, "object does not exist [id: , rel_path: bad]") assert.Nil(t, fileContentResponse) }) t.Run("bad ref", func(t *testing.T) { badRef := "bad_ref" fileContentResponse, err := GetContents(ctx, repo, treePath, badRef, false) - assert.Error(t, err) - assert.EqualError(t, err, "object does not exist [id: "+badRef+", rel_path: ]") + require.EqualError(t, err, "object does not exist [id: "+badRef+", rel_path: ]") assert.Nil(t, fileContentResponse) }) } @@ -189,16 +188,14 @@ func TestGetContentsOrListErrors(t *testing.T) { t.Run("bad treePath", func(t *testing.T) { badTreePath := "bad/tree.md" fileContentResponse, err := GetContentsOrList(ctx, repo, badTreePath, ref) - assert.Error(t, err) - assert.EqualError(t, err, "object does not exist [id: , rel_path: bad]") + require.EqualError(t, err, "object does not exist [id: , rel_path: bad]") assert.Nil(t, fileContentResponse) }) t.Run("bad ref", func(t *testing.T) { badRef := "bad_ref" fileContentResponse, err := GetContentsOrList(ctx, repo, treePath, badRef) - assert.Error(t, err) - assert.EqualError(t, err, "object does not exist [id: "+badRef+", rel_path: ]") + require.EqualError(t, err, "object does not exist [id: "+badRef+", rel_path: ]") assert.Nil(t, fileContentResponse) }) } @@ -216,7 +213,7 @@ func TestGetContentsOrListOfEmptyRepos(t *testing.T) { t.Run("empty repo", func(t *testing.T) { contents, err := GetContentsOrList(ctx, repo, "", "") - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, contents) }) } @@ -247,6 +244,6 @@ func TestGetBlobBySHA(t *testing.T) { SHA: "65f1bf27bc3bf70f64657658635e66094edbcb4d", Size: 180, } - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, expectedGBR, gbr) } diff --git a/services/repository/files/diff_test.go b/services/repository/files/diff_test.go index 7cec979d72..1ea4a170cc 100644 --- a/services/repository/files/diff_test.go +++ b/services/repository/files/diff_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/services/gitdiff" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetDiffPreview(t *testing.T) { @@ -118,21 +119,21 @@ func TestGetDiffPreview(t *testing.T) { t.Run("with given branch", func(t *testing.T) { diff, err := GetDiffPreview(ctx, ctx.Repo.Repository, branch, treePath, content) - assert.NoError(t, err) + require.NoError(t, err) expectedBs, err := json.Marshal(expectedDiff) - assert.NoError(t, err) + require.NoError(t, err) bs, err := json.Marshal(diff) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, string(expectedBs), string(bs)) }) t.Run("empty branch, same results", func(t *testing.T) { diff, err := GetDiffPreview(ctx, ctx.Repo.Repository, "", treePath, content) - assert.NoError(t, err) + require.NoError(t, err) expectedBs, err := json.Marshal(expectedDiff) - assert.NoError(t, err) + require.NoError(t, err) bs, err := json.Marshal(diff) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expectedBs, bs) }) } diff --git a/services/repository/files/file_test.go b/services/repository/files/file_test.go index a5b3aad91e..2c6a169da1 100644 --- a/services/repository/files/file_test.go +++ b/services/repository/files/file_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/services/contexttest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCleanUploadFileName(t *testing.T) { @@ -115,6 +116,6 @@ func TestGetFileResponseFromCommit(t *testing.T) { expectedFileResponse := getExpectedFileResponse() fileResponse, err := GetFileResponseFromCommit(ctx, repo, commit, branch, treePath) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expectedFileResponse, fileResponse) } diff --git a/services/repository/files/temp_repo_test.go b/services/repository/files/temp_repo_test.go index 2e31996c40..e7d85ea3cc 100644 --- a/services/repository/files/temp_repo_test.go +++ b/services/repository/files/temp_repo_test.go @@ -11,7 +11,7 @@ import ( "code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/modules/git" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRemoveFilesFromIndexSha256(t *testing.T) { @@ -22,7 +22,7 @@ func TestRemoveFilesFromIndexSha256(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) temp, err := NewTemporaryUploadRepository(db.DefaultContext, repo) - assert.NoError(t, err) - assert.NoError(t, temp.Init("sha256")) - assert.NoError(t, temp.RemoveFilesFromIndex("README.md")) + require.NoError(t, err) + require.NoError(t, temp.Init("sha256")) + require.NoError(t, temp.RemoveFilesFromIndex("README.md")) } diff --git a/services/repository/files/tree_test.go b/services/repository/files/tree_test.go index 508f20090d..faa9b8e29e 100644 --- a/services/repository/files/tree_test.go +++ b/services/repository/files/tree_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/services/contexttest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGetTreeBySHA(t *testing.T) { @@ -29,7 +30,7 @@ func TestGetTreeBySHA(t *testing.T) { ctx.SetParams(":sha", sha) tree, err := GetTreeBySHA(ctx, ctx.Repo.Repository, ctx.Repo.GitRepo, ctx.Params(":sha"), page, perPage, true) - assert.NoError(t, err) + require.NoError(t, err) expectedTree := &api.GitTreeResponse{ SHA: "65f1bf27bc3bf70f64657658635e66094edbcb4d", URL: "https://try.gitea.io/api/v1/repos/user2/repo1/git/trees/65f1bf27bc3bf70f64657658635e66094edbcb4d", diff --git a/services/repository/fork_test.go b/services/repository/fork_test.go index 452798b25b..4680d99a32 100644 --- a/services/repository/fork_test.go +++ b/services/repository/fork_test.go @@ -13,10 +13,11 @@ import ( "code.gitea.io/gitea/modules/setting" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestForkRepository(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // user 13 has already forked repo10 user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 13}) @@ -28,7 +29,7 @@ func TestForkRepository(t *testing.T) { Description: "test", }) assert.Nil(t, fork) - assert.Error(t, err) + require.Error(t, err) assert.True(t, IsErrForkAlreadyExist(err)) // user not reached maximum limit of repositories diff --git a/services/repository/lfs_test.go b/services/repository/lfs_test.go index 52ee05a147..a0c01dff8f 100644 --- a/services/repository/lfs_test.go +++ b/services/repository/lfs_test.go @@ -19,6 +19,7 @@ import ( repo_service "code.gitea.io/gitea/services/repository" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGarbageCollectLFSMetaObjects(t *testing.T) { @@ -26,13 +27,13 @@ func TestGarbageCollectLFSMetaObjects(t *testing.T) { setting.LFS.StartServer = true err := storage.Init() - assert.NoError(t, err) + require.NoError(t, err) repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "lfs") - assert.NoError(t, err) + require.NoError(t, err) validLFSObjects, err := db.GetEngine(db.DefaultContext).Count(git_model.LFSMetaObject{RepositoryID: repo.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Greater(t, validLFSObjects, int64(1)) // add lfs object @@ -46,29 +47,29 @@ func TestGarbageCollectLFSMetaObjects(t *testing.T) { UpdatedLessRecentlyThan: time.Time{}, // ensure that the models/fixtures/lfs_meta_object.yml objects are considered as well LogDetail: t.Logf, }) - assert.NoError(t, err) + require.NoError(t, err) // lfs meta has been deleted _, err = git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, lfsOid) - assert.ErrorIs(t, err, git_model.ErrLFSObjectNotExist) + require.ErrorIs(t, err, git_model.ErrLFSObjectNotExist) remainingLFSObjects, err := db.GetEngine(db.DefaultContext).Count(git_model.LFSMetaObject{RepositoryID: repo.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, validLFSObjects-1, remainingLFSObjects) } func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string { pointer, err := lfs.GeneratePointer(bytes.NewReader(*content)) - assert.NoError(t, err) + require.NoError(t, err) _, err = git_model.NewLFSMetaObject(db.DefaultContext, repositoryID, pointer) - assert.NoError(t, err) + require.NoError(t, err) contentStore := lfs.NewContentStore() exist, err := contentStore.Exists(pointer) - assert.NoError(t, err) + require.NoError(t, err) if !exist { err := contentStore.Put(pointer, bytes.NewReader(*content)) - assert.NoError(t, err) + require.NoError(t, err) } return pointer.Oid } diff --git a/services/repository/repository_test.go b/services/repository/repository_test.go index 892a11a23e..a5c0b3efcd 100644 --- a/services/repository/repository_test.go +++ b/services/repository/repository_test.go @@ -12,10 +12,11 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLinkedRepository(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testCases := []struct { name string attachID int64 @@ -30,9 +31,9 @@ func TestLinkedRepository(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { attach, err := repo_model.GetAttachmentByID(db.DefaultContext, tc.attachID) - assert.NoError(t, err) + require.NoError(t, err) repo, unitType, err := LinkedRepository(db.DefaultContext, attach) - assert.NoError(t, err) + require.NoError(t, err) if tc.expectedRepo != nil { assert.Equal(t, tc.expectedRepo.ID, repo.ID) } diff --git a/services/repository/review_test.go b/services/repository/review_test.go index 2db56d4e8a..eb1712c2ce 100644 --- a/services/repository/review_test.go +++ b/services/repository/review_test.go @@ -11,18 +11,19 @@ import ( "code.gitea.io/gitea/models/unittest" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepoGetReviewerTeams(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) teams, err := GetReviewerTeams(db.DefaultContext, repo2) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, teams) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) teams, err = GetReviewerTeams(db.DefaultContext, repo3) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, teams, 2) } diff --git a/services/repository/transfer_test.go b/services/repository/transfer_test.go index b201b5cb98..cc51a05781 100644 --- a/services/repository/transfer_test.go +++ b/services/repository/transfer_test.go @@ -20,6 +20,7 @@ import ( notify_service "code.gitea.io/gitea/services/notify" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var notifySync sync.Once @@ -33,21 +34,21 @@ func registerNotifier() { func TestTransferOwnership(t *testing.T) { registerNotifier() - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) repo.Owner = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - assert.NoError(t, TransferOwnership(db.DefaultContext, doer, doer, repo, nil)) + require.NoError(t, TransferOwnership(db.DefaultContext, doer, doer, repo, nil)) transferredRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) assert.EqualValues(t, 2, transferredRepo.OwnerID) exist, err := util.IsExist(repo_model.RepoPath("org3", "repo3")) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exist) exist, err = util.IsExist(repo_model.RepoPath("user2", "repo3")) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exist) unittest.AssertExistsAndLoadBean(t, &activities_model.Action{ OpType: activities_model.ActionTransferRepo, @@ -60,7 +61,7 @@ func TestTransferOwnership(t *testing.T) { } func TestStartRepositoryTransferSetPermission(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) recipient := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) @@ -68,56 +69,56 @@ func TestStartRepositoryTransferSetPermission(t *testing.T) { repo.Owner = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) hasAccess, err := access_model.HasAccess(db.DefaultContext, recipient.ID, repo) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, hasAccess) - assert.NoError(t, StartRepositoryTransfer(db.DefaultContext, doer, recipient, repo, nil)) + require.NoError(t, StartRepositoryTransfer(db.DefaultContext, doer, recipient, repo, nil)) hasAccess, err = access_model.HasAccess(db.DefaultContext, recipient.ID, repo) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, hasAccess) unittest.CheckConsistencyFor(t, &repo_model.Repository{}, &user_model.User{}, &organization.Team{}) } func TestRepositoryTransfer(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) transfer, err := models.GetPendingRepositoryTransfer(db.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, transfer) // Cancel transfer - assert.NoError(t, CancelRepositoryTransfer(db.DefaultContext, repo)) + require.NoError(t, CancelRepositoryTransfer(db.DefaultContext, repo)) transfer, err = models.GetPendingRepositoryTransfer(db.DefaultContext, repo) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, transfer) assert.True(t, models.IsErrNoPendingTransfer(err)) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.NoError(t, models.CreatePendingRepositoryTransfer(db.DefaultContext, doer, user2, repo.ID, nil)) + require.NoError(t, models.CreatePendingRepositoryTransfer(db.DefaultContext, doer, user2, repo.ID, nil)) transfer, err = models.GetPendingRepositoryTransfer(db.DefaultContext, repo) - assert.Nil(t, err) - assert.NoError(t, transfer.LoadAttributes(db.DefaultContext)) + require.NoError(t, err) + require.NoError(t, transfer.LoadAttributes(db.DefaultContext)) assert.Equal(t, "user2", transfer.Recipient.Name) org6 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) // Only transfer can be started at any given time err = models.CreatePendingRepositoryTransfer(db.DefaultContext, doer, org6, repo.ID, nil) - assert.Error(t, err) + require.Error(t, err) assert.True(t, models.IsErrRepoTransferInProgress(err)) // Unknown user err = models.CreatePendingRepositoryTransfer(db.DefaultContext, doer, &user_model.User{ID: 1000, LowerName: "user1000"}, repo.ID, nil) - assert.Error(t, err) + require.Error(t, err) // Cancel transfer - assert.NoError(t, CancelRepositoryTransfer(db.DefaultContext, repo)) + require.NoError(t, CancelRepositoryTransfer(db.DefaultContext, repo)) } diff --git a/services/user/avatar_test.go b/services/user/avatar_test.go index 557ddccec0..21fca8dd09 100644 --- a/services/user/avatar_test.go +++ b/services/user/avatar_test.go @@ -17,6 +17,7 @@ import ( "code.gitea.io/gitea/modules/test" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type alreadyDeletedStorage struct { @@ -35,18 +36,18 @@ func TestUserDeleteAvatar(t *testing.T) { t.Run("AtomicStorageFailure", func(t *testing.T) { defer test.MockProtect[storage.ObjectStorage](&storage.Avatars)() - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) err := UploadAvatar(db.DefaultContext, user, buff.Bytes()) - assert.NoError(t, err) + require.NoError(t, err) verification := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) assert.NotEqual(t, "", verification.Avatar) // fail to delete ... storage.Avatars = storage.UninitializedStorage err = DeleteAvatar(db.DefaultContext, user) - assert.Error(t, err) + require.Error(t, err) // ... the avatar is not removed from the database verification = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -55,7 +56,7 @@ func TestUserDeleteAvatar(t *testing.T) { // already deleted ... storage.Avatars = alreadyDeletedStorage{} err = DeleteAvatar(db.DefaultContext, user) - assert.NoError(t, err) + require.NoError(t, err) // ... the avatar is removed from the database verification = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -63,16 +64,16 @@ func TestUserDeleteAvatar(t *testing.T) { }) t.Run("Success", func(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) err := UploadAvatar(db.DefaultContext, user, buff.Bytes()) - assert.NoError(t, err) + require.NoError(t, err) verification := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) assert.NotEqual(t, "", verification.Avatar) err = DeleteAvatar(db.DefaultContext, user) - assert.NoError(t, err) + require.NoError(t, err) verification = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) assert.Equal(t, "", verification.Avatar) diff --git a/services/user/block_test.go b/services/user/block_test.go index 121c1ea8b7..f9e95ed7f7 100644 --- a/services/user/block_test.go +++ b/services/user/block_test.go @@ -13,12 +13,13 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // TestBlockUser will ensure that when you block a user, certain actions have // been taken, like unfollowing each other etc. func TestBlockUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) blockedUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) @@ -27,10 +28,10 @@ func TestBlockUser(t *testing.T) { defer user_model.UnblockUser(db.DefaultContext, doer.ID, blockedUser.ID) // Follow each other. - assert.NoError(t, user_model.FollowUser(db.DefaultContext, doer.ID, blockedUser.ID)) - assert.NoError(t, user_model.FollowUser(db.DefaultContext, blockedUser.ID, doer.ID)) + require.NoError(t, user_model.FollowUser(db.DefaultContext, doer.ID, blockedUser.ID)) + require.NoError(t, user_model.FollowUser(db.DefaultContext, blockedUser.ID, doer.ID)) - assert.NoError(t, BlockUser(db.DefaultContext, doer.ID, blockedUser.ID)) + require.NoError(t, BlockUser(db.DefaultContext, doer.ID, blockedUser.ID)) // Ensure they aren't following each other anymore. assert.False(t, user_model.IsFollowing(db.DefaultContext, doer.ID, blockedUser.ID)) @@ -42,9 +43,9 @@ func TestBlockUser(t *testing.T) { // Blocked user watch repository of doer. repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: doer.ID}) - assert.NoError(t, repo_model.WatchRepo(db.DefaultContext, blockedUser.ID, repo.ID, true)) + require.NoError(t, repo_model.WatchRepo(db.DefaultContext, blockedUser.ID, repo.ID, true)) - assert.NoError(t, BlockUser(db.DefaultContext, doer.ID, blockedUser.ID)) + require.NoError(t, BlockUser(db.DefaultContext, doer.ID, blockedUser.ID)) // Ensure blocked user isn't following doer's repository. assert.False(t, repo_model.IsWatching(db.DefaultContext, blockedUser.ID, repo.ID)) @@ -59,14 +60,14 @@ func TestBlockUser(t *testing.T) { isBlockedUserCollab := func(repo *repo_model.Repository) bool { isCollaborator, err := repo_model.IsCollaborator(db.DefaultContext, repo.ID, blockedUser.ID) - assert.NoError(t, err) + require.NoError(t, err) return isCollaborator } assert.True(t, isBlockedUserCollab(repo1)) assert.True(t, isBlockedUserCollab(repo2)) - assert.NoError(t, BlockUser(db.DefaultContext, doer.ID, blockedUser.ID)) + require.NoError(t, BlockUser(db.DefaultContext, doer.ID, blockedUser.ID)) assert.False(t, isBlockedUserCollab(repo1)) assert.False(t, isBlockedUserCollab(repo2)) @@ -80,7 +81,7 @@ func TestBlockUser(t *testing.T) { unittest.AssertExistsIf(t, true, &repo_model.Repository{ID: 3, OwnerID: blockedUser.ID, Status: repo_model.RepositoryPendingTransfer}) unittest.AssertExistsIf(t, true, &model.RepoTransfer{ID: 1, RecipientID: doer.ID, DoerID: blockedUser.ID}) - assert.NoError(t, BlockUser(db.DefaultContext, doer.ID, blockedUser.ID)) + require.NoError(t, BlockUser(db.DefaultContext, doer.ID, blockedUser.ID)) unittest.AssertExistsIf(t, false, &model.RepoTransfer{ID: 1, RecipientID: doer.ID, DoerID: blockedUser.ID}) diff --git a/services/user/email_test.go b/services/user/email_test.go index 74f8b8d010..86f31a8984 100644 --- a/services/user/email_test.go +++ b/services/user/email_test.go @@ -18,28 +18,28 @@ import ( ) func TestAdminAddOrSetPrimaryEmailAddress(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 27}) emails, err := user_model.GetEmailAddresses(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, emails, 1) primary, err := user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, "new-primary@example.com", primary.Email) assert.Equal(t, user.Email, primary.Email) - assert.NoError(t, AdminAddOrSetPrimaryEmailAddress(db.DefaultContext, user, "new-primary@example.com")) + require.NoError(t, AdminAddOrSetPrimaryEmailAddress(db.DefaultContext, user, "new-primary@example.com")) primary, err = user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "new-primary@example.com", primary.Email) assert.Equal(t, user.Email, primary.Email) emails, err = user_model.GetEmailAddresses(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, emails, 2) setting.Service.EmailDomainAllowList = []glob.Glob{glob.MustCompile("example.org")} @@ -47,52 +47,52 @@ func TestAdminAddOrSetPrimaryEmailAddress(t *testing.T) { setting.Service.EmailDomainAllowList = []glob.Glob{} }() - assert.NoError(t, AdminAddOrSetPrimaryEmailAddress(db.DefaultContext, user, "new-primary2@example2.com")) + require.NoError(t, AdminAddOrSetPrimaryEmailAddress(db.DefaultContext, user, "new-primary2@example2.com")) primary, err = user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "new-primary2@example2.com", primary.Email) assert.Equal(t, user.Email, primary.Email) - assert.NoError(t, AdminAddOrSetPrimaryEmailAddress(db.DefaultContext, user, "user27@example.com")) + require.NoError(t, AdminAddOrSetPrimaryEmailAddress(db.DefaultContext, user, "user27@example.com")) primary, err = user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "user27@example.com", primary.Email) assert.Equal(t, user.Email, primary.Email) emails, err = user_model.GetEmailAddresses(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, emails, 3) } func TestReplacePrimaryEmailAddress(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) t.Run("User", func(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 13}) emails, err := user_model.GetEmailAddresses(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, emails, 1) primary, err := user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, "primary-13@example.com", primary.Email) assert.Equal(t, user.Email, primary.Email) - assert.NoError(t, ReplacePrimaryEmailAddress(db.DefaultContext, user, "primary-13@example.com")) + require.NoError(t, ReplacePrimaryEmailAddress(db.DefaultContext, user, "primary-13@example.com")) primary, err = user_model.GetPrimaryEmailAddressOfUser(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "primary-13@example.com", primary.Email) assert.Equal(t, user.Email, primary.Email) emails, err = user_model.GetEmailAddresses(db.DefaultContext, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, emails, 1) - assert.NoError(t, ReplacePrimaryEmailAddress(db.DefaultContext, user, "primary-13@example.com")) + require.NoError(t, ReplacePrimaryEmailAddress(db.DefaultContext, user, "primary-13@example.com")) }) t.Run("Organization", func(t *testing.T) { @@ -100,37 +100,37 @@ func TestReplacePrimaryEmailAddress(t *testing.T) { assert.Equal(t, "org3@example.com", org.Email) - assert.NoError(t, ReplacePrimaryEmailAddress(db.DefaultContext, org.AsUser(), "primary-org@example.com")) + require.NoError(t, ReplacePrimaryEmailAddress(db.DefaultContext, org.AsUser(), "primary-org@example.com")) assert.Equal(t, "primary-org@example.com", org.Email) }) } func TestAddEmailAddresses(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.Error(t, AddEmailAddresses(db.DefaultContext, user, []string{" invalid email "})) + require.Error(t, AddEmailAddresses(db.DefaultContext, user, []string{" invalid email "})) emails := []string{"user1234@example.com", "user5678@example.com"} - assert.NoError(t, AddEmailAddresses(db.DefaultContext, user, emails)) + require.NoError(t, AddEmailAddresses(db.DefaultContext, user, emails)) err := AddEmailAddresses(db.DefaultContext, user, emails) - assert.Error(t, err) + require.Error(t, err) assert.True(t, user_model.IsErrEmailAlreadyUsed(err)) } func TestReplaceInactivePrimaryEmail(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) email := &user_model.EmailAddress{ Email: "user9999999@example.com", UID: 9999999, } err := ReplaceInactivePrimaryEmail(db.DefaultContext, "user10@example.com", email) - assert.Error(t, err) + require.Error(t, err) assert.True(t, user_model.IsErrUserNotExist(err)) email = &user_model.EmailAddress{ @@ -138,30 +138,30 @@ func TestReplaceInactivePrimaryEmail(t *testing.T) { UID: 10, } err = ReplaceInactivePrimaryEmail(db.DefaultContext, "user10@example.com", email) - assert.NoError(t, err) + require.NoError(t, err) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 10}) assert.Equal(t, "user201@example.com", user.Email) } func TestDeleteEmailAddresses(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) emails := []string{"user2-2@example.com"} err := DeleteEmailAddresses(db.DefaultContext, user, emails) - assert.NoError(t, err) + require.NoError(t, err) err = DeleteEmailAddresses(db.DefaultContext, user, emails) - assert.Error(t, err) + require.Error(t, err) assert.True(t, user_model.IsErrEmailAddressNotExist(err)) emails = []string{"user2@example.com"} err = DeleteEmailAddresses(db.DefaultContext, user, emails) - assert.Error(t, err) + require.Error(t, err) assert.True(t, user_model.IsErrPrimaryEmailCannotDelete(err)) } diff --git a/services/user/update_test.go b/services/user/update_test.go index fc24a6c212..11379d4508 100644 --- a/services/user/update_test.go +++ b/services/user/update_test.go @@ -14,14 +14,15 @@ import ( "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUpdateUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - assert.Error(t, UpdateUser(db.DefaultContext, admin, &UpdateOptions{ + require.Error(t, UpdateUser(db.DefaultContext, admin, &UpdateOptions{ IsAdmin: optional.Some(false), })) @@ -48,7 +49,7 @@ func TestUpdateUser(t *testing.T) { EmailNotificationsPreference: optional.Some("disabled"), SetLastLogin: true, } - assert.NoError(t, UpdateUser(db.DefaultContext, user, opts)) + require.NoError(t, UpdateUser(db.DefaultContext, user, opts)) assert.Equal(t, opts.KeepEmailPrivate.Value(), user.KeepEmailPrivate) assert.Equal(t, opts.FullName.Value(), user.FullName) @@ -91,17 +92,17 @@ func TestUpdateUser(t *testing.T) { } func TestUpdateAuth(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 28}) userCopy := *user - assert.NoError(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ + require.NoError(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ LoginName: optional.Some("new-login"), })) assert.Equal(t, "new-login", user.LoginName) - assert.NoError(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ + require.NoError(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ Password: optional.Some("%$DRZUVB576tfzgu"), MustChangePassword: optional.Some(true), })) @@ -109,12 +110,12 @@ func TestUpdateAuth(t *testing.T) { assert.NotEqual(t, userCopy.Passwd, user.Passwd) assert.NotEqual(t, userCopy.Salt, user.Salt) - assert.NoError(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ + require.NoError(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ ProhibitLogin: optional.Some(true), })) assert.True(t, user.ProhibitLogin) - assert.ErrorIs(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ + require.ErrorIs(t, UpdateAuth(db.DefaultContext, user, &UpdateAuthOptions{ Password: optional.Some("aaaa"), }), password_module.ErrMinLength) } diff --git a/services/user/user_test.go b/services/user/user_test.go index 9013208ed0..45bf1e6993 100644 --- a/services/user/user_test.go +++ b/services/user/user_test.go @@ -20,6 +20,7 @@ import ( "code.gitea.io/gitea/modules/timeutil" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -28,27 +29,27 @@ func TestMain(m *testing.M) { func TestDeleteUser(t *testing.T) { test := func(userID int64) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID}) ownedRepos := make([]*repo_model.Repository, 0, 10) - assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&ownedRepos, &repo_model.Repository{OwnerID: userID})) + require.NoError(t, db.GetEngine(db.DefaultContext).Find(&ownedRepos, &repo_model.Repository{OwnerID: userID})) if len(ownedRepos) > 0 { err := DeleteUser(db.DefaultContext, user, false) - assert.Error(t, err) + require.Error(t, err) assert.True(t, models.IsErrUserOwnRepos(err)) return } orgUsers := make([]*organization.OrgUser, 0, 10) - assert.NoError(t, db.GetEngine(db.DefaultContext).Find(&orgUsers, &organization.OrgUser{UID: userID})) + require.NoError(t, db.GetEngine(db.DefaultContext).Find(&orgUsers, &organization.OrgUser{UID: userID})) for _, orgUser := range orgUsers { if err := models.RemoveOrgUser(db.DefaultContext, orgUser.OrgID, orgUser.UID); err != nil { assert.True(t, organization.IsErrLastOrgOwner(err)) return } } - assert.NoError(t, DeleteUser(db.DefaultContext, user, false)) + require.NoError(t, DeleteUser(db.DefaultContext, user, false)) unittest.AssertNotExistsBean(t, &user_model.User{ID: userID}) unittest.CheckConsistencyFor(t, &user_model.User{}, &repo_model.Repository{}) } @@ -58,16 +59,16 @@ func TestDeleteUser(t *testing.T) { test(11) org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) - assert.Error(t, DeleteUser(db.DefaultContext, org, false)) + require.Error(t, DeleteUser(db.DefaultContext, org, false)) } func TestPurgeUser(t *testing.T) { test := func(userID int64) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userID}) err := DeleteUser(db.DefaultContext, user, true) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertNotExistsBean(t, &user_model.User{ID: userID}) unittest.CheckConsistencyFor(t, &user_model.User{}, &repo_model.Repository{}) @@ -78,7 +79,7 @@ func TestPurgeUser(t *testing.T) { test(11) org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) - assert.Error(t, DeleteUser(db.DefaultContext, org, false)) + require.Error(t, DeleteUser(db.DefaultContext, org, false)) } func TestCreateUser(t *testing.T) { @@ -91,13 +92,13 @@ func TestCreateUser(t *testing.T) { MustChangePassword: false, } - assert.NoError(t, user_model.CreateUser(db.DefaultContext, user)) + require.NoError(t, user_model.CreateUser(db.DefaultContext, user)) - assert.NoError(t, DeleteUser(db.DefaultContext, user, false)) + require.NoError(t, DeleteUser(db.DefaultContext, user, false)) } func TestRenameUser(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 21}) t.Run("Non-Local", func(t *testing.T) { @@ -105,19 +106,19 @@ func TestRenameUser(t *testing.T) { Type: user_model.UserTypeIndividual, LoginType: auth.OAuth2, } - assert.ErrorIs(t, RenameUser(db.DefaultContext, u, "user_rename"), user_model.ErrUserIsNotLocal{}) + require.ErrorIs(t, RenameUser(db.DefaultContext, u, "user_rename"), user_model.ErrUserIsNotLocal{}) }) t.Run("Same username", func(t *testing.T) { - assert.NoError(t, RenameUser(db.DefaultContext, user, user.Name)) + require.NoError(t, RenameUser(db.DefaultContext, user, user.Name)) }) t.Run("Non usable username", func(t *testing.T) { usernames := []string{"--diff", "aa.png", ".well-known", "search", "aaa.atom"} for _, username := range usernames { t.Run(username, func(t *testing.T) { - assert.Error(t, user_model.IsUsableUsername(username)) - assert.Error(t, RenameUser(db.DefaultContext, user, username)) + require.Error(t, user_model.IsUsableUsername(username)) + require.Error(t, RenameUser(db.DefaultContext, user, username)) }) } }) @@ -127,7 +128,7 @@ func TestRenameUser(t *testing.T) { unittest.AssertNotExistsBean(t, &user_model.User{ID: user.ID, Name: caps}) unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID, OwnerName: user.Name}) - assert.NoError(t, RenameUser(db.DefaultContext, user, caps)) + require.NoError(t, RenameUser(db.DefaultContext, user, caps)) unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: user.ID, Name: caps}) unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID, OwnerName: caps}) @@ -136,21 +137,21 @@ func TestRenameUser(t *testing.T) { t.Run("Already exists", func(t *testing.T) { existUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) - assert.ErrorIs(t, RenameUser(db.DefaultContext, user, existUser.Name), user_model.ErrUserAlreadyExist{Name: existUser.Name}) - assert.ErrorIs(t, RenameUser(db.DefaultContext, user, existUser.LowerName), user_model.ErrUserAlreadyExist{Name: existUser.LowerName}) + require.ErrorIs(t, RenameUser(db.DefaultContext, user, existUser.Name), user_model.ErrUserAlreadyExist{Name: existUser.Name}) + require.ErrorIs(t, RenameUser(db.DefaultContext, user, existUser.LowerName), user_model.ErrUserAlreadyExist{Name: existUser.LowerName}) newUsername := fmt.Sprintf("uSEr%d", existUser.ID) - assert.ErrorIs(t, RenameUser(db.DefaultContext, user, newUsername), user_model.ErrUserAlreadyExist{Name: newUsername}) + require.ErrorIs(t, RenameUser(db.DefaultContext, user, newUsername), user_model.ErrUserAlreadyExist{Name: newUsername}) }) t.Run("Normal", func(t *testing.T) { oldUsername := user.Name newUsername := "User_Rename" - assert.NoError(t, RenameUser(db.DefaultContext, user, newUsername)) + require.NoError(t, RenameUser(db.DefaultContext, user, newUsername)) unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: user.ID, Name: newUsername, LowerName: strings.ToLower(newUsername)}) redirectUID, err := user_model.LookupUserRedirect(db.DefaultContext, oldUsername) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, user.ID, redirectUID) unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: user.ID, OwnerName: user.Name}) @@ -176,37 +177,37 @@ func TestCreateUser_Issue5882(t *testing.T) { for _, v := range tt { setting.Admin.DisableRegularOrgCreation = v.disableOrgCreation - assert.NoError(t, user_model.CreateUser(db.DefaultContext, v.user)) + require.NoError(t, user_model.CreateUser(db.DefaultContext, v.user)) u, err := user_model.GetUserByEmail(db.DefaultContext, v.user.Email) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, !u.AllowCreateOrganization, v.disableOrgCreation) - assert.NoError(t, DeleteUser(db.DefaultContext, v.user, false)) + require.NoError(t, DeleteUser(db.DefaultContext, v.user, false)) } } func TestDeleteInactiveUsers(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // Add an inactive user older than a minute, with an associated email_address record. oldUser := &user_model.User{Name: "OldInactive", LowerName: "oldinactive", Email: "old@example.com", CreatedUnix: timeutil.TimeStampNow().Add(-120)} _, err := db.GetEngine(db.DefaultContext).NoAutoTime().Insert(oldUser) - assert.NoError(t, err) + require.NoError(t, err) oldEmail := &user_model.EmailAddress{UID: oldUser.ID, IsPrimary: true, Email: "old@example.com", LowerEmail: "old@example.com"} err = db.Insert(db.DefaultContext, oldEmail) - assert.NoError(t, err) + require.NoError(t, err) // Add an inactive user that's not older than a minute, with an associated email_address record. newUser := &user_model.User{Name: "NewInactive", LowerName: "newinactive", Email: "new@example.com"} err = db.Insert(db.DefaultContext, newUser) - assert.NoError(t, err) + require.NoError(t, err) newEmail := &user_model.EmailAddress{UID: newUser.ID, IsPrimary: true, Email: "new@example.com", LowerEmail: "new@example.com"} err = db.Insert(db.DefaultContext, newEmail) - assert.NoError(t, err) + require.NoError(t, err) err = DeleteInactiveUsers(db.DefaultContext, time.Minute) - assert.NoError(t, err) + require.NoError(t, err) // User older than a minute should be deleted along with their email address. unittest.AssertExistsIf(t, false, oldUser) diff --git a/services/webhook/default_test.go b/services/webhook/default_test.go index e6e59fed03..f3e2848659 100644 --- a/services/webhook/default_test.go +++ b/services/webhook/default_test.go @@ -58,7 +58,7 @@ func TestGiteaPayload(t *testing.T) { Ref string `json:"ref"` } err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "test", body.Ref) // short ref }) @@ -87,7 +87,7 @@ func TestGiteaPayload(t *testing.T) { Ref string `json:"ref"` } err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "refs/heads/test", body.Ref) // full ref }) @@ -116,7 +116,7 @@ func TestGiteaPayload(t *testing.T) { Ref string `json:"ref"` } err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "test", body.Ref) // short ref }) } @@ -161,7 +161,7 @@ func TestForgejoPayload(t *testing.T) { Ref string `json:"ref"` } err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "refs/heads/test", body.Ref) // full ref }) @@ -190,7 +190,7 @@ func TestForgejoPayload(t *testing.T) { Ref string `json:"ref"` } err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "refs/heads/test", body.Ref) // full ref }) @@ -219,7 +219,7 @@ func TestForgejoPayload(t *testing.T) { Ref string `json:"ref"` } err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "refs/heads/test", body.Ref) // full ref }) } @@ -245,9 +245,9 @@ func TestOpenProjectPayload(t *testing.T) { assert.Equal(t, "test/repo", j.Get("base", "repo", "full_name").MustBeValid().ToString()) assert.Equal(t, "http://localhost:3000/test/repo", j.Get("base", "repo", "html_url").MustBeValid().ToString()) - assert.Equal(t, false, j.Get("draft").MustBeValid().ToBool()) + assert.False(t, j.Get("draft").MustBeValid().ToBool()) assert.Equal(t, jsoniter.NilValue, j.Get("merge_commit_sha").ValueType()) - assert.Equal(t, false, j.Get("merged").MustBeValid().ToBool()) + assert.False(t, j.Get("merged").MustBeValid().ToBool()) assert.Equal(t, jsoniter.NilValue, j.Get("merged_by").ValueType()) assert.Equal(t, jsoniter.NilValue, j.Get("merged_at").ValueType()) assert.Equal(t, 0, j.Get("comments").MustBeValid().ToInt()) diff --git a/services/webhook/deliver_test.go b/services/webhook/deliver_test.go index 0311d810e6..21af3c7116 100644 --- a/services/webhook/deliver_test.go +++ b/services/webhook/deliver_test.go @@ -76,11 +76,11 @@ func TestWebhookProxy(t *testing.T) { u, err := webhookProxy(allowedHostMatcher)(req) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) got := "" if u != nil { @@ -92,7 +92,7 @@ func TestWebhookProxy(t *testing.T) { } func TestWebhookDeliverAuthorizationHeader(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) done := make(chan struct{}, 1) s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -111,8 +111,8 @@ func TestWebhookDeliverAuthorizationHeader(t *testing.T) { Type: webhook_module.GITEA, } err := hook.SetHeaderAuthorization("Bearer s3cr3t-t0ken") - assert.NoError(t, err) - assert.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) + require.NoError(t, err) + require.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) hookTask := &webhook_model.HookTask{ HookID: hook.ID, @@ -121,10 +121,10 @@ func TestWebhookDeliverAuthorizationHeader(t *testing.T) { } hookTask, err = webhook_model.CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, hookTask) - assert.NoError(t, Deliver(context.Background(), hookTask)) + require.NoError(t, Deliver(context.Background(), hookTask)) select { case <-done: case <-time.After(5 * time.Second): @@ -136,7 +136,7 @@ func TestWebhookDeliverAuthorizationHeader(t *testing.T) { } func TestWebhookDeliverHookTask(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) done := make(chan struct{}, 1) s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -147,14 +147,14 @@ func TestWebhookDeliverHookTask(t *testing.T) { assert.Equal(t, "push", r.Header.Get("X-GitHub-Event")) assert.Equal(t, "", r.Header.Get("Content-Type")) body, err := io.ReadAll(r.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, `{"data": 42}`, string(body)) case "/webhook/6db5dc1e282529a8c162c7fe93dd2667494eeb51": // Version 2 assert.Equal(t, "application/json", r.Header.Get("Content-Type")) body, err := io.ReadAll(r.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, body, 2147) default: @@ -176,7 +176,7 @@ func TestWebhookDeliverHookTask(t *testing.T) { ContentType: webhook_model.ContentTypeJSON, Meta: `{"message_type":0}`, // text } - assert.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) + require.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) t.Run("Version 1", func(t *testing.T) { hookTask := &webhook_model.HookTask{ @@ -187,10 +187,10 @@ func TestWebhookDeliverHookTask(t *testing.T) { } hookTask, err := webhook_model.CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, hookTask) - assert.NoError(t, Deliver(context.Background(), hookTask)) + require.NoError(t, Deliver(context.Background(), hookTask)) select { case <-done: case <-time.After(5 * time.Second): @@ -203,7 +203,7 @@ func TestWebhookDeliverHookTask(t *testing.T) { t.Run("Version 2", func(t *testing.T) { p := pushTestPayload() data, err := p.JSONPayload() - assert.NoError(t, err) + require.NoError(t, err) hookTask := &webhook_model.HookTask{ HookID: hook.ID, @@ -213,10 +213,10 @@ func TestWebhookDeliverHookTask(t *testing.T) { } hookTask, err = webhook_model.CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, hookTask) - assert.NoError(t, Deliver(context.Background(), hookTask)) + require.NoError(t, Deliver(context.Background(), hookTask)) select { case <-done: case <-time.After(5 * time.Second): @@ -228,7 +228,7 @@ func TestWebhookDeliverHookTask(t *testing.T) { } func TestWebhookDeliverSpecificTypes(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) type hookCase struct { gotBody chan []byte @@ -280,7 +280,7 @@ func TestWebhookDeliverSpecificTypes(t *testing.T) { require.NotNil(t, hc.gotBody, r.URL.Path) body, err := io.ReadAll(r.Body) - assert.NoError(t, err) + require.NoError(t, err) w.WriteHeader(200) hc.gotBody <- body })) @@ -288,7 +288,7 @@ func TestWebhookDeliverSpecificTypes(t *testing.T) { p := pushTestPayload() data, err := p.JSONPayload() - assert.NoError(t, err) + require.NoError(t, err) for typ, hc := range cases { typ := typ @@ -304,7 +304,7 @@ func TestWebhookDeliverSpecificTypes(t *testing.T) { ContentType: 0, // set to 0 so that falling back to default request fails with "invalid content type" Meta: "{}", } - assert.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) + require.NoError(t, webhook_model.CreateWebhook(db.DefaultContext, hook)) hookTask := &webhook_model.HookTask{ HookID: hook.ID, @@ -314,10 +314,10 @@ func TestWebhookDeliverSpecificTypes(t *testing.T) { } hookTask, err := webhook_model.CreateHookTask(db.DefaultContext, hookTask) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, hookTask) - assert.NoError(t, Deliver(context.Background(), hookTask)) + require.NoError(t, Deliver(context.Background(), hookTask)) select { case gotBody := <-hc.gotBody: assert.NotEqual(t, string(data), string(gotBody), "request body must be different from the event payload") diff --git a/services/webhook/dingtalk_test.go b/services/webhook/dingtalk_test.go index 073904f660..d0a2d48908 100644 --- a/services/webhook/dingtalk_test.go +++ b/services/webhook/dingtalk_test.go @@ -247,6 +247,6 @@ func TestDingTalkJSONPayload(t *testing.T) { assert.Equal(t, "application/json", req.Header.Get("Content-Type")) var body DingtalkPayload err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "[2020558](http://localhost:3000/test/repo/commit/2020558fe2e34debb818a514715839cabd25e778) commit message - user1\r\n[2020558](http://localhost:3000/test/repo/commit/2020558fe2e34debb818a514715839cabd25e778) commit message - user1", body.ActionCard.Text) } diff --git a/services/webhook/discord_test.go b/services/webhook/discord_test.go index 895914ab2f..73be143f46 100644 --- a/services/webhook/discord_test.go +++ b/services/webhook/discord_test.go @@ -286,6 +286,6 @@ func TestDiscordJSONPayload(t *testing.T) { assert.Equal(t, "application/json", req.Header.Get("Content-Type")) var body DiscordPayload err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "[2020558](http://localhost:3000/test/repo/commit/2020558fe2e34debb818a514715839cabd25e778) commit message - user1\n[2020558](http://localhost:3000/test/repo/commit/2020558fe2e34debb818a514715839cabd25e778) commit message - user1", body.Embeds[0].Description) } diff --git a/services/webhook/feishu_test.go b/services/webhook/feishu_test.go index f591133cbd..9744571b39 100644 --- a/services/webhook/feishu_test.go +++ b/services/webhook/feishu_test.go @@ -188,6 +188,6 @@ func TestFeishuJSONPayload(t *testing.T) { assert.Equal(t, "application/json", req.Header.Get("Content-Type")) var body FeishuPayload err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "[test/repo:test] \r\n[2020558](http://localhost:3000/test/repo/commit/2020558fe2e34debb818a514715839cabd25e778) commit message - user1\r\n[2020558](http://localhost:3000/test/repo/commit/2020558fe2e34debb818a514715839cabd25e778) commit message - user1", body.Content.Text) } diff --git a/services/webhook/matrix_test.go b/services/webhook/matrix_test.go index 7031a45bec..6cedb15ef3 100644 --- a/services/webhook/matrix_test.go +++ b/services/webhook/matrix_test.go @@ -221,7 +221,7 @@ func TestMatrixJSONPayload(t *testing.T) { assert.Equal(t, "application/json", req.Header.Get("Content-Type")) var body MatrixPayload err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "[[test/repo](http://localhost:3000/test/repo)] user1 pushed 2 commits to [test](http://localhost:3000/test/repo/src/branch/test):\n[2020558](http://localhost:3000/test/repo/commit/2020558fe2e34debb818a514715839cabd25e778): commit message - user1\n[2020558](http://localhost:3000/test/repo/commit/2020558fe2e34debb818a514715839cabd25e778): commit message - user1", body.Body) } diff --git a/services/webhook/msteams_test.go b/services/webhook/msteams_test.go index c63ad1f89a..a97e9f3de3 100644 --- a/services/webhook/msteams_test.go +++ b/services/webhook/msteams_test.go @@ -450,6 +450,6 @@ func TestMSTeamsJSONPayload(t *testing.T) { assert.Equal(t, "application/json", req.Header.Get("Content-Type")) var body MSTeamsPayload err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "[test/repo:test] 2 new commits", body.Summary) } diff --git a/services/webhook/packagist_test.go b/services/webhook/packagist_test.go index d7374fde09..320c1c85a1 100644 --- a/services/webhook/packagist_test.go +++ b/services/webhook/packagist_test.go @@ -63,7 +63,7 @@ func TestPackagistPayload(t *testing.T) { assert.Equal(t, "application/json", req.Header.Get("Content-Type")) var body PackagistPayload err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "https://packagist.org/packages/example", body.PackagistRepository.URL) }) } diff --git a/services/webhook/slack_test.go b/services/webhook/slack_test.go index 58f4e78878..3d801843ae 100644 --- a/services/webhook/slack_test.go +++ b/services/webhook/slack_test.go @@ -189,7 +189,7 @@ func TestSlackJSONPayload(t *testing.T) { assert.Equal(t, "application/json", req.Header.Get("Content-Type")) var body SlackPayload err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "[:] 2 new commits pushed by user1", body.Text) } @@ -217,11 +217,12 @@ func TestSlackMetadata(t *testing.T) { Meta: `{"channel": "foo", "username": "username", "color": "blue"}`, } slackHook := slackHandler{}.Metadata(w) - assert.Equal(t, *slackHook.(*SlackMeta), SlackMeta{ + assert.Equal(t, SlackMeta{ Channel: "foo", Username: "username", Color: "blue", - }) + }, + *slackHook.(*SlackMeta)) } func TestSlackToHook(t *testing.T) { @@ -242,9 +243,9 @@ func TestSlackToHook(t *testing.T) { }, } h, err := ToHook("repoLink", w) - assert.NoError(t, err) + require.NoError(t, err) - assert.Equal(t, h.Config, map[string]string{ + assert.Equal(t, map[string]string{ "url": "https://slack.example.com", "content_type": "json", @@ -252,13 +253,13 @@ func TestSlackToHook(t *testing.T) { "color": "blue", "icon_url": "", "username": "username", - }) - assert.Equal(t, h.URL, "https://slack.example.com") - assert.Equal(t, h.ContentType, "json") - assert.Equal(t, h.Metadata, &SlackMeta{ + }, h.Config) + assert.Equal(t, "https://slack.example.com", h.URL) + assert.Equal(t, "json", h.ContentType) + assert.Equal(t, &SlackMeta{ Channel: "foo", Username: "username", IconURL: "", Color: "blue", - }) + }, h.Metadata) } diff --git a/services/webhook/sourcehut/builds_test.go b/services/webhook/sourcehut/builds_test.go index 64c6081076..020bbfc9ad 100644 --- a/services/webhook/sourcehut/builds_test.go +++ b/services/webhook/sourcehut/builds_test.go @@ -32,7 +32,7 @@ func gitInit(t testing.TB) { return } t.Cleanup(test.MockVariableValue(&setting.Git.HomePath, t.TempDir())) - assert.NoError(t, git.InitSimple(context.Background())) + require.NoError(t, git.InitSimple(context.Background())) } func TestSourcehutBuildsPayload(t *testing.T) { @@ -129,16 +129,16 @@ tasks: p := &api.DeletePayload{} pl, err := pc.Delete(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) t.Run("Fork", func(t *testing.T) { p := &api.ForkPayload{} pl, err := pc.Fork(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) t.Run("Push/simple", func(t *testing.T) { @@ -250,29 +250,29 @@ triggers: p.Action = api.HookIssueOpened pl, err := pc.Issue(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) p.Action = api.HookIssueClosed pl, err = pc.Issue(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) t.Run("IssueComment", func(t *testing.T) { p := &api.IssueCommentPayload{} pl, err := pc.IssueComment(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) t.Run("PullRequest", func(t *testing.T) { p := &api.PullRequestPayload{} pl, err := pc.PullRequest(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) t.Run("PullRequestComment", func(t *testing.T) { @@ -281,8 +281,8 @@ triggers: } pl, err := pc.IssueComment(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) t.Run("Review", func(t *testing.T) { @@ -290,24 +290,24 @@ triggers: p.Action = api.HookIssueReviewed pl, err := pc.Review(p, webhook_module.HookEventPullRequestReviewApproved) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) t.Run("Repository", func(t *testing.T) { p := &api.RepositoryPayload{} pl, err := pc.Repository(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) t.Run("Package", func(t *testing.T) { p := &api.PackagePayload{} pl, err := pc.Package(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) t.Run("Wiki", func(t *testing.T) { @@ -315,26 +315,26 @@ triggers: p.Action = api.HookWikiCreated pl, err := pc.Wiki(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) p.Action = api.HookWikiEdited pl, err = pc.Wiki(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) p.Action = api.HookWikiDeleted pl, err = pc.Wiki(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) t.Run("Release", func(t *testing.T) { p := &api.ReleasePayload{} pl, err := pc.Release(p) - require.Equal(t, err, shared.ErrPayloadTypeNotSupported) - require.Equal(t, pl, graphqlPayload[buildsVariables]{}) + require.Equal(t, shared.ErrPayloadTypeNotSupported, err) + require.Equal(t, graphqlPayload[buildsVariables]{}, pl) }) } @@ -388,7 +388,7 @@ func TestSourcehutJSONPayload(t *testing.T) { assert.Equal(t, "application/json", req.Header.Get("Content-Type")) var body graphqlPayload[buildsVariables] err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "json test", body.Variables.Note) } @@ -405,7 +405,7 @@ func CreateDeclarativeRepo(t *testing.T, owner *user_model.User, name string, en Readme: "Default", DefaultBranch: "main", }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, repo) t.Cleanup(func() { repo_service.DeleteRepository(db.DefaultContext, owner, repo, false) @@ -421,7 +421,7 @@ func CreateDeclarativeRepo(t *testing.T, owner *user_model.User, name string, en } err := repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, units, disabledUnits) - assert.NoError(t, err) + require.NoError(t, err) } var sha string @@ -444,7 +444,7 @@ func CreateDeclarativeRepo(t *testing.T, owner *user_model.User, name string, en Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp) sha = resp.Commit.SHA diff --git a/services/webhook/telegram_test.go b/services/webhook/telegram_test.go index 65b767f0af..0e27535a03 100644 --- a/services/webhook/telegram_test.go +++ b/services/webhook/telegram_test.go @@ -23,7 +23,7 @@ func TestTelegramPayload(t *testing.T) { p := createTelegramPayload("testMsg ") assert.Equal(t, "HTML", p.ParseMode) - assert.Equal(t, true, p.DisableWebPreview) + assert.True(t, p.DisableWebPreview) assert.Equal(t, "testMsg", p.Message) }) @@ -205,7 +205,7 @@ func TestTelegramJSONPayload(t *testing.T) { assert.Equal(t, "application/json", req.Header.Get("Content-Type")) var body TelegramPayload err = json.NewDecoder(req.Body).Decode(&body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, `[test/repo:test] 2 new commits [2020558] commit message - user1 [2020558] commit message - user1`, body.Message) diff --git a/services/webhook/webhook_test.go b/services/webhook/webhook_test.go index f8b66d46fc..816940a2b5 100644 --- a/services/webhook/webhook_test.go +++ b/services/webhook/webhook_test.go @@ -15,17 +15,18 @@ import ( webhook_module "code.gitea.io/gitea/modules/webhook" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func activateWebhook(t *testing.T, hookID int64) { t.Helper() updated, err := db.GetEngine(db.DefaultContext).ID(hookID).Cols("is_active").Update(webhook_model.Webhook{IsActive: true}) assert.Equal(t, int64(1), updated) - assert.NoError(t, err) + require.NoError(t, err) } func TestPrepareWebhooks(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) activateWebhook(t, 1) @@ -36,7 +37,7 @@ func TestPrepareWebhooks(t *testing.T) { for _, hookTask := range hookTasks { unittest.AssertNotExistsBean(t, hookTask) } - assert.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Commits: []*api.PayloadCommit{{}}})) + require.NoError(t, PrepareWebhooks(db.DefaultContext, EventSource{Repository: repo}, webhook_module.HookEventPush, &api.PushPayload{Commits: []*api.PayloadCommit{{}}})) for _, hookTask := range hookTasks { unittest.AssertExistsAndLoadBean(t, hookTask) } @@ -55,7 +56,7 @@ func eventType(p api.Payloader) webhook_module.HookEventType { } func TestPrepareWebhooksBranchFilterMatch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // branch_filter: {master,feature*} w := unittest.AssertExistsAndLoadBean(t, &webhook_model.Webhook{ID: 4}) @@ -69,7 +70,7 @@ func TestPrepareWebhooksBranchFilterMatch(t *testing.T) { t.Run(fmt.Sprintf("%T", p), func(t *testing.T) { db.DeleteBeans(db.DefaultContext, webhook_model.HookTask{HookID: w.ID}) typ := eventType(p) - assert.NoError(t, PrepareWebhook(db.DefaultContext, w, typ, p)) + require.NoError(t, PrepareWebhook(db.DefaultContext, w, typ, p)) unittest.AssertExistsAndLoadBean(t, &webhook_model.HookTask{ HookID: w.ID, EventType: typ, @@ -79,7 +80,7 @@ func TestPrepareWebhooksBranchFilterMatch(t *testing.T) { } func TestPrepareWebhooksBranchFilterNoMatch(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) // branch_filter: {master,feature*} w := unittest.AssertExistsAndLoadBean(t, &webhook_model.Webhook{ID: 4}) @@ -92,7 +93,7 @@ func TestPrepareWebhooksBranchFilterNoMatch(t *testing.T) { } { t.Run(fmt.Sprintf("%T", p), func(t *testing.T) { db.DeleteBeans(db.DefaultContext, webhook_model.HookTask{HookID: w.ID}) - assert.NoError(t, PrepareWebhook(db.DefaultContext, w, eventType(p), p)) + require.NoError(t, PrepareWebhook(db.DefaultContext, w, eventType(p), p)) unittest.AssertNotExistsBean(t, &webhook_model.HookTask{HookID: w.ID}) }) } diff --git a/services/wiki/wiki_test.go b/services/wiki/wiki_test.go index ef0c3a0a3a..efcc13db99 100644 --- a/services/wiki/wiki_test.go +++ b/services/wiki/wiki_test.go @@ -17,6 +17,7 @@ import ( _ "code.gitea.io/gitea/models/actions" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMain(m *testing.M) { @@ -96,7 +97,7 @@ func TestGitPathToWebPath(t *testing.T) { {"symbols-%2F", "symbols %2F.md"}, } { name, err := GitPathToWebPath(test.Filename) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, test.Expected, name) } for _, badFilename := range []string{ @@ -104,11 +105,11 @@ func TestGitPathToWebPath(t *testing.T) { "wrongfileextension.txt", } { _, err := GitPathToWebPath(badFilename) - assert.Error(t, err) + require.Error(t, err) assert.True(t, repo_model.IsErrWikiInvalidFileName(err)) } _, err := GitPathToWebPath("badescaping%%.md") - assert.Error(t, err) + require.Error(t, err) assert.False(t, repo_model.IsErrWikiInvalidFileName(err)) } @@ -143,16 +144,16 @@ func TestRepository_InitWiki(t *testing.T) { unittest.PrepareTestEnv(t) // repo1 already has a wiki repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) - assert.NoError(t, InitWiki(git.DefaultContext, repo1)) + require.NoError(t, InitWiki(git.DefaultContext, repo1)) // repo2 does not already have a wiki repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) - assert.NoError(t, InitWiki(git.DefaultContext, repo2)) + require.NoError(t, InitWiki(git.DefaultContext, repo2)) assert.True(t, repo2.HasWiki()) } func TestRepository_AddWikiPage(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) const wikiContent = "This is the wiki content" const commitMsg = "Commit message" repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) @@ -163,18 +164,17 @@ func TestRepository_AddWikiPage(t *testing.T) { } { t.Run("test wiki exist: "+userTitle, func(t *testing.T) { webPath := UserTitleToWebPath("", userTitle) - assert.NoError(t, AddWikiPage(git.DefaultContext, doer, repo, webPath, wikiContent, commitMsg)) + require.NoError(t, AddWikiPage(git.DefaultContext, doer, repo, webPath, wikiContent, commitMsg)) // Now need to show that the page has been added: gitRepo, err := gitrepo.OpenWikiRepository(git.DefaultContext, repo) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() masterTree, err := gitRepo.GetTree("master") - assert.NoError(t, err) + require.NoError(t, err) gitPath := WebPathToGitPath(webPath) entry, err := masterTree.GetTreeEntryByPath(gitPath) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, gitPath, entry.Name(), "%s not added correctly", userTitle) }) } @@ -183,7 +183,7 @@ func TestRepository_AddWikiPage(t *testing.T) { t.Parallel() // test for already-existing wiki name err := AddWikiPage(git.DefaultContext, doer, repo, "Home", wikiContent, commitMsg) - assert.Error(t, err) + require.Error(t, err) assert.True(t, repo_model.IsErrWikiAlreadyExist(err)) }) @@ -191,13 +191,13 @@ func TestRepository_AddWikiPage(t *testing.T) { t.Parallel() // test for reserved wiki name err := AddWikiPage(git.DefaultContext, doer, repo, "_edit", wikiContent, commitMsg) - assert.Error(t, err) + require.Error(t, err) assert.True(t, repo_model.IsErrWikiReservedName(err)) }) } func TestRepository_EditWikiPage(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) const newWikiContent = "This is the new content" const commitMsg = "Commit message" @@ -210,21 +210,21 @@ func TestRepository_EditWikiPage(t *testing.T) { } { webPath := UserTitleToWebPath("", newWikiName) unittest.PrepareTestEnv(t) - assert.NoError(t, EditWikiPage(git.DefaultContext, doer, repo, "Home", webPath, newWikiContent, commitMsg)) + require.NoError(t, EditWikiPage(git.DefaultContext, doer, repo, "Home", webPath, newWikiContent, commitMsg)) // Now need to show that the page has been added: gitRepo, err := gitrepo.OpenWikiRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) masterTree, err := gitRepo.GetTree("master") - assert.NoError(t, err) + require.NoError(t, err) gitPath := WebPathToGitPath(webPath) entry, err := masterTree.GetTreeEntryByPath(gitPath) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, gitPath, entry.Name(), "%s not edited correctly", newWikiName) if newWikiName != "Home" { _, err := masterTree.GetTreeEntryByPath("Home.md") - assert.Error(t, err) + require.Error(t, err) } gitRepo.Close() } @@ -234,28 +234,25 @@ func TestRepository_DeleteWikiPage(t *testing.T) { unittest.PrepareTestEnv(t) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.NoError(t, DeleteWikiPage(git.DefaultContext, doer, repo, "Home")) + require.NoError(t, DeleteWikiPage(git.DefaultContext, doer, repo, "Home")) // Now need to show that the page has been added: gitRepo, err := gitrepo.OpenWikiRepository(git.DefaultContext, repo) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) defer gitRepo.Close() masterTree, err := gitRepo.GetTree("master") - assert.NoError(t, err) + require.NoError(t, err) gitPath := WebPathToGitPath("Home") _, err = masterTree.GetTreeEntryByPath(gitPath) - assert.Error(t, err) + require.Error(t, err) } func TestPrepareWikiFileName(t *testing.T) { unittest.PrepareTestEnv(t) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) gitRepo, err := gitrepo.OpenWikiRepository(git.DefaultContext, repo) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() tests := []struct { @@ -282,7 +279,7 @@ func TestPrepareWikiFileName(t *testing.T) { webPath := UserTitleToWebPath("", tt.arg) existence, newWikiPath, err := prepareGitPath(gitRepo, "master", webPath) if (err != nil) != tt.wantErr { - assert.NoError(t, err) + require.NoError(t, err) return } if existence != tt.existence { @@ -304,17 +301,16 @@ func TestPrepareWikiFileName_FirstPage(t *testing.T) { tmpDir := t.TempDir() err := git.InitRepository(git.DefaultContext, tmpDir, true, git.Sha1ObjectFormat.Name()) - assert.NoError(t, err) + require.NoError(t, err) gitRepo, err := git.OpenRepository(git.DefaultContext, tmpDir) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() existence, newWikiPath, err := prepareGitPath(gitRepo, "master", "Home") assert.False(t, existence) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "Home.md", newWikiPath) } diff --git a/tests/e2e/utils_e2e_test.go b/tests/e2e/utils_e2e_test.go index efb4a6ba88..a0e940f1e7 100644 --- a/tests/e2e/utils_e2e_test.go +++ b/tests/e2e/utils_e2e_test.go @@ -14,7 +14,7 @@ import ( "code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/tests" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func onGiteaRunTB(t testing.TB, callback func(testing.TB, *url.URL), prepare ...bool) { @@ -26,7 +26,7 @@ func onGiteaRunTB(t testing.TB, callback func(testing.TB, *url.URL), prepare ... } u, err := url.Parse(setting.AppURL) - assert.NoError(t, err) + require.NoError(t, err) listener, err := net.Listen("tcp", u.Host) i := 0 for err != nil && i <= 10 { @@ -34,7 +34,7 @@ func onGiteaRunTB(t testing.TB, callback func(testing.TB, *url.URL), prepare ... listener, err = net.Listen("tcp", u.Host) i++ } - assert.NoError(t, err) + require.NoError(t, err) u.Host = listener.Addr().String() defer func() { diff --git a/tests/integration/actions_commit_status_test.go b/tests/integration/actions_commit_status_test.go index 1bd1e325b6..ace0fbd323 100644 --- a/tests/integration/actions_commit_status_test.go +++ b/tests/integration/actions_commit_status_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/services/automerge" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestActionsAutomerge(t *testing.T) { @@ -35,7 +36,7 @@ func TestActionsAutomerge(t *testing.T) { scheduled, err := automerge.ScheduleAutoMerge(ctx, user, pr, repo_model.MergeStyleMerge, "Dummy") - assert.NoError(t, err, "PR should be scheduled for automerge") + require.NoError(t, err, "PR should be scheduled for automerge") assert.True(t, scheduled, "PR should be scheduled for automerge") actions.CreateCommitStatus(ctx, job) diff --git a/tests/integration/actions_route_test.go b/tests/integration/actions_route_test.go index 4dba053b1d..2277da3cff 100644 --- a/tests/integration/actions_route_test.go +++ b/tests/integration/actions_route_test.go @@ -20,6 +20,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func GetWorkflowRunRedirectURI(t *testing.T, repoURL, workflow string) string { @@ -71,12 +72,12 @@ func TestActionsWebRouteLatestWorkflowRun(t *testing.T) { // Verify that each points to the correct workflow. workflowOne := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{RepoID: repo.ID, Index: 1}) err := workflowOne.LoadAttributes(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, workflowOneURI, workflowOne.HTMLURL()) workflowTwo := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{RepoID: repo.ID, Index: 2}) err = workflowTwo.LoadAttributes(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, workflowTwoURI, workflowTwo.HTMLURL()) }) @@ -141,7 +142,7 @@ func TestActionsWebRouteLatestRun(t *testing.T) { // Verify that it redirects to the run we just created workflow := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{RepoID: repo.ID}) err := workflow.LoadAttributes(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, workflow.HTMLURL(), resp.Header().Get("Location")) }) @@ -170,7 +171,7 @@ func TestActionsArtifactDeletion(t *testing.T) { // Load the run we just created run := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{RepoID: repo.ID}) err := run.LoadAttributes(context.Background()) - assert.NoError(t, err) + require.NoError(t, err) // Visit it's web view req := NewRequest(t, "GET", run.HTMLURL()) diff --git a/tests/integration/actions_trigger_test.go b/tests/integration/actions_trigger_test.go index 67dd3247b7..0a00ede806 100644 --- a/tests/integration/actions_trigger_test.go +++ b/tests/integration/actions_trigger_test.go @@ -31,6 +31,7 @@ import ( files_service "code.gitea.io/gitea/services/repository/files" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPullRequestTargetEvent(t *testing.T) { @@ -50,7 +51,7 @@ func TestPullRequestTargetEvent(t *testing.T) { Name: "forked-repo-pull-request-target", Description: "test pull-request-target event", }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, forkedRepo) // add workflow file to the base repo @@ -78,7 +79,7 @@ func TestPullRequestTargetEvent(t *testing.T) { Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, addWorkflowToBaseResp) // add a new file to the forked repo @@ -106,7 +107,7 @@ func TestPullRequestTargetEvent(t *testing.T) { Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, addFileToForkedResp) // create Pull @@ -127,7 +128,7 @@ func TestPullRequestTargetEvent(t *testing.T) { Type: issues_model.PullRequestGitea, } err = pull_service.NewPullRequest(git.DefaultContext, baseRepo, pullIssue, nil, nil, pullRequest, nil) - assert.NoError(t, err) + require.NoError(t, err) // if a PR "synchronized" event races the "opened" event by having the same SHA, it must be skipped. See https://codeberg.org/forgejo/forgejo/issues/2009. assert.True(t, actions_service.SkipPullRequestEvent(git.DefaultContext, webhook_module.HookEventPullRequestSync, baseRepo.ID, addFileToForkedResp.Commit.SHA)) @@ -162,7 +163,7 @@ func TestPullRequestTargetEvent(t *testing.T) { Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, addFileToForkedResp) // create Pull @@ -183,7 +184,7 @@ func TestPullRequestTargetEvent(t *testing.T) { Type: issues_model.PullRequestGitea, } err = pull_service.NewPullRequest(git.DefaultContext, baseRepo, pullIssue, nil, nil, pullRequest, nil) - assert.NoError(t, err) + require.NoError(t, err) // the new pull request cannot trigger actions, so there is still only 1 record assert.Equal(t, 1, unittest.GetCount(t, &actions_model.ActionRun{RepoID: baseRepo.ID})) @@ -236,7 +237,7 @@ func TestSkipCI(t *testing.T) { Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, addFileResp) // the commit message contains a configured skip-ci string, so there is still only 1 record @@ -267,7 +268,7 @@ func TestSkipCI(t *testing.T) { Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, addFileToBranchResp) resp := testPullCreate(t, session, "user2", "skip-ci", true, "main", "test-skip-ci", "[skip ci] test-skip-ci") @@ -296,7 +297,7 @@ func TestCreateDeleteRefEvent(t *testing.T) { DefaultBranch: "main", IsPrivate: false, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, repo) // enable actions @@ -304,7 +305,7 @@ func TestCreateDeleteRefEvent(t *testing.T) { RepoID: repo.ID, Type: unit_model.TypeActions, }}, nil) - assert.NoError(t, err) + require.NoError(t, err) // add workflow file to the repo addWorkflowToBaseResp, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{ @@ -331,19 +332,19 @@ func TestCreateDeleteRefEvent(t *testing.T) { Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, addWorkflowToBaseResp) // Get the commit ID of the default branch gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() branch, err := git_model.GetBranch(db.DefaultContext, repo.ID, repo.DefaultBranch) - assert.NoError(t, err) + require.NoError(t, err) // create a branch err = repo_service.CreateNewBranchFromCommit(db.DefaultContext, user2, repo, gitRepo, branch.CommitID, "test-create-branch") - assert.NoError(t, err) + require.NoError(t, err) run := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ Title: "add workflow", RepoID: repo.ID, @@ -356,7 +357,7 @@ func TestCreateDeleteRefEvent(t *testing.T) { // create a tag err = release_service.CreateNewTag(db.DefaultContext, user2, repo, branch.CommitID, "test-create-tag", "test create tag event") - assert.NoError(t, err) + require.NoError(t, err) run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ Title: "add workflow", RepoID: repo.ID, @@ -369,7 +370,7 @@ func TestCreateDeleteRefEvent(t *testing.T) { // delete the branch err = repo_service.DeleteBranch(db.DefaultContext, user2, repo, gitRepo, "test-create-branch") - assert.NoError(t, err) + require.NoError(t, err) run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ Title: "add workflow", RepoID: repo.ID, @@ -382,9 +383,9 @@ func TestCreateDeleteRefEvent(t *testing.T) { // delete the tag tag, err := repo_model.GetRelease(db.DefaultContext, repo.ID, "test-create-tag") - assert.NoError(t, err) + require.NoError(t, err) err = release_service.DeleteReleaseByID(db.DefaultContext, repo, tag, user2, true) - assert.NoError(t, err) + require.NoError(t, err) run = unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ Title: "add workflow", RepoID: repo.ID, @@ -423,11 +424,11 @@ func TestWorkflowDispatchEvent(t *testing.T) { defer f() gitRepo, err := gitrepo.OpenRepository(db.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() workflow, err := actions_service.GetWorkflowFromCommit(gitRepo, "main", "dispatch.yml") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "refs/heads/main", workflow.Ref) assert.Equal(t, sha, workflow.Commit.ID.String()) @@ -436,7 +437,7 @@ func TestWorkflowDispatchEvent(t *testing.T) { } err = workflow.Dispatch(db.DefaultContext, inputGetter, repo, user2) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, 1, unittest.GetCount(t, &actions_model.ActionRun{RepoID: repo.ID})) }) diff --git a/tests/integration/api_actions_artifact_test.go b/tests/integration/api_actions_artifact_test.go index ce2d14cc0c..2798024c16 100644 --- a/tests/integration/api_actions_artifact_test.go +++ b/tests/integration/api_actions_artifact_test.go @@ -357,7 +357,7 @@ func TestActionsArtifactOverwrite(t *testing.T) { break } } - assert.Equal(t, uploadedItem.Name, "artifact") + assert.Equal(t, "artifact", uploadedItem.Name) idx := strings.Index(uploadedItem.FileContainerResourceURL, "/api/actions_pipeline/_apis/pipelines/") url := uploadedItem.FileContainerResourceURL[idx+1:] + "?itemPath=artifact" diff --git a/tests/integration/api_actions_artifact_v4_test.go b/tests/integration/api_actions_artifact_v4_test.go index c70e99e2eb..b2c25a2e70 100644 --- a/tests/integration/api_actions_artifact_v4_test.go +++ b/tests/integration/api_actions_artifact_v4_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/known/timestamppb" @@ -33,7 +34,7 @@ func toProtoJSON(m protoreflect.ProtoMessage) io.Reader { func uploadArtifact(t *testing.T, body string) string { token, err := actions_service.CreateAuthorizationToken(48, 792, 193) - assert.NoError(t, err) + require.NoError(t, err) // acquire artifact upload url req := NewRequestWithBody(t, "POST", "/twirp/github.actions.results.api.v1.ArtifactService/CreateArtifact", toProtoJSON(&actions.CreateArtifactRequest{ @@ -86,7 +87,7 @@ func TestActionsArtifactV4UploadSingleFileWrongChecksum(t *testing.T) { defer tests.PrepareTestEnv(t)() token, err := actions_service.CreateAuthorizationToken(48, 792, 193) - assert.NoError(t, err) + require.NoError(t, err) // acquire artifact upload url req := NewRequestWithBody(t, "POST", "/twirp/github.actions.results.api.v1.ArtifactService/CreateArtifact", toProtoJSON(&actions.CreateArtifactRequest{ @@ -130,7 +131,7 @@ func TestActionsArtifactV4UploadSingleFileWithRetentionDays(t *testing.T) { defer tests.PrepareTestEnv(t)() token, err := actions_service.CreateAuthorizationToken(48, 792, 193) - assert.NoError(t, err) + require.NoError(t, err) // acquire artifact upload url req := NewRequestWithBody(t, "POST", "/twirp/github.actions.results.api.v1.ArtifactService/CreateArtifact", toProtoJSON(&actions.CreateArtifactRequest{ @@ -178,7 +179,7 @@ func TestActionsArtifactV4DownloadSingle(t *testing.T) { defer tests.PrepareTestEnv(t)() token, err := actions_service.CreateAuthorizationToken(48, 792, 193) - assert.NoError(t, err) + require.NoError(t, err) // acquire artifact upload url req := NewRequestWithBody(t, "POST", "/twirp/github.actions.results.api.v1.ArtifactService/ListArtifacts", toProtoJSON(&actions.ListArtifactsRequest{ @@ -258,7 +259,7 @@ func TestActionsArtifactV4Delete(t *testing.T) { defer tests.PrepareTestEnv(t)() token, err := actions_service.CreateAuthorizationToken(48, 792, 193) - assert.NoError(t, err) + require.NoError(t, err) // delete artifact by name req := NewRequestWithBody(t, "POST", "/twirp/github.actions.results.api.v1.ArtifactService/DeleteArtifact", toProtoJSON(&actions.DeleteArtifactRequest{ diff --git a/tests/integration/api_activitypub_person_test.go b/tests/integration/api_activitypub_person_test.go index eb00d6031c..f5cb1244af 100644 --- a/tests/integration/api_activitypub_person_test.go +++ b/tests/integration/api_activitypub_person_test.go @@ -19,6 +19,7 @@ import ( ap "github.com/go-ap/activitypub" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestActivityPubPerson(t *testing.T) { @@ -39,7 +40,7 @@ func TestActivityPubPerson(t *testing.T) { var person ap.Person err := person.UnmarshalJSON(body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, ap.PersonType, person.Type) assert.Equal(t, username, person.PreferredUsername.String()) @@ -95,15 +96,15 @@ func TestActivityPubPersonInbox(t *testing.T) { username1 := "user1" ctx := context.Background() user1, err := user_model.GetUserByName(ctx, username1) - assert.NoError(t, err) + require.NoError(t, err) user1url := fmt.Sprintf("%s/api/v1/activitypub/user-id/1#main-key", srv.URL) c, err := activitypub.NewClient(db.DefaultContext, user1, user1url) - assert.NoError(t, err) + require.NoError(t, err) user2inboxurl := fmt.Sprintf("%s/api/v1/activitypub/user-id/2/inbox", srv.URL) // Signed request succeeds resp, err := c.Post([]byte{}, user2inboxurl) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, http.StatusNoContent, resp.StatusCode) // Unsigned request fails diff --git a/tests/integration/api_activitypub_repository_test.go b/tests/integration/api_activitypub_repository_test.go index bccc594d07..5c97586b19 100644 --- a/tests/integration/api_activitypub_repository_test.go +++ b/tests/integration/api_activitypub_repository_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/routers" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestActivityPubRepository(t *testing.T) { @@ -40,7 +41,7 @@ func TestActivityPubRepository(t *testing.T) { var repository forgefed_modules.Repository err := repository.UnmarshalJSON(body) - assert.NoError(t, err) + require.NoError(t, err) assert.Regexp(t, fmt.Sprintf("activitypub/repository-id/%v$", repositoryID), repository.GetID().String()) }) @@ -140,7 +141,7 @@ func TestActivityPubRepositoryInboxValid(t *testing.T) { actionsUser := user.NewActionsUser() repositoryID := 2 c, err := activitypub.NewClient(db.DefaultContext, actionsUser, "not used") - assert.NoError(t, err) + require.NoError(t, err) repoInboxURL := fmt.Sprintf( "%s/api/v1/activitypub/repository-id/%v/inbox", srv.URL, repositoryID) @@ -157,7 +158,7 @@ func TestActivityPubRepositoryInboxValid(t *testing.T) { t.Logf("activity: %s", activity1) resp, err := c.Post(activity1, repoInboxURL) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, http.StatusNoContent, resp.StatusCode) federationHost := unittest.AssertExistsAndLoadBean(t, &forgefed.FederationHost{HostFqdn: "127.0.0.1"}) @@ -176,7 +177,7 @@ func TestActivityPubRepositoryInboxValid(t *testing.T) { t.Logf("activity: %s", activity2) resp, err = c.Post(activity2, repoInboxURL) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, http.StatusNoContent, resp.StatusCode) federatedUser = unittest.AssertExistsAndLoadBean(t, &user.FederatedUser{ExternalID: "30", FederationHostID: federationHost.ID}) @@ -198,7 +199,7 @@ func TestActivityPubRepositoryInboxValid(t *testing.T) { t.Logf("activity: %s", activity3) resp, err = c.Post(activity3, otherRepoInboxURL) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, http.StatusNoContent, resp.StatusCode) federatedUser = unittest.AssertExistsAndLoadBean(t, &user.FederatedUser{ExternalID: "30", FederationHostID: federationHost.ID}) @@ -206,7 +207,7 @@ func TestActivityPubRepositoryInboxValid(t *testing.T) { // Replay activity2. resp, err = c.Post(activity2, repoInboxURL) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, http.StatusNotAcceptable, resp.StatusCode) }) } @@ -232,13 +233,13 @@ func TestActivityPubRepositoryInboxInvalid(t *testing.T) { actionsUser := user.NewActionsUser() repositoryID := 2 c, err := activitypub.NewClient(db.DefaultContext, actionsUser, "not used") - assert.NoError(t, err) + require.NoError(t, err) repoInboxURL := fmt.Sprintf("%s/api/v1/activitypub/repository-id/%v/inbox", srv.URL, repositoryID) activity := []byte(`{"type":"Wrong"}`) resp, err := c.Post(activity, repoInboxURL) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, http.StatusNotAcceptable, resp.StatusCode) }) } diff --git a/tests/integration/api_branch_test.go b/tests/integration/api_branch_test.go index 089221dec2..63159f3c41 100644 --- a/tests/integration/api_branch_test.go +++ b/tests/integration/api_branch_test.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testAPIGetBranch(t *testing.T, branchName string, exists bool) { @@ -213,7 +214,7 @@ func TestAPIBranchProtection(t *testing.T) { StatusCheckContexts: []string{"test1"}, }, http.StatusOK) bp := testAPIGetBranchProtection(t, "master", http.StatusOK) - assert.Equal(t, true, bp.EnableStatusCheck) + assert.True(t, bp.EnableStatusCheck) assert.Equal(t, []string{"test1"}, bp.StatusCheckContexts) // disable status checks, clear the list of required checks @@ -222,7 +223,7 @@ func TestAPIBranchProtection(t *testing.T) { StatusCheckContexts: []string{}, }, http.StatusOK) bp = testAPIGetBranchProtection(t, "master", http.StatusOK) - assert.Equal(t, false, bp.EnableStatusCheck) + assert.False(t, bp.EnableStatusCheck) assert.Equal(t, []string{}, bp.StatusCheckContexts) testAPIDeleteBranchProtection(t, "master", http.StatusNoContent) @@ -238,12 +239,12 @@ func TestAPICreateBranchWithSyncBranches(t *testing.T) { branches, err := db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ RepoID: 1, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, branches, 4) // make a broke repository with no branch on database _, err = db.DeleteByBean(db.DefaultContext, git_model.Branch{RepoID: 1}) - assert.NoError(t, err) + require.NoError(t, err) onGiteaRun(t, func(t *testing.T, giteaURL *url.URL) { ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) @@ -255,13 +256,13 @@ func TestAPICreateBranchWithSyncBranches(t *testing.T) { branches, err = db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ RepoID: 1, }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, branches, 5) branches, err = db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ RepoID: 1, Keyword: "new_branch", }) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, branches, 1) } diff --git a/tests/integration/api_comment_attachment_test.go b/tests/integration/api_comment_attachment_test.go index eac9965191..db1b98a20f 100644 --- a/tests/integration/api_comment_attachment_test.go +++ b/tests/integration/api_comment_attachment_test.go @@ -23,14 +23,15 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIGetCommentAttachment(t *testing.T) { defer tests.PrepareTestEnv(t)() comment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 2}) - assert.NoError(t, comment.LoadIssue(db.DefaultContext)) - assert.NoError(t, comment.LoadAttachments(db.DefaultContext)) + require.NoError(t, comment.LoadIssue(db.DefaultContext)) + require.NoError(t, comment.LoadAttachments(db.DefaultContext)) attachment := unittest.AssertExistsAndLoadBean(t, &repo_model.Attachment{ID: comment.Attachments[0].ID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: comment.Issue.RepoID}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) @@ -111,11 +112,11 @@ func TestAPICreateCommentAttachment(t *testing.T) { // Setup multi-part writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("attachment", filename) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(part, &buff) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithBody(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets", repoOwner.Name, repo.Name, comment.ID), body). AddTokenAuth(token). @@ -151,11 +152,11 @@ func TestAPICreateCommentAttachmentAutoDate(t *testing.T) { // Setup multi-part writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("attachment", filename) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(part, &buff) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithBody(t, "POST", urlStr, body).AddTokenAuth(token) req.Header.Add("Content-Type", writer.FormDataContentType()) @@ -182,11 +183,11 @@ func TestAPICreateCommentAttachmentAutoDate(t *testing.T) { // Setup multi-part writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("attachment", filename) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(part, &buff) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithBody(t, "POST", urlStr, body).AddTokenAuth(token) req.Header.Add("Content-Type", writer.FormDataContentType()) @@ -265,9 +266,9 @@ func TestAPICreateCommentAttachmentWithUnallowedFile(t *testing.T) { // Setup multi-part. writer := multipart.NewWriter(body) _, err := writer.CreateFormFile("attachment", filename) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithBody(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/comments/%d/assets", repoOwner.Name, repo.Name, comment.ID), body). AddTokenAuth(token). diff --git a/tests/integration/api_comment_test.go b/tests/integration/api_comment_test.go index daa7b5b910..a53b56d783 100644 --- a/tests/integration/api_comment_test.go +++ b/tests/integration/api_comment_test.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIListRepoComments(t *testing.T) { @@ -266,7 +267,7 @@ func TestAPIGetComment(t *testing.T) { defer tests.PrepareTestEnv(t)() comment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 2}) - assert.NoError(t, comment.LoadIssue(db.DefaultContext)) + require.NoError(t, comment.LoadIssue(db.DefaultContext)) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: comment.Issue.RepoID}) repoOwner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) @@ -280,7 +281,7 @@ func TestAPIGetComment(t *testing.T) { var apiComment api.Comment DecodeJSON(t, resp, &apiComment) - assert.NoError(t, comment.LoadPoster(db.DefaultContext)) + require.NoError(t, comment.LoadPoster(db.DefaultContext)) expect := convert.ToAPIComment(db.DefaultContext, repo, comment) assert.Equal(t, expect.ID, apiComment.ID) @@ -308,7 +309,7 @@ func TestAPIGetSystemUserComment(t *testing.T) { Issue: issue, Content: body, }) - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestf(t, "GET", "/api/v1/repos/%s/%s/issues/comments/%d", repoOwner.Name, repo.Name, comment.ID) resp := MakeRequest(t, req, http.StatusOK) @@ -318,7 +319,7 @@ func TestAPIGetSystemUserComment(t *testing.T) { if assert.NotNil(t, apiComment.Poster) { if assert.Equal(t, systemUser.ID, apiComment.Poster.ID) { - assert.NoError(t, comment.LoadPoster(db.DefaultContext)) + require.NoError(t, comment.LoadPoster(db.DefaultContext)) assert.Equal(t, systemUser.Name, apiComment.Poster.UserName) } } diff --git a/tests/integration/api_feed_user_test.go b/tests/integration/api_feed_user_test.go index 608f7608ae..7f3824963a 100644 --- a/tests/integration/api_feed_user_test.go +++ b/tests/integration/api_feed_user_test.go @@ -12,6 +12,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestFeed(t *testing.T) { @@ -62,7 +63,7 @@ func TestFeed(t *testing.T) { }) t.Run("Empty", func(t *testing.T) { err := user_model.UpdateUserCols(db.DefaultContext, &user_model.User{ID: 30, ProhibitLogin: false}, "prohibit_login") - assert.NoError(t, err) + require.NoError(t, err) session := loginUser(t, "user30") t.Run("Atom", func(t *testing.T) { diff --git a/tests/integration/api_helper_for_declarative_test.go b/tests/integration/api_helper_for_declarative_test.go index 1aceda8241..dae71ca8ef 100644 --- a/tests/integration/api_helper_for_declarative_test.go +++ b/tests/integration/api_helper_for_declarative_test.go @@ -23,6 +23,7 @@ import ( "code.gitea.io/gitea/services/forms" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type APITestContext struct { @@ -168,7 +169,7 @@ func doAPIDeleteRepository(ctx APITestContext) func(*testing.T) { func doAPICreateUserKey(ctx APITestContext, keyname, keyFile string, callback ...func(*testing.T, api.PublicKey)) func(*testing.T) { return func(t *testing.T) { dataPubKey, err := os.ReadFile(keyFile + ".pub") - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithJSON(t, "POST", "/api/v1/user/keys", &api.CreateKeyOption{ Title: keyname, Key: string(dataPubKey), @@ -201,7 +202,7 @@ func doAPIDeleteUserKey(ctx APITestContext, keyID int64) func(*testing.T) { func doAPICreateDeployKey(ctx APITestContext, keyname, keyFile string, readOnly bool) func(*testing.T) { return func(t *testing.T) { dataPubKey, err := os.ReadFile(keyFile + ".pub") - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/keys", ctx.Username, ctx.Reponame), api.CreateKeyOption{ Title: keyname, Key: string(dataPubKey), diff --git a/tests/integration/api_issue_attachment_test.go b/tests/integration/api_issue_attachment_test.go index 919dea2e62..77e752d122 100644 --- a/tests/integration/api_issue_attachment_test.go +++ b/tests/integration/api_issue_attachment_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIGetIssueAttachment(t *testing.T) { @@ -80,11 +81,11 @@ func TestAPICreateIssueAttachment(t *testing.T) { // Setup multi-part writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("attachment", filename) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(part, &buff) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithBody(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets", repoOwner.Name, repo.Name, issue.Index), body). AddTokenAuth(token) @@ -119,11 +120,11 @@ func TestAPICreateIssueAttachmentAutoDate(t *testing.T) { // Setup multi-part writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("attachment", filename) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(part, &buff) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithBody(t, "POST", urlStr, body).AddTokenAuth(token) req.Header.Add("Content-Type", writer.FormDataContentType()) @@ -151,11 +152,11 @@ func TestAPICreateIssueAttachmentAutoDate(t *testing.T) { // Setup multi-part writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("attachment", filename) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(part, &buff) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithBody(t, "POST", urlStr, body).AddTokenAuth(token) req.Header.Add("Content-Type", writer.FormDataContentType()) @@ -189,9 +190,9 @@ func TestAPICreateIssueAttachmentWithUnallowedFile(t *testing.T) { // Setup multi-part. writer := multipart.NewWriter(body) _, err := writer.CreateFormFile("attachment", filename) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithBody(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/issues/%d/assets", repoOwner.Name, repo.Name, issue.Index), body). AddTokenAuth(token) diff --git a/tests/integration/api_issue_config_test.go b/tests/integration/api_issue_config_test.go index 245114700f..16f81e785d 100644 --- a/tests/integration/api_issue_config_test.go +++ b/tests/integration/api_issue_config_test.go @@ -16,15 +16,16 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) func createIssueConfigInDirectory(t *testing.T, user *user_model.User, repo *repo_model.Repository, dir string, issueConfig map[string]any) { config, err := yaml.Marshal(issueConfig) - assert.NoError(t, err) + require.NoError(t, err) err = createOrReplaceFileInBranch(user, repo, fmt.Sprintf("%s/ISSUE_TEMPLATE/config.yaml", dir), repo.DefaultBranch, string(config)) - assert.NoError(t, err) + require.NoError(t, err) } func createIssueConfig(t *testing.T, user *user_model.User, repo *repo_model.Repository, issueConfig map[string]any) { @@ -54,7 +55,7 @@ func TestAPIRepoGetIssueConfig(t *testing.T) { issueConfig := getIssueConfig(t, owner.Name, repo.Name) assert.True(t, issueConfig.BlankIssuesEnabled) - assert.Len(t, issueConfig.ContactLinks, 0) + assert.Empty(t, issueConfig.ContactLinks) }) t.Run("DisableBlankIssues", func(t *testing.T) { @@ -68,7 +69,7 @@ func TestAPIRepoGetIssueConfig(t *testing.T) { issueConfig := getIssueConfig(t, owner.Name, repo.Name) assert.False(t, issueConfig.BlankIssuesEnabled) - assert.Len(t, issueConfig.ContactLinks, 0) + assert.Empty(t, issueConfig.ContactLinks) }) t.Run("ContactLinks", func(t *testing.T) { @@ -144,18 +145,18 @@ func TestAPIRepoIssueConfigPaths(t *testing.T) { configMap["blank_issues_enabled"] = false configData, err := yaml.Marshal(configMap) - assert.NoError(t, err) + require.NoError(t, err) _, err = createFileInBranch(owner, repo, fullPath, repo.DefaultBranch, string(configData)) - assert.NoError(t, err) + require.NoError(t, err) issueConfig := getIssueConfig(t, owner.Name, repo.Name) assert.False(t, issueConfig.BlankIssuesEnabled) - assert.Len(t, issueConfig.ContactLinks, 0) + assert.Empty(t, issueConfig.ContactLinks) _, err = deleteFileInBranch(owner, repo, fullPath, repo.DefaultBranch) - assert.NoError(t, err) + require.NoError(t, err) }) } } diff --git a/tests/integration/api_issue_label_test.go b/tests/integration/api_issue_label_test.go index e99c3dfd86..29da419380 100644 --- a/tests/integration/api_issue_label_test.go +++ b/tests/integration/api_issue_label_test.go @@ -19,10 +19,11 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIModifyLabels(t *testing.T) { - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) @@ -94,7 +95,7 @@ func TestAPIModifyLabels(t *testing.T) { } func TestAPIAddIssueLabels(t *testing.T) { - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: repo.ID}) @@ -117,7 +118,7 @@ func TestAPIAddIssueLabels(t *testing.T) { } func TestAPIAddIssueLabelsWithLabelNames(t *testing.T) { - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: repo.ID}) @@ -186,7 +187,7 @@ func TestAPIAddIssueLabelsAutoDate(t *testing.T) { } func TestAPIReplaceIssueLabels(t *testing.T) { - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: repo.ID}) @@ -212,7 +213,7 @@ func TestAPIReplaceIssueLabels(t *testing.T) { } func TestAPIReplaceIssueLabelsWithLabelNames(t *testing.T) { - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: repo.ID}) @@ -235,7 +236,7 @@ func TestAPIReplaceIssueLabelsWithLabelNames(t *testing.T) { } func TestAPIModifyOrgLabels(t *testing.T) { - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) diff --git a/tests/integration/api_issue_pin_test.go b/tests/integration/api_issue_pin_test.go index 1cff937254..2f257a89e0 100644 --- a/tests/integration/api_issue_pin_test.go +++ b/tests/integration/api_issue_pin_test.go @@ -17,12 +17,13 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIPinIssue(t *testing.T) { defer tests.PrepareTestEnv(t)() - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: repo.ID}) @@ -47,7 +48,7 @@ func TestAPIPinIssue(t *testing.T) { func TestAPIUnpinIssue(t *testing.T) { defer tests.PrepareTestEnv(t)() - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: repo.ID}) @@ -83,7 +84,7 @@ func TestAPIUnpinIssue(t *testing.T) { func TestAPIMoveIssuePin(t *testing.T) { defer tests.PrepareTestEnv(t)() - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: repo.ID}) @@ -133,7 +134,7 @@ func TestAPIMoveIssuePin(t *testing.T) { func TestAPIListPinnedIssues(t *testing.T) { defer tests.PrepareTestEnv(t)() - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: repo.ID}) @@ -153,14 +154,14 @@ func TestAPIListPinnedIssues(t *testing.T) { var issueList []api.Issue DecodeJSON(t, resp, &issueList) - assert.Equal(t, 1, len(issueList)) + assert.Len(t, issueList, 1) assert.Equal(t, issue.ID, issueList[0].ID) } func TestAPIListPinnedPullrequests(t *testing.T) { defer tests.PrepareTestEnv(t)() - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) @@ -169,7 +170,7 @@ func TestAPIListPinnedPullrequests(t *testing.T) { var prList []api.PullRequest DecodeJSON(t, resp, &prList) - assert.Equal(t, 0, len(prList)) + assert.Empty(t, prList) } func TestAPINewPinAllowed(t *testing.T) { diff --git a/tests/integration/api_issue_templates_test.go b/tests/integration/api_issue_templates_test.go index 15c2dd422b..d634329514 100644 --- a/tests/integration/api_issue_templates_test.go +++ b/tests/integration/api_issue_templates_test.go @@ -16,6 +16,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIIssueTemplateList(t *testing.T) { @@ -59,7 +60,7 @@ ref: 'main' --- This is the template!`) - assert.NoError(t, err) + require.NoError(t, err) req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/issue_templates", repo.FullName())) resp := MakeRequest(t, req, http.StatusOK) @@ -97,7 +98,7 @@ ref: 'main' --- This is the template!`) - assert.NoError(t, err) + require.NoError(t, err) } req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/repos/%s/issue_templates", repo.FullName())) diff --git a/tests/integration/api_issue_test.go b/tests/integration/api_issue_test.go index a8df0250df..6e60fe72bc 100644 --- a/tests/integration/api_issue_test.go +++ b/tests/integration/api_issue_test.go @@ -23,6 +23,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIListIssues(t *testing.T) { @@ -157,7 +158,7 @@ func TestAPIEditIssue(t *testing.T) { issueBefore := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 10}) repoBefore := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issueBefore.RepoID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) - assert.NoError(t, issueBefore.LoadAttributes(db.DefaultContext)) + require.NoError(t, issueBefore.LoadAttributes(db.DefaultContext)) assert.Equal(t, int64(1019307200), int64(issueBefore.DeadlineUnix)) assert.Equal(t, api.StateOpen, issueBefore.State()) @@ -194,7 +195,7 @@ func TestAPIEditIssue(t *testing.T) { // check deleted user assert.Equal(t, int64(500), issueAfter.PosterID) - assert.NoError(t, issueAfter.LoadAttributes(db.DefaultContext)) + require.NoError(t, issueAfter.LoadAttributes(db.DefaultContext)) assert.Equal(t, int64(-1), issueAfter.PosterID) assert.Equal(t, int64(-1), issueBefore.PosterID) assert.Equal(t, int64(-1), apiIssue.Poster.ID) @@ -206,7 +207,7 @@ func TestAPIEditIssue(t *testing.T) { assert.Equal(t, api.StateClosed, apiIssue.State) assert.Equal(t, milestone, apiIssue.Milestone.ID) assert.Equal(t, body, apiIssue.Body) - assert.True(t, apiIssue.Deadline == nil) + assert.Nil(t, apiIssue.Deadline) assert.Equal(t, title, apiIssue.Title) // in database @@ -238,7 +239,7 @@ func TestAPIEditIssueAutoDate(t *testing.T) { issueBefore := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 13}) repoBefore := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issueBefore.RepoID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) - assert.NoError(t, issueBefore.LoadAttributes(db.DefaultContext)) + require.NoError(t, issueBefore.LoadAttributes(db.DefaultContext)) t.Run("WithAutoDate", func(t *testing.T) { defer tests.PrintCurrentTest(t)() @@ -320,7 +321,7 @@ func TestAPIEditIssueMilestoneAutoDate(t *testing.T) { repoBefore := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issueBefore.RepoID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) - assert.NoError(t, issueBefore.LoadAttributes(db.DefaultContext)) + require.NoError(t, issueBefore.LoadAttributes(db.DefaultContext)) session := loginUser(t, owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteIssue) diff --git a/tests/integration/api_issue_tracked_time_test.go b/tests/integration/api_issue_tracked_time_test.go index fd2c452b20..90a59fb481 100644 --- a/tests/integration/api_issue_tracked_time_test.go +++ b/tests/integration/api_issue_tracked_time_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIGetTrackedTimes(t *testing.T) { @@ -25,7 +26,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) - assert.NoError(t, issue2.LoadRepo(db.DefaultContext)) + require.NoError(t, issue2.LoadRepo(db.DefaultContext)) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeReadIssue) @@ -36,7 +37,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { var apiTimes api.TrackedTimeList DecodeJSON(t, resp, &apiTimes) expect, err := issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: issue2.ID}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, apiTimes, 3) for i, time := range expect { @@ -46,7 +47,7 @@ func TestAPIGetTrackedTimes(t *testing.T) { assert.Equal(t, time.Created.Unix(), apiTimes[i].Created.Unix()) assert.Equal(t, time.Time, apiTimes[i].Time) user, err := user_model.GetUserByID(db.DefaultContext, time.UserID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, user.Name, apiTimes[i].UserName) } @@ -69,7 +70,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { time6 := unittest.AssertExistsAndLoadBean(t, &issues_model.TrackedTime{ID: 6}) issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) - assert.NoError(t, issue2.LoadRepo(db.DefaultContext)) + require.NoError(t, issue2.LoadRepo(db.DefaultContext)) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session := loginUser(t, user2.Name) @@ -89,7 +90,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { // Reset time of user 2 on issue 2 trackedSeconds, err := issues_model.GetTrackedSeconds(db.DefaultContext, issues_model.FindTrackedTimesOptions{IssueID: 2, UserID: 2}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(3661), trackedSeconds) req = NewRequestf(t, "DELETE", "/api/v1/repos/%s/%s/issues/%d/times", user2.Name, issue2.Repo.Name, issue2.Index). @@ -98,7 +99,7 @@ func TestAPIDeleteTrackedTime(t *testing.T) { MakeRequest(t, req, http.StatusNotFound) trackedSeconds, err = issues_model.GetTrackedSeconds(db.DefaultContext, issues_model.FindTrackedTimesOptions{IssueID: 2, UserID: 2}) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(0), trackedSeconds) } @@ -106,7 +107,7 @@ func TestAPIAddTrackedTimes(t *testing.T) { defer tests.PrepareTestEnv(t)() issue2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) - assert.NoError(t, issue2.LoadRepo(db.DefaultContext)) + require.NoError(t, issue2.LoadRepo(db.DefaultContext)) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) admin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) diff --git a/tests/integration/api_keys_test.go b/tests/integration/api_keys_test.go index 89ad1ec0df..86daa8c506 100644 --- a/tests/integration/api_keys_test.go +++ b/tests/integration/api_keys_test.go @@ -19,6 +19,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestViewDeployKeysNoLogin(t *testing.T) { @@ -133,7 +134,7 @@ func TestCreateUserKey(t *testing.T) { var newPublicKey api.PublicKey DecodeJSON(t, resp, &newPublicKey) fingerprint, err := asymkey_model.CalcFingerprint(rawKeyBody.Key) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, &asymkey_model.PublicKey{ ID: newPublicKey.ID, OwnerID: user.ID, @@ -168,7 +169,7 @@ func TestCreateUserKey(t *testing.T) { resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) - assert.Len(t, fingerprintPublicKeys, 0) + assert.Empty(t, fingerprintPublicKeys) // Fail searching for wrong users key req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/users/%s/keys?fingerprint=%s", "user2", newPublicKey.Fingerprint)). @@ -176,7 +177,7 @@ func TestCreateUserKey(t *testing.T) { resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) - assert.Len(t, fingerprintPublicKeys, 0) + assert.Empty(t, fingerprintPublicKeys) // Now login as user 2 session2 := loginUser(t, "user2") @@ -208,5 +209,5 @@ func TestCreateUserKey(t *testing.T) { resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &fingerprintPublicKeys) - assert.Len(t, fingerprintPublicKeys, 0) + assert.Empty(t, fingerprintPublicKeys) } diff --git a/tests/integration/api_label_templates_test.go b/tests/integration/api_label_templates_test.go index 007e979011..3039f8c60c 100644 --- a/tests/integration/api_label_templates_test.go +++ b/tests/integration/api_label_templates_test.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIListLabelTemplates(t *testing.T) { @@ -50,7 +51,7 @@ func TestAPIGetLabelTemplateInfo(t *testing.T) { DecodeJSON(t, resp, &templateInfo) labels, err := repo_module.LoadTemplateLabelsByDisplayName(templateName) - assert.NoError(t, err) + require.NoError(t, err) for i := range labels { assert.Equal(t, strings.TrimLeft(labels[i].Color, "#"), templateInfo[i].Color) diff --git a/tests/integration/api_notification_test.go b/tests/integration/api_notification_test.go index abb9852eef..ad233d9e73 100644 --- a/tests/integration/api_notification_test.go +++ b/tests/integration/api_notification_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPINotification(t *testing.T) { @@ -26,7 +27,7 @@ func TestAPINotification(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) - assert.NoError(t, thread5.LoadAttributes(db.DefaultContext)) + require.NoError(t, thread5.LoadAttributes(db.DefaultContext)) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteNotification, auth_model.AccessTokenScopeWriteRepository) @@ -120,7 +121,7 @@ func TestAPINotification(t *testing.T) { AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &newStruct) - assert.True(t, newStruct.New > 0) + assert.Positive(t, newStruct.New) // -- mark notifications as read -- req = NewRequest(t, "GET", "/api/v1/notifications?status-types=unread"). @@ -154,7 +155,7 @@ func TestAPINotification(t *testing.T) { AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) DecodeJSON(t, resp, &newStruct) - assert.True(t, newStruct.New == 0) + assert.Equal(t, int64(0), newStruct.New) } func TestAPINotificationPUT(t *testing.T) { @@ -162,7 +163,7 @@ func TestAPINotificationPUT(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) - assert.NoError(t, thread5.LoadAttributes(db.DefaultContext)) + require.NoError(t, thread5.LoadAttributes(db.DefaultContext)) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteNotification) diff --git a/tests/integration/api_oauth2_apps_test.go b/tests/integration/api_oauth2_apps_test.go index 0ea3dc72ff..85c7184b64 100644 --- a/tests/integration/api_oauth2_apps_test.go +++ b/tests/integration/api_oauth2_apps_test.go @@ -74,12 +74,12 @@ func testAPIListOAuth2Applications(t *testing.T) { DecodeJSON(t, resp, &appList) expectedApp := appList[0] - assert.EqualValues(t, existApp.Name, expectedApp.Name) - assert.EqualValues(t, existApp.ClientID, expectedApp.ClientID) - assert.Equal(t, existApp.ConfidentialClient, expectedApp.ConfidentialClient) + assert.EqualValues(t, expectedApp.Name, existApp.Name) + assert.EqualValues(t, expectedApp.ClientID, existApp.ClientID) + assert.Equal(t, expectedApp.ConfidentialClient, existApp.ConfidentialClient) assert.Len(t, expectedApp.ClientID, 36) assert.Empty(t, expectedApp.ClientSecret) - assert.EqualValues(t, existApp.RedirectURIs[0], expectedApp.RedirectURIs[0]) + assert.EqualValues(t, expectedApp.RedirectURIs[0], existApp.RedirectURIs[0]) unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) } @@ -128,13 +128,13 @@ func testAPIGetOAuth2Application(t *testing.T) { DecodeJSON(t, resp, &app) expectedApp := app - assert.EqualValues(t, existApp.Name, expectedApp.Name) - assert.EqualValues(t, existApp.ClientID, expectedApp.ClientID) - assert.Equal(t, existApp.ConfidentialClient, expectedApp.ConfidentialClient) + assert.EqualValues(t, expectedApp.Name, existApp.Name) + assert.EqualValues(t, expectedApp.ClientID, existApp.ClientID) + assert.Equal(t, expectedApp.ConfidentialClient, existApp.ConfidentialClient) assert.Len(t, expectedApp.ClientID, 36) assert.Empty(t, expectedApp.ClientSecret) assert.Len(t, expectedApp.RedirectURIs, 1) - assert.EqualValues(t, existApp.RedirectURIs[0], expectedApp.RedirectURIs[0]) + assert.EqualValues(t, expectedApp.RedirectURIs[0], existApp.RedirectURIs[0]) unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: expectedApp.ID, Name: expectedApp.Name}) } diff --git a/tests/integration/api_org_avatar_test.go b/tests/integration/api_org_avatar_test.go index cc1452c153..bbe116cd60 100644 --- a/tests/integration/api_org_avatar_test.go +++ b/tests/integration/api_org_avatar_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIUpdateOrgAvatar(t *testing.T) { @@ -25,7 +26,7 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { // Test what happens if you use a valid image avatar, err := os.ReadFile("tests/integration/avatar.png") - assert.NoError(t, err) + require.NoError(t, err) if err != nil { assert.FailNow(t, "Unable to open avatar.png") } @@ -49,7 +50,7 @@ func TestAPIUpdateOrgAvatar(t *testing.T) { // Test what happens if you use a file that is not an image text, err := os.ReadFile("tests/integration/README.md") - assert.NoError(t, err) + require.NoError(t, err) if err != nil { assert.FailNow(t, "Unable to open README.md") } diff --git a/tests/integration/api_packages_alpine_test.go b/tests/integration/api_packages_alpine_test.go index e7f866d0e8..2264625556 100644 --- a/tests/integration/api_packages_alpine_test.go +++ b/tests/integration/api_packages_alpine_test.go @@ -23,6 +23,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageAlpine(t *testing.T) { @@ -58,7 +59,7 @@ FduBtm5sFa7C/ifOo7y5Lf2QeiHar6jTaDSbnF5Mp+fzOL/x+aJuy3g+HvGhs8JY4b3yOpMZOZEo lRW+MEoTTw3ZwqU0INNjsAe2VPk/9b/L3/s/kIKzqOtk+IbJGTtmr+bx7WoxOUoun98frk/un14O Djfa/2q5bH4699v++uMAAAAAAAAAAAAAAAAAAAAAAHbgA/eXQh8AKAAA` content, err := base64.StdEncoding.DecodeString(base64AlpinePackageContent) - assert.NoError(t, err) + require.NoError(t, err) branches := []string{"v3.16", "v3.17", "v3.18"} repositories := []string{"main", "testing"} @@ -95,18 +96,18 @@ Djfa/2q5bH4699v++uMAAAAAAAAAAAAAAAAAAAAAAHbgA/eXQh8AKAAA` MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeAlpine) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &alpine_module.VersionMetadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, pfs) assert.Condition(t, func() bool { seen := false @@ -122,7 +123,7 @@ Djfa/2q5bH4699v++uMAAAAAAAAAAAAAAAAAAAAAAHbgA/eXQh8AKAAA` assert.True(t, pf.IsLead) pfps, err := packages.GetProperties(db.DefaultContext, packages.PropertyTypeFile, pf.ID) - assert.NoError(t, err) + require.NoError(t, err) for _, pfp := range pfps { switch pfp.Name { @@ -192,7 +193,7 @@ Djfa/2q5bH4699v++uMAAAAAAAAAAAAAAAAAAAAAAHbgA/eXQh8AKAAA` resp := MakeRequest(t, req, http.StatusOK) content, err := readIndexContent(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, content, "C:Q1/se1PjO94hYXbfpNR1/61hVORIc=\n") assert.Contains(t, content, "P:"+packageName+"\n") @@ -275,7 +276,7 @@ vZNm87hdDvs2vEwno3K7UWc1Iw1341kw21U26mkeBIFPlW+rmkktopAHTIWmihmyVvn/9dAv0/8i 8//Hqe9OebNMus+Q75Miub8rHmw9vrzu3l53ns1h7enm9AH9/3M72/PtT/uFgg37sVdq2OEw9jpx MoxKyDAAAAAAAAAAAADA2noDOINxQwAoAAA=` content, err := base64.StdEncoding.DecodeString(base64AlpinePackageContent) - assert.NoError(t, err) + require.NoError(t, err) packageContents := map[string][]byte{} packageContents["forgejo-noarch-test"] = content @@ -309,7 +310,7 @@ W9xysWebmBuBbbgm44R1mWGHFGbIsuX/b0M/R/8Twj7nnxJS9X+VSfkb0j3UQg/9l6fbx93yYuNm zbm+77fu7Gfo/9/b2tRzL0r09Fwkmd/JykRR/DSO3SRw2nqZZ3p1d/rXaCtKIOTTwfaOeqmsJ0IE aiIK5QoSDwAAAAAAAAAAAAAAAP/IK49O1e8AKAAA` content, err = base64.StdEncoding.DecodeString(base64AlpinePackageContent) - assert.NoError(t, err) + require.NoError(t, err) packageContents["forgejo-noarch-test-openrc"] = content @@ -349,18 +350,18 @@ aiIK5QoSDwAAAAAAAAAAAAAAAP/IK49O1e8AKAAA` MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageName(db.DefaultContext, user.ID, packages.TypeAlpine, pkg) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &alpine_module.VersionMetadata{}, pd.Metadata) assert.Equal(t, pkg, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, pfs) assert.Condition(t, func() bool { seen := false @@ -376,7 +377,7 @@ aiIK5QoSDwAAAAAAAAAAAAAAAP/IK49O1e8AKAAA` assert.True(t, pf.IsLead) pfps, err := packages.GetProperties(db.DefaultContext, packages.PropertyTypeFile, pf.ID) - assert.NoError(t, err) + require.NoError(t, err) for _, pfp := range pfps { switch pfp.Name { @@ -407,7 +408,7 @@ aiIK5QoSDwAAAAAAAAAAAAAAAP/IK49O1e8AKAAA` br := bufio.NewReader(resp.Body) gzr, err := gzip.NewReader(br) - assert.NoError(t, err) + require.NoError(t, err) for { gzr.Multistream(false) @@ -418,11 +419,11 @@ aiIK5QoSDwAAAAAAAAAAAAAAAP/IK49O1e8AKAAA` if err == io.EOF { break } - assert.NoError(t, err) + require.NoError(t, err) if hd.Name == "APKINDEX" { buf, err := io.ReadAll(tr) - assert.NoError(t, err) + require.NoError(t, err) s := string(buf) @@ -462,7 +463,7 @@ aiIK5QoSDwAAAAAAAAAAAAAAAP/IK49O1e8AKAAA` if err == io.EOF { break } - assert.NoError(t, err) + require.NoError(t, err) } return false diff --git a/tests/integration/api_packages_cargo_test.go b/tests/integration/api_packages_cargo_test.go index 55cce50c7b..7a9105eb3a 100644 --- a/tests/integration/api_packages_cargo_test.go +++ b/tests/integration/api_packages_cargo_test.go @@ -27,6 +27,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageCargo(t *testing.T) { @@ -71,25 +72,25 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { } err := cargo_service.InitializeIndexRepository(db.DefaultContext, user, user) - assert.NoError(t, err) + require.NoError(t, err) repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, user.Name, cargo_service.IndexRepositoryName) assert.NotNil(t, repo) - assert.NoError(t, err) + require.NoError(t, err) readGitContent := func(t *testing.T, path string) string { gitRepo, err := gitrepo.OpenRepository(db.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() commit, err := gitRepo.GetBranchCommit(repo.DefaultBranch) - assert.NoError(t, err) + require.NoError(t, err) blob, err := commit.GetBlobByPath(path) - assert.NoError(t, err) + require.NoError(t, err) content, err := blob.GetBlobContent(1024) - assert.NoError(t, err) + require.NoError(t, err) return content } @@ -105,7 +106,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { var config cargo_service.Config err := json.Unmarshal([]byte(content), &config) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, url, config.DownloadURL) assert.Equal(t, root, config.APIURL) @@ -119,7 +120,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { var config cargo_service.Config err := json.Unmarshal(resp.Body.Bytes(), &config) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, url, config.DownloadURL) assert.Equal(t, root, config.APIURL) @@ -181,24 +182,24 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { assert.True(t, status.OK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeCargo) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &cargo_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s-%s.crate", packageName, packageVersion), pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 4, pb.Size) req = NewRequestWithBody(t, "PUT", url+"/new", createPackage(packageName, packageVersion)). @@ -214,7 +215,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { var entry cargo_service.IndexVersionEntry err := json.Unmarshal([]byte(content), &entry) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageName, entry.Name) assert.Equal(t, packageVersion, entry.Version) @@ -238,7 +239,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { defer tests.PrintCurrentTest(t)() err := cargo_service.RebuildIndex(db.DefaultContext, user, user) - assert.NoError(t, err) + require.NoError(t, err) _ = readGitContent(t, cargo_service.BuildPackagePath(packageName)) }) @@ -253,7 +254,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { var entry cargo_service.IndexVersionEntry err := json.Unmarshal(resp.Body.Bytes(), &entry) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageName, entry.Name) assert.Equal(t, packageVersion, entry.Version) @@ -281,11 +282,11 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { defer tests.PrintCurrentTest(t)() pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeCargo, packageName, packageVersion) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, pv.DownloadCount) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pv.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/%s/download", url, neturl.PathEscape(packageName), neturl.PathEscape(pv.Version))). @@ -295,7 +296,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { assert.Equal(t, "test", resp.Body.String()) pv, err = packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeCargo, packageName, packageVersion) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, pv.DownloadCount) }) @@ -345,7 +346,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { var entry cargo_service.IndexVersionEntry err := json.Unmarshal([]byte(content), &entry) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, entry.Yanked) }) @@ -365,7 +366,7 @@ func testPackageCargo(t *testing.T, _ *neturl.URL) { var entry cargo_service.IndexVersionEntry err := json.Unmarshal([]byte(content), &entry) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, entry.Yanked) }) diff --git a/tests/integration/api_packages_chef_test.go b/tests/integration/api_packages_chef_test.go index 6efb2708af..febb1a8b6c 100644 --- a/tests/integration/api_packages_chef_test.go +++ b/tests/integration/api_packages_chef_test.go @@ -35,6 +35,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageChef(t *testing.T) { @@ -84,7 +85,7 @@ nwIDAQAB -----END PUBLIC KEY-----` err := user_model.SetUserSetting(db.DefaultContext, user.ID, chef_module.SettingPublicPem, pubPem) - assert.NoError(t, err) + require.NoError(t, err) t.Run("Authenticate", func(t *testing.T) { auth := &chef_router.Auth{} @@ -95,7 +96,7 @@ nwIDAQAB req := NewRequest(t, "POST", "/dummy") u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("NotExistingUser", func(t *testing.T) { @@ -105,7 +106,7 @@ nwIDAQAB SetHeader("X-Ops-Userid", "not-existing-user") u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) - assert.Error(t, err) + require.Error(t, err) }) t.Run("Timestamp", func(t *testing.T) { @@ -115,12 +116,12 @@ nwIDAQAB SetHeader("X-Ops-Userid", user.Name) u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) - assert.Error(t, err) + require.Error(t, err) req.SetHeader("X-Ops-Timestamp", "2023-01-01T00:00:00Z") u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) - assert.Error(t, err) + require.Error(t, err) }) t.Run("SigningVersion", func(t *testing.T) { @@ -131,27 +132,27 @@ nwIDAQAB SetHeader("X-Ops-Timestamp", time.Now().UTC().Format(time.RFC3339)) u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) - assert.Error(t, err) + require.Error(t, err) req.SetHeader("X-Ops-Sign", "version=none") u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) - assert.Error(t, err) + require.Error(t, err) req.SetHeader("X-Ops-Sign", "version=1.4") u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) - assert.Error(t, err) + require.Error(t, err) req.SetHeader("X-Ops-Sign", "version=1.0;algorithm=sha2") u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) - assert.Error(t, err) + require.Error(t, err) req.SetHeader("X-Ops-Sign", "version=1.0;algorithm=sha256") u, err = auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) - assert.Error(t, err) + require.Error(t, err) }) t.Run("SignedHeaders", func(t *testing.T) { @@ -167,7 +168,7 @@ nwIDAQAB SetHeader("X-Ops-Authorization-4", "dummy") u, err := auth.Verify(req.Request, nil, nil, nil) assert.Nil(t, u) - assert.Error(t, err) + require.Error(t, err) signRequest := func(rw *RequestWrapper, version string) { req := rw.Request @@ -258,7 +259,7 @@ nwIDAQAB signRequest(req, v) u, err = auth.Verify(req.Request, nil, nil, nil) assert.NotNil(t, u) - assert.NoError(t, err) + require.NoError(t, err) }) } }) @@ -307,18 +308,18 @@ nwIDAQAB uploadPackage(t, packageVersion, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeChef) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &chef_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s.tar.gz", packageVersion), pfs[0].Name) assert.True(t, pfs[0].IsLead) @@ -540,7 +541,7 @@ nwIDAQAB pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeChef, packageName, "1.0.2") assert.Nil(t, pv) - assert.Error(t, err) + require.Error(t, err) }) t.Run("Package", func(t *testing.T) { @@ -554,7 +555,7 @@ nwIDAQAB MakeRequest(t, req, http.StatusOK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeChef) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, pvs) }) }) diff --git a/tests/integration/api_packages_composer_test.go b/tests/integration/api_packages_composer_test.go index 6e0d2eee1b..9cdcd07e37 100644 --- a/tests/integration/api_packages_composer_test.go +++ b/tests/integration/api_packages_composer_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageComposer(t *testing.T) { @@ -90,24 +91,24 @@ func TestPackageComposer(t *testing.T) { MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeComposer) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &composer_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s-%s.%s.zip", vendorName, projectName, packageVersion), pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). @@ -120,12 +121,12 @@ func TestPackageComposer(t *testing.T) { defer tests.PrintCurrentTest(t)() pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeComposer) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(0), pvs[0].DownloadCount) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) req := NewRequest(t, "GET", fmt.Sprintf("%s/files/%s/%s/%s", url, neturl.PathEscape(packageName), neturl.PathEscape(pvs[0].LowerVersion), neturl.PathEscape(pfs[0].LowerName))). @@ -135,7 +136,7 @@ func TestPackageComposer(t *testing.T) { assert.Equal(t, content, resp.Body.Bytes()) pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeComposer) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(1), pvs[0].DownloadCount) }) diff --git a/tests/integration/api_packages_conan_test.go b/tests/integration/api_packages_conan_test.go index a25713f039..003867441b 100644 --- a/tests/integration/api_packages_conan_test.go +++ b/tests/integration/api_packages_conan_test.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -253,11 +254,11 @@ func TestPackageConan(t *testing.T) { defer tests.PrintCurrentTest(t)() pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConan) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.Equal(t, name, pd.Package.Name) assert.Equal(t, version1, pd.Version.Version) @@ -271,12 +272,12 @@ func TestPackageConan(t *testing.T) { assert.Equal(t, []string{conanTopic}, metadata.Keywords) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 2) for _, pf := range pfs { pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) - assert.NoError(t, err) + require.NoError(t, err) if pf.Name == conanfileName { assert.True(t, pf.IsLead) @@ -426,7 +427,7 @@ func TestPackageConan(t *testing.T) { for i, c := range cases { rref, _ := conan_module.NewRecipeReference(name, version1, user1, c.Channel, conan_module.DefaultRevision) references, err := conan_model.GetPackageReferences(db.DefaultContext, user.ID, rref) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, references) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s/packages/delete", url, name, version1, user1, c.Channel), map[string][]string{ @@ -435,7 +436,7 @@ func TestPackageConan(t *testing.T) { MakeRequest(t, req, http.StatusOK) references, err = conan_model.GetPackageReferences(db.DefaultContext, user.ID, rref) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, references, "case %d: should be empty", i) } }) @@ -453,7 +454,7 @@ func TestPackageConan(t *testing.T) { for i, c := range cases { rref, _ := conan_module.NewRecipeReference(name, version1, user1, c.Channel, conan_module.DefaultRevision) revisions, err := conan_model.GetRecipeRevisions(db.DefaultContext, user.ID, rref) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, revisions) req := NewRequest(t, "DELETE", fmt.Sprintf("%s/v1/conans/%s/%s/%s/%s", url, name, version1, user1, c.Channel)). @@ -461,7 +462,7 @@ func TestPackageConan(t *testing.T) { MakeRequest(t, req, http.StatusOK) revisions, err = conan_model.GetRecipeRevisions(db.DefaultContext, user.ID, rref) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, revisions, "case %d: should be empty", i) } }) @@ -510,7 +511,7 @@ func TestPackageConan(t *testing.T) { defer tests.PrintCurrentTest(t)() pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConan) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 2) }) }) @@ -651,12 +652,12 @@ func TestPackageConan(t *testing.T) { checkPackageRevisionCount := func(count int) { revisions, err := conan_model.GetPackageRevisions(db.DefaultContext, user.ID, pref) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, revisions, count) } checkPackageReferenceCount := func(count int) { references, err := conan_model.GetPackageReferences(db.DefaultContext, user.ID, rref) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, references, count) } @@ -692,7 +693,7 @@ func TestPackageConan(t *testing.T) { checkRecipeRevisionCount := func(count int) { revisions, err := conan_model.GetRecipeRevisions(db.DefaultContext, user.ID, rref) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, revisions, count) } diff --git a/tests/integration/api_packages_conda_test.go b/tests/integration/api_packages_conda_test.go index bb269e82d6..1367897f02 100644 --- a/tests/integration/api_packages_conda_test.go +++ b/tests/integration/api_packages_conda_test.go @@ -22,6 +22,7 @@ import ( "github.com/dsnet/compress/bzip2" "github.com/klauspost/compress/zstd" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageConda(t *testing.T) { @@ -75,11 +76,11 @@ func TestPackageConda(t *testing.T) { MakeRequest(t, req, http.StatusConflict) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConda) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &conda_module.VersionMetadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) @@ -116,11 +117,11 @@ func TestPackageConda(t *testing.T) { MakeRequest(t, req, http.StatusConflict) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeConda) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 2) pds, err := packages.GetPackageDescriptors(db.DefaultContext, pvs) - assert.NoError(t, err) + require.NoError(t, err) assert.Condition(t, func() bool { for _, pd := range pds { @@ -213,10 +214,10 @@ func TestPackageConda(t *testing.T) { defer tests.PrintCurrentTest(t)() pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeConda, packageName, packageVersion) - assert.NoError(t, err) + require.NoError(t, err) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv) - assert.NoError(t, err) + require.NoError(t, err) req := NewRequest(t, "GET", fmt.Sprintf("%s/noarch/repodata.json", root)) resp := MakeRequest(t, req, http.StatusOK) @@ -244,10 +245,10 @@ func TestPackageConda(t *testing.T) { defer tests.PrintCurrentTest(t)() pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeConda, channel+"/"+packageName, packageVersion) - assert.NoError(t, err) + require.NoError(t, err) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv) - assert.NoError(t, err) + require.NoError(t, err) req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/noarch/repodata.json", root, channel)) resp := MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/api_packages_container_test.go b/tests/integration/api_packages_container_test.go index 9ac6e5256b..1197408830 100644 --- a/tests/integration/api_packages_container_test.go +++ b/tests/integration/api_packages_container_test.go @@ -27,6 +27,7 @@ import ( oci "github.com/opencontainers/image-spec/specs-go/v1" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageContainer(t *testing.T) { @@ -174,14 +175,14 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, blobDigest, resp.Header().Get("Docker-Content-Digest")) pv, err := packages_model.GetInternalVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, container_model.UploadVersion) - assert.NoError(t, err) + require.NoError(t, err) pfs, err := packages_model.GetFilesByVersionID(db.DefaultContext, pv.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) pb, err := packages_model.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, len(blobContent), pb.Size) }) @@ -196,7 +197,7 @@ func TestPackageContainer(t *testing.T) { assert.NotEmpty(t, uuid) pbu, err := packages_model.GetBlobUploadByID(db.DefaultContext, uuid) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, pbu.BytesReceived) uploadURL := resp.Header().Get("Location") @@ -228,7 +229,7 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, fmt.Sprintf("0-%d", len(blobContent)), resp.Header().Get("Range")) pbu, err = packages_model.GetBlobUploadByID(db.DefaultContext, uuid) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, len(blobContent), pbu.BytesReceived) req = NewRequest(t, "PUT", fmt.Sprintf("%s?digest=%s", setting.AppURL+uploadURL[1:], blobDigest)). @@ -325,10 +326,10 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, manifestDigest, resp.Header().Get("Docker-Content-Digest")) pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag) - assert.NoError(t, err) + require.NoError(t, err) pd, err := packages_model.GetPackageDescriptor(db.DefaultContext, pv) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.Equal(t, image, pd.Package.Name) assert.Equal(t, tag, pd.Version.Version) @@ -366,7 +367,7 @@ func TestPackageContainer(t *testing.T) { MakeRequest(t, req, http.StatusOK) pv, err = packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, pv.DownloadCount) // Overwrite existing tag should keep the download count @@ -376,7 +377,7 @@ func TestPackageContainer(t *testing.T) { MakeRequest(t, req, http.StatusCreated) pv, err = packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, tag) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, pv.DownloadCount) }) @@ -432,10 +433,10 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, untaggedManifestDigest, resp.Header().Get("Docker-Content-Digest")) pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, untaggedManifestDigest) - assert.NoError(t, err) + require.NoError(t, err) pd, err := packages_model.GetPackageDescriptor(db.DefaultContext, pv) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.Equal(t, image, pd.Package.Name) assert.Equal(t, untaggedManifestDigest, pd.Version.Version) @@ -465,10 +466,10 @@ func TestPackageContainer(t *testing.T) { assert.Equal(t, indexManifestDigest, resp.Header().Get("Docker-Content-Digest")) pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, image, multiTag) - assert.NoError(t, err) + require.NoError(t, err) pd, err := packages_model.GetPackageDescriptor(db.DefaultContext, pv) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.Equal(t, image, pd.Package.Name) assert.Equal(t, multiTag, pd.Version.Version) diff --git a/tests/integration/api_packages_cran_test.go b/tests/integration/api_packages_cran_test.go index d307e87d4e..31864d1ab7 100644 --- a/tests/integration/api_packages_cran_test.go +++ b/tests/integration/api_packages_cran_test.go @@ -20,6 +20,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageCran(t *testing.T) { @@ -84,18 +85,18 @@ func TestPackageCran(t *testing.T) { MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeCran) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &cran_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s_%s.tar.gz", packageName, packageVersion), pfs[0].Name) assert.True(t, pfs[0].IsLead) @@ -175,11 +176,11 @@ func TestPackageCran(t *testing.T) { MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeCran) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 2) req = NewRequestWithBody(t, "PUT", uploadURL, createArchive( diff --git a/tests/integration/api_packages_debian_test.go b/tests/integration/api_packages_debian_test.go index 05979fccb5..d85f56fdbb 100644 --- a/tests/integration/api_packages_debian_test.go +++ b/tests/integration/api_packages_debian_test.go @@ -23,6 +23,7 @@ import ( "github.com/blakesmith/ar" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageDebian(t *testing.T) { @@ -102,17 +103,17 @@ func TestPackageDebian(t *testing.T) { MakeRequest(t, req, http.StatusCreated) pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeDebian, packageName, packageVersion) - assert.NoError(t, err) + require.NoError(t, err) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &debian_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pv.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, pfs) assert.Condition(t, func() bool { seen := false @@ -128,7 +129,7 @@ func TestPackageDebian(t *testing.T) { assert.True(t, pf.IsLead) pfps, err := packages.GetProperties(db.DefaultContext, packages.PropertyTypeFile, pf.ID) - assert.NoError(t, err) + require.NoError(t, err) for _, pfp := range pfps { switch pfp.Name { diff --git a/tests/integration/api_packages_generic_test.go b/tests/integration/api_packages_generic_test.go index 1cbae599af..1a53f33387 100644 --- a/tests/integration/api_packages_generic_test.go +++ b/tests/integration/api_packages_generic_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageGeneric(t *testing.T) { @@ -40,23 +41,23 @@ func TestPackageGeneric(t *testing.T) { MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) t.Run("Exists", func(t *testing.T) { @@ -76,7 +77,7 @@ func TestPackageGeneric(t *testing.T) { // Check deduplication pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 2) assert.Equal(t, pfs[0].BlobID, pfs[1].BlobID) }) @@ -103,7 +104,7 @@ func TestPackageGeneric(t *testing.T) { checkDownloadCount := func(count int64) { pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, count, pvs[0].DownloadCount) } @@ -167,11 +168,11 @@ func TestPackageGeneric(t *testing.T) { assert.NotEmpty(t, location) resp2, err := (&http.Client{}).Get(location) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, http.StatusOK, resp2.StatusCode) body, err := io.ReadAll(resp2.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, content, body) checkDownloadCount(3) @@ -199,7 +200,7 @@ func TestPackageGeneric(t *testing.T) { MakeRequest(t, req, http.StatusNotFound) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) t.Run("RemovesVersion", func(t *testing.T) { @@ -210,7 +211,7 @@ func TestPackageGeneric(t *testing.T) { MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, pvs) }) }) @@ -230,7 +231,7 @@ func TestPackageGeneric(t *testing.T) { MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGeneric) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, pvs) req = NewRequest(t, "GET", url+"/"+filename) diff --git a/tests/integration/api_packages_goproxy_test.go b/tests/integration/api_packages_goproxy_test.go index dab9fefc5e..716d90b242 100644 --- a/tests/integration/api_packages_goproxy_test.go +++ b/tests/integration/api_packages_goproxy_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageGo(t *testing.T) { @@ -64,23 +65,23 @@ func TestPackageGo(t *testing.T) { MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeGo) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, packageVersion+".zip", pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) req = NewRequestWithBody(t, "PUT", url+"/upload", bytes.NewReader(content)). diff --git a/tests/integration/api_packages_helm_test.go b/tests/integration/api_packages_helm_test.go index 76285add11..4b48b74ce0 100644 --- a/tests/integration/api_packages_helm_test.go +++ b/tests/integration/api_packages_helm_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) @@ -73,24 +74,24 @@ dependencies: MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeHelm) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &helm_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) req = NewRequestWithBody(t, "POST", uploadURL, bytes.NewReader(content)). @@ -103,7 +104,7 @@ dependencies: checkDownloadCount := func(count int64) { pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeHelm) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, count, pvs[0].DownloadCount) } @@ -146,7 +147,7 @@ dependencies: } var result Index - assert.NoError(t, yaml.NewDecoder(resp.Body).Decode(&result)) + require.NoError(t, yaml.NewDecoder(resp.Body).Decode(&result)) assert.NotEmpty(t, result.Entries) assert.Contains(t, result.Entries, packageName) diff --git a/tests/integration/api_packages_maven_test.go b/tests/integration/api_packages_maven_test.go index 2fc4a0f6de..7ada3b28ac 100644 --- a/tests/integration/api_packages_maven_test.go +++ b/tests/integration/api_packages_maven_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageMaven(t *testing.T) { @@ -54,24 +55,24 @@ func TestPackageMaven(t *testing.T) { putFile(t, "/maven-metadata.xml", "test", http.StatusOK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeMaven) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.Nil(t, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.False(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(4), pb.Size) }) @@ -99,7 +100,7 @@ func TestPackageMaven(t *testing.T) { assert.Equal(t, []byte("test"), resp.Body.Bytes()) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeMaven) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(0), pvs[0].DownloadCount) }) @@ -131,26 +132,26 @@ func TestPackageMaven(t *testing.T) { defer tests.PrintCurrentTest(t)() pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeMaven) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.Metadata) putFile(t, fmt.Sprintf("/%s/%s.pom", packageVersion, filename), pomContent, http.StatusCreated) pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeMaven) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err = packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.IsType(t, &maven.Metadata{}, pd.Metadata) assert.Equal(t, packageDescription, pd.Metadata.(*maven.Metadata).Description) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 2) for _, pf := range pfs { if strings.HasSuffix(pf.Name, ".pom") { @@ -180,7 +181,7 @@ func TestPackageMaven(t *testing.T) { assert.Equal(t, []byte(pomContent), resp.Body.Bytes()) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeMaven) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(1), pvs[0].DownloadCount) }) diff --git a/tests/integration/api_packages_npm_test.go b/tests/integration/api_packages_npm_test.go index 9c888972ff..d0c54c306b 100644 --- a/tests/integration/api_packages_npm_test.go +++ b/tests/integration/api_packages_npm_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageNpm(t *testing.T) { @@ -92,11 +93,11 @@ func TestPackageNpm(t *testing.T) { MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &npm.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) @@ -106,13 +107,13 @@ func TestPackageNpm(t *testing.T) { assert.Equal(t, packageTag, pd.VersionProperties[0].Value) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(192), pb.Size) }) @@ -141,7 +142,7 @@ func TestPackageNpm(t *testing.T) { assert.Equal(t, b, resp.Body.Bytes()) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(2), pvs[0].DownloadCount) }) @@ -294,7 +295,7 @@ func TestPackageNpm(t *testing.T) { defer tests.PrintCurrentTest(t)() pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 2) req := NewRequest(t, "DELETE", fmt.Sprintf("%s/-/%s/%s/-rev/dummy", root, packageVersion, filename)) @@ -305,7 +306,7 @@ func TestPackageNpm(t *testing.T) { MakeRequest(t, req, http.StatusOK) pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) }) @@ -313,7 +314,7 @@ func TestPackageNpm(t *testing.T) { defer tests.PrintCurrentTest(t)() pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) req := NewRequest(t, "DELETE", root+"/-rev/dummy") @@ -324,8 +325,8 @@ func TestPackageNpm(t *testing.T) { MakeRequest(t, req, http.StatusOK) pvs, err = packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNpm) - assert.NoError(t, err) - assert.Len(t, pvs, 0) + require.NoError(t, err) + assert.Empty(t, pvs) }) }) } diff --git a/tests/integration/api_packages_nuget_test.go b/tests/integration/api_packages_nuget_test.go index e0ec279d7a..321bcd7e1c 100644 --- a/tests/integration/api_packages_nuget_test.go +++ b/tests/integration/api_packages_nuget_test.go @@ -29,6 +29,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func addNuGetAPIKeyHeader(req *RequestWrapper, token string) { @@ -38,7 +39,7 @@ func addNuGetAPIKeyHeader(req *RequestWrapper, token string) { func decodeXML(t testing.TB, resp *httptest.ResponseRecorder, v any) { t.Helper() - assert.NoError(t, xml.NewDecoder(resp.Body).Decode(v)) + require.NoError(t, xml.NewDecoder(resp.Body).Decode(v)) } func TestPackageNuGet(t *testing.T) { @@ -237,24 +238,24 @@ func TestPackageNuGet(t *testing.T) { MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1, "Should have one version") pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &nuget_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 2, "Should have 2 files: nuget and nuspec") assert.Equal(t, fmt.Sprintf("%s.%s.nupkg", packageName, packageVersion), pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). @@ -304,18 +305,18 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &nuget_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 4, "Should have 4 files: nupkg, snupkg, nuspec and pdb") for _, pf := range pfs { switch pf.Name { @@ -323,29 +324,29 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) assert.True(t, pf.IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(414), pb.Size) case fmt.Sprintf("%s.%s.snupkg", packageName, packageVersion): assert.False(t, pf.IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(616), pb.Size) case fmt.Sprintf("%s.nuspec", packageName): assert.False(t, pf.IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(453), pb.Size) case symbolFilename: assert.False(t, pf.IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(160), pb.Size) pps, err := packages.GetProperties(db.DefaultContext, packages.PropertyTypeFile, pf.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pps, 1) assert.Equal(t, nuget_module.PropertySymbolID, pps[0].Name) assert.Equal(t, symbolID, pps[0].Value) @@ -365,7 +366,7 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) checkDownloadCount := func(count int64) { pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, count, pvs[0].DownloadCount) } @@ -417,7 +418,7 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) if l.Rel == "next" { found++ u, err := neturl.Parse(l.Href) - assert.NoError(t, err) + require.NoError(t, err) q := u.Query() assert.Contains(t, q, "$skip") assert.Contains(t, q, "$top") @@ -736,7 +737,7 @@ AAAjQmxvYgAAAGm7ENm9SGxMtAFVvPUsPJTF6PbtAAAAAFcVogEJAAAAAQAAAA==`) MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeNuGet) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, pvs) }) diff --git a/tests/integration/api_packages_pub_test.go b/tests/integration/api_packages_pub_test.go index 11da894ddf..d6bce3055e 100644 --- a/tests/integration/api_packages_pub_test.go +++ b/tests/integration/api_packages_pub_test.go @@ -24,6 +24,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackagePub(t *testing.T) { @@ -101,24 +102,24 @@ description: ` + packageDescription MakeRequest(t, req, http.StatusOK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypePub) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &pub_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) _ = uploadFile(t, result.URL, content, http.StatusConflict) diff --git a/tests/integration/api_packages_pypi_test.go b/tests/integration/api_packages_pypi_test.go index e973f6a52a..ef03dbe509 100644 --- a/tests/integration/api_packages_pypi_test.go +++ b/tests/integration/api_packages_pypi_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackagePyPI(t *testing.T) { @@ -67,24 +68,24 @@ func TestPackagePyPI(t *testing.T) { uploadFile(t, filename, content, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypePyPI) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &pypi.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(4), pb.Size) }) @@ -95,27 +96,27 @@ func TestPackagePyPI(t *testing.T) { uploadFile(t, filename, content, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypePyPI) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &pypi.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 2) pf, err := packages.GetFileForVersionByName(db.DefaultContext, pvs[0].ID, filename, packages.EmptyFileKey) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, filename, pf.Name) assert.True(t, pf.IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pf.BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(4), pb.Size) }) @@ -148,7 +149,7 @@ func TestPackagePyPI(t *testing.T) { downloadFile("test.tar.gz") pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypePyPI) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(2), pvs[0].DownloadCount) }) diff --git a/tests/integration/api_packages_rpm_test.go b/tests/integration/api_packages_rpm_test.go index 1dcec6099e..2b9c4c7bcb 100644 --- a/tests/integration/api_packages_rpm_test.go +++ b/tests/integration/api_packages_rpm_test.go @@ -25,6 +25,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageRpm(t *testing.T) { @@ -65,13 +66,13 @@ Mu0UFYgZ/bYnuvn/vz4wtCz8qMwsHUvP0PX3tbYFUctAPdrY6tiiDtcCddDECahx7SuVNP5dpmb5 7tpp/pEjDS7cGPZ6BY430+7danDq6f42Nw49b9F7zp6BiKpJb9s5P0AYN2+L159cnrur636rx+v1 7ae1K28QbMMcqI8CqwIrgwg9nTOp8Oj9q81plUY7ZuwXN8Vvs8wbAAA=` rpmPackageContent, err := base64.StdEncoding.DecodeString(base64RpmPackageContent) - assert.NoError(t, err) + require.NoError(t, err) zr, err := gzip.NewReader(bytes.NewReader(rpmPackageContent)) - assert.NoError(t, err) + require.NoError(t, err) content, err := io.ReadAll(zr) - assert.NoError(t, err) + require.NoError(t, err) rootURL := fmt.Sprintf("/api/packages/%s/rpm", user.Name) @@ -126,24 +127,24 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, MakeRequest(t, req, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRpm) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, pd.SemVer) assert.IsType(t, &rpm_module.VersionMetadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s-%s.%s.rpm", packageName, packageVersion, packageArchitecture), pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) req = NewRequestWithBody(t, "PUT", url, bytes.NewReader(content)). @@ -245,9 +246,9 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, t.Helper() zr, err := gzip.NewReader(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, xml.NewDecoder(zr).Decode(v)) + require.NoError(t, xml.NewDecoder(zr).Decode(v)) } t.Run("primary.xml.gz", func(t *testing.T) { @@ -425,7 +426,7 @@ gpgkey=%sapi/packages/%s/rpm/repository.key`, MakeRequest(t, req, http.StatusNoContent) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRpm) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, pvs) req = NewRequest(t, "DELETE", fmt.Sprintf("%s/package/%s/%s/%s", groupURL, packageName, packageVersion, packageArchitecture)). AddBasicAuth(user.Name) diff --git a/tests/integration/api_packages_rubygems_test.go b/tests/integration/api_packages_rubygems_test.go index 26f41d7061..eb3dc0e7f2 100644 --- a/tests/integration/api_packages_rubygems_test.go +++ b/tests/integration/api_packages_rubygems_test.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageRubyGems(t *testing.T) { @@ -214,24 +215,24 @@ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==`) uploadFile(t, gemContent, http.StatusCreated) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &rubygems.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, packageFilename, pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(4608), pb.Size) }) @@ -251,7 +252,7 @@ AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==`) assert.Equal(t, gemContent, resp.Body.Bytes()) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(1), pvs[0].DownloadCount) }) @@ -270,7 +271,7 @@ gAAAAP//MS06Gw==`) assert.Equal(t, b, resp.Body.Bytes()) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) assert.Equal(t, int64(1), pvs[0].DownloadCount) }) @@ -375,7 +376,7 @@ gAAAAP//MS06Gw==`) MakeRequest(t, req, http.StatusOK) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeRubyGems) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, pvs) }) diff --git a/tests/integration/api_packages_swift_test.go b/tests/integration/api_packages_swift_test.go index 7d4ff954e2..5b6229f721 100644 --- a/tests/integration/api_packages_swift_test.go +++ b/tests/integration/api_packages_swift_test.go @@ -23,6 +23,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageSwift(t *testing.T) { @@ -131,11 +132,11 @@ func TestPackageSwift(t *testing.T) { ) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeSwift) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.Equal(t, packageID, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) @@ -149,7 +150,7 @@ func TestPackageSwift(t *testing.T) { assert.Equal(t, packageRepositoryURL, pd.VersionProperties.GetByName(swift_module.PropertyRepositoryURL)) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, fmt.Sprintf("%s-%s.zip", packageName, packageVersion), pfs[0].Name) assert.True(t, pfs[0].IsLead) @@ -178,10 +179,10 @@ func TestPackageSwift(t *testing.T) { pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeSwift, packageID, packageVersion) assert.NotNil(t, pv) - assert.NoError(t, err) + require.NoError(t, err) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "sha256="+pd.Files[0].Blob.HashSHA256, resp.Header().Get("Digest")) }) @@ -231,10 +232,10 @@ func TestPackageSwift(t *testing.T) { pv, err := packages.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages.TypeSwift, packageID, packageVersion) assert.NotNil(t, pv) - assert.NoError(t, err) + require.NoError(t, err) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pv) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, packageID, result.ID) assert.Equal(t, packageVersion, result.Version) diff --git a/tests/integration/api_packages_test.go b/tests/integration/api_packages_test.go index 9021d4e7fa..27aed0feb1 100644 --- a/tests/integration/api_packages_test.go +++ b/tests/integration/api_packages_test.go @@ -26,6 +26,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageAPI(t *testing.T) { @@ -87,7 +88,7 @@ func TestPackageAPI(t *testing.T) { defer tests.PrintCurrentTest(t)() p, err := packages_model.GetPackageByName(db.DefaultContext, user.ID, packages_model.TypeGeneric, packageName) - assert.NoError(t, err) + require.NoError(t, err) // no repository link req := NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). @@ -99,7 +100,7 @@ func TestPackageAPI(t *testing.T) { assert.Nil(t, ap1.Repository) // link to public repository - assert.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, p.ID, 1)) + require.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, p.ID, 1)) req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). AddTokenAuth(tokenReadPackage) @@ -111,7 +112,7 @@ func TestPackageAPI(t *testing.T) { assert.EqualValues(t, 1, ap2.Repository.ID) // link to private repository - assert.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, p.ID, 2)) + require.NoError(t, packages_model.SetRepositoryLink(db.DefaultContext, p.ID, 2)) req = NewRequest(t, "GET", fmt.Sprintf("/api/v1/packages/%s/generic/%s/%s", user.Name, packageName, packageVersion)). AddTokenAuth(tokenReadPackage) @@ -121,7 +122,7 @@ func TestPackageAPI(t *testing.T) { DecodeJSON(t, resp, &ap3) assert.Nil(t, ap3.Repository) - assert.NoError(t, packages_model.UnlinkRepositoryFromAllPackages(db.DefaultContext, 2)) + require.NoError(t, packages_model.UnlinkRepositoryFromAllPackages(db.DefaultContext, 2)) }) }) @@ -482,23 +483,23 @@ func TestPackageCleanup(t *testing.T) { unittest.AssertExistsAndLoadBean(t, &packages_model.Package{Name: "cleanup-test"}) pbs, err := packages_model.FindExpiredUnreferencedBlobs(db.DefaultContext, duration) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, pbs) _, err = packages_model.GetInternalVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, "cleanup-test", container_model.UploadVersion) - assert.NoError(t, err) + require.NoError(t, err) err = packages_cleanup_service.CleanupTask(db.DefaultContext, duration) - assert.NoError(t, err) + require.NoError(t, err) pbs, err = packages_model.FindExpiredUnreferencedBlobs(db.DefaultContext, duration) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, pbs) unittest.AssertNotExistsBean(t, &packages_model.Package{Name: "cleanup-test"}) _, err = packages_model.GetInternalVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeContainer, "cleanup-test", container_model.UploadVersion) - assert.ErrorIs(t, err, packages_model.ErrPackageNotExist) + require.ErrorIs(t, err, packages_model.ErrPackageNotExist) }) t.Run("CleanupRules", func(t *testing.T) { @@ -613,9 +614,9 @@ func TestPackageCleanup(t *testing.T) { if v.Created != 0 { pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeGeneric, "package", v.Version) - assert.NoError(t, err) + require.NoError(t, err) _, err = db.GetEngine(db.DefaultContext).Exec("UPDATE package_version SET created_unix = ? WHERE id = ?", v.Created, pv.ID) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -623,23 +624,23 @@ func TestPackageCleanup(t *testing.T) { c.Rule.Type = packages_model.TypeGeneric pcr, err := packages_model.InsertCleanupRule(db.DefaultContext, c.Rule) - assert.NoError(t, err) + require.NoError(t, err) err = packages_cleanup_service.CleanupTask(db.DefaultContext, duration) - assert.NoError(t, err) + require.NoError(t, err) for _, v := range c.Versions { pv, err := packages_model.GetVersionByNameAndVersion(db.DefaultContext, user.ID, packages_model.TypeGeneric, "package", v.Version) if v.ShouldExist { - assert.NoError(t, err) + require.NoError(t, err) err = packages_service.DeletePackageVersionAndReferences(db.DefaultContext, pv) - assert.NoError(t, err) + require.NoError(t, err) } else { - assert.ErrorIs(t, err, packages_model.ErrPackageNotExist) + require.ErrorIs(t, err, packages_model.ErrPackageNotExist) } } - assert.NoError(t, packages_model.DeleteCleanupRuleByID(db.DefaultContext, pcr.ID)) + require.NoError(t, packages_model.DeleteCleanupRuleByID(db.DefaultContext, pcr.ID)) }) } }) diff --git a/tests/integration/api_packages_vagrant_test.go b/tests/integration/api_packages_vagrant_test.go index a5e954f3a2..b446466296 100644 --- a/tests/integration/api_packages_vagrant_test.go +++ b/tests/integration/api_packages_vagrant_test.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPackageVagrant(t *testing.T) { @@ -91,24 +92,24 @@ func TestPackageVagrant(t *testing.T) { assert.True(t, strings.HasPrefix(resp.Header().Get("Content-Type"), "application/json")) pvs, err := packages.GetVersionsByPackageType(db.DefaultContext, user.ID, packages.TypeVagrant) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pvs, 1) pd, err := packages.GetPackageDescriptor(db.DefaultContext, pvs[0]) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, pd.SemVer) assert.IsType(t, &vagrant_module.Metadata{}, pd.Metadata) assert.Equal(t, packageName, pd.Package.Name) assert.Equal(t, packageVersion, pd.Version.Version) pfs, err := packages.GetFilesByVersionID(db.DefaultContext, pvs[0].ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, pfs, 1) assert.Equal(t, filename, pfs[0].Name) assert.True(t, pfs[0].IsLead) pb, err := packages.GetBlobByID(db.DefaultContext, pfs[0].BlobID) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(len(content)), pb.Size) req = NewRequestWithBody(t, "PUT", uploadURL, bytes.NewReader(content)). diff --git a/tests/integration/api_private_serv_test.go b/tests/integration/api_private_serv_test.go index 2001bb1fad..3339fc4430 100644 --- a/tests/integration/api_private_serv_test.go +++ b/tests/integration/api_private_serv_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/private" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIPrivateNoServ(t *testing.T) { @@ -20,17 +21,17 @@ func TestAPIPrivateNoServ(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() key, user, err := private.ServNoCommand(ctx, 1) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, int64(2), user.ID) assert.Equal(t, "user2", user.Name) assert.Equal(t, int64(1), key.ID) assert.Equal(t, "user2@localhost", key.Name) deployKey, err := asymkey_model.AddDeployKey(ctx, 1, "test-deploy", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment", false) - assert.NoError(t, err) + require.NoError(t, err) key, user, err = private.ServNoCommand(ctx, deployKey.KeyID) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, user) assert.Equal(t, deployKey.KeyID, key.ID) assert.Equal(t, "test-deploy", key.Name) @@ -44,7 +45,7 @@ func TestAPIPrivateServ(t *testing.T) { // Can push to a repo we own results, extra := private.ServCommand(ctx, 1, "user2", "repo1", perm.AccessModeWrite, "git-upload-pack", "") - assert.NoError(t, extra.Error) + require.NoError(t, extra.Error) assert.False(t, results.IsWiki) assert.Zero(t, results.DeployKeyID) assert.Equal(t, int64(1), results.KeyID) @@ -57,17 +58,17 @@ func TestAPIPrivateServ(t *testing.T) { // Cannot push to a private repo we're not associated with results, extra = private.ServCommand(ctx, 1, "user15", "big_test_private_1", perm.AccessModeWrite, "git-upload-pack", "") - assert.Error(t, extra.Error) + require.Error(t, extra.Error) assert.Empty(t, results) // Cannot pull from a private repo we're not associated with results, extra = private.ServCommand(ctx, 1, "user15", "big_test_private_1", perm.AccessModeRead, "git-upload-pack", "") - assert.Error(t, extra.Error) + require.Error(t, extra.Error) assert.Empty(t, results) // Can pull from a public repo we're not associated with results, extra = private.ServCommand(ctx, 1, "user15", "big_test_public_1", perm.AccessModeRead, "git-upload-pack", "") - assert.NoError(t, extra.Error) + require.NoError(t, extra.Error) assert.False(t, results.IsWiki) assert.Zero(t, results.DeployKeyID) assert.Equal(t, int64(1), results.KeyID) @@ -80,16 +81,16 @@ func TestAPIPrivateServ(t *testing.T) { // Cannot push to a public repo we're not associated with results, extra = private.ServCommand(ctx, 1, "user15", "big_test_public_1", perm.AccessModeWrite, "git-upload-pack", "") - assert.Error(t, extra.Error) + require.Error(t, extra.Error) assert.Empty(t, results) // Add reading deploy key deployKey, err := asymkey_model.AddDeployKey(ctx, 19, "test-deploy", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment", true) - assert.NoError(t, err) + require.NoError(t, err) // Can pull from repo we're a deploy key for results, extra = private.ServCommand(ctx, deployKey.KeyID, "user15", "big_test_private_1", perm.AccessModeRead, "git-upload-pack", "") - assert.NoError(t, extra.Error) + require.NoError(t, extra.Error) assert.False(t, results.IsWiki) assert.NotZero(t, results.DeployKeyID) assert.Equal(t, deployKey.KeyID, results.KeyID) @@ -102,31 +103,31 @@ func TestAPIPrivateServ(t *testing.T) { // Cannot push to a private repo with reading key results, extra = private.ServCommand(ctx, deployKey.KeyID, "user15", "big_test_private_1", perm.AccessModeWrite, "git-upload-pack", "") - assert.Error(t, extra.Error) + require.Error(t, extra.Error) assert.Empty(t, results) // Cannot pull from a private repo we're not associated with results, extra = private.ServCommand(ctx, deployKey.ID, "user15", "big_test_private_2", perm.AccessModeRead, "git-upload-pack", "") - assert.Error(t, extra.Error) + require.Error(t, extra.Error) assert.Empty(t, results) // Cannot pull from a public repo we're not associated with results, extra = private.ServCommand(ctx, deployKey.ID, "user15", "big_test_public_1", perm.AccessModeRead, "git-upload-pack", "") - assert.Error(t, extra.Error) + require.Error(t, extra.Error) assert.Empty(t, results) // Add writing deploy key deployKey, err = asymkey_model.AddDeployKey(ctx, 20, "test-deploy", "sk-ecdsa-sha2-nistp256@openssh.com AAAAInNrLWVjZHNhLXNoYTItbmlzdHAyNTZAb3BlbnNzaC5jb20AAAAIbmlzdHAyNTYAAABBBGXEEzWmm1dxb+57RoK5KVCL0w2eNv9cqJX2AGGVlkFsVDhOXHzsadS3LTK4VlEbbrDMJdoti9yM8vclA8IeRacAAAAEc3NoOg== nocomment", false) - assert.NoError(t, err) + require.NoError(t, err) // Cannot push to a private repo with reading key results, extra = private.ServCommand(ctx, deployKey.KeyID, "user15", "big_test_private_1", perm.AccessModeWrite, "git-upload-pack", "") - assert.Error(t, extra.Error) + require.Error(t, extra.Error) assert.Empty(t, results) // Can pull from repo we're a writing deploy key for results, extra = private.ServCommand(ctx, deployKey.KeyID, "user15", "big_test_private_2", perm.AccessModeRead, "git-upload-pack", "") - assert.NoError(t, extra.Error) + require.NoError(t, extra.Error) assert.False(t, results.IsWiki) assert.NotZero(t, results.DeployKeyID) assert.Equal(t, deployKey.KeyID, results.KeyID) @@ -139,7 +140,7 @@ func TestAPIPrivateServ(t *testing.T) { // Can push to repo we're a writing deploy key for results, extra = private.ServCommand(ctx, deployKey.KeyID, "user15", "big_test_private_2", perm.AccessModeWrite, "git-upload-pack", "") - assert.NoError(t, extra.Error) + require.NoError(t, extra.Error) assert.False(t, results.IsWiki) assert.NotZero(t, results.DeployKeyID) assert.Equal(t, deployKey.KeyID, results.KeyID) diff --git a/tests/integration/api_pull_commits_test.go b/tests/integration/api_pull_commits_test.go index ad0cb0329c..d62b9d9140 100644 --- a/tests/integration/api_pull_commits_test.go +++ b/tests/integration/api_pull_commits_test.go @@ -15,12 +15,13 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIPullCommits(t *testing.T) { defer tests.PrepareTestEnv(t)() pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + require.NoError(t, pr.LoadIssue(db.DefaultContext)) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pr.HeadRepoID}) req := NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/commits", repo.OwnerName, repo.Name, pr.Index) diff --git a/tests/integration/api_pull_review_test.go b/tests/integration/api_pull_review_test.go index bc536b4f7a..b7e5130cb8 100644 --- a/tests/integration/api_pull_review_test.go +++ b/tests/integration/api_pull_review_test.go @@ -27,7 +27,7 @@ import ( func TestAPIPullReviewCreateDeleteComment(t *testing.T) { defer tests.PrepareTestEnv(t)() pullIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) - assert.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) + require.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.RepoID}) username := "user2" @@ -71,7 +71,7 @@ func TestAPIPullReviewCreateDeleteComment(t *testing.T) { resp := MakeRequest(t, req, http.StatusOK) var reviews []*api.PullReview DecodeJSON(t, resp, &reviews) - require.EqualValues(t, count, len(reviews)) + require.Len(t, reviews, count) } { @@ -148,7 +148,7 @@ func TestAPIPullReviewCreateDeleteComment(t *testing.T) { func TestAPIPullReview(t *testing.T) { defer tests.PrepareTestEnv(t)() pullIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) - assert.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) + require.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.RepoID}) // test ListPullReviews @@ -333,7 +333,7 @@ func TestAPIPullReview(t *testing.T) { // test get review requests // to make it simple, use same api with get review pullIssue12 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 12}) - assert.NoError(t, pullIssue12.LoadAttributes(db.DefaultContext)) + require.NoError(t, pullIssue12.LoadAttributes(db.DefaultContext)) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue12.RepoID}) req = NewRequestf(t, http.MethodGet, "/api/v1/repos/%s/%s/pulls/%d/reviews", repo3.OwnerName, repo3.Name, pullIssue12.Index). @@ -358,7 +358,7 @@ func TestAPIPullReview(t *testing.T) { func TestAPIPullReviewRequest(t *testing.T) { defer tests.PrepareTestEnv(t)() pullIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) - assert.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) + require.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.RepoID}) // Test add Review Request @@ -403,7 +403,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // a collaborator can add/remove a review request pullIssue21 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 21}) - assert.NoError(t, pullIssue21.LoadAttributes(db.DefaultContext)) + require.NoError(t, pullIssue21.LoadAttributes(db.DefaultContext)) pull21Repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue21.RepoID}) // repo60 user38Session := loginUser(t, "user38") user38Token := getTokenForLoggedInUser(t, user38Session, auth_model.AccessTokenScopeWriteRepository) @@ -432,7 +432,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // user with read permission on pull requests unit can add/remove a review request pullIssue22 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 22}) - assert.NoError(t, pullIssue22.LoadAttributes(db.DefaultContext)) + require.NoError(t, pullIssue22.LoadAttributes(db.DefaultContext)) pull22Repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue22.RepoID}) // repo61 req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", pull22Repo.OwnerName, pull22Repo.Name, pullIssue22.Index), &api.PullReviewRequestOptions{ Reviewers: []string{"user38"}, @@ -446,7 +446,7 @@ func TestAPIPullReviewRequest(t *testing.T) { // Test team review request pullIssue12 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 12}) - assert.NoError(t, pullIssue12.LoadAttributes(db.DefaultContext)) + require.NoError(t, pullIssue12.LoadAttributes(db.DefaultContext)) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue12.RepoID}) // Test add Team Review Request @@ -488,7 +488,7 @@ func TestAPIPullReviewStayDismissed(t *testing.T) { // where old reviews surface after a review request got dismissed. defer tests.PrepareTestEnv(t)() pullIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) - assert.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) + require.NoError(t, pullIssue.LoadAttributes(db.DefaultContext)) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: pullIssue.RepoID}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) session2 := loginUser(t, user2.LoginName) @@ -531,7 +531,7 @@ func TestAPIPullReviewStayDismissed(t *testing.T) { // emulate of auto-dismiss lgtm on a protected branch that where a pull just got an update _, err := db.GetEngine(db.DefaultContext).Where("issue_id = ? AND reviewer_id = ?", pullIssue.ID, user8.ID). Cols("dismissed").Update(&issues_model.Review{Dismissed: true}) - assert.NoError(t, err) + require.NoError(t, err) // user2 request user8 again req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls/%d/requested_reviewers", repo.OwnerName, repo.Name, pullIssue.Index), &api.PullReviewRequestOptions{ @@ -545,7 +545,7 @@ func TestAPIPullReviewStayDismissed(t *testing.T) { // user8 dismiss review _, err = issue_service.ReviewRequest(db.DefaultContext, pullIssue, user8, user8, false) - assert.NoError(t, err) + require.NoError(t, err) reviewsCountCheck(t, "check new review request is now dismissed", diff --git a/tests/integration/api_pull_test.go b/tests/integration/api_pull_test.go index b1bd0aba85..51c25fb75f 100644 --- a/tests/integration/api_pull_test.go +++ b/tests/integration/api_pull_test.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIViewPulls(t *testing.T) { @@ -44,7 +45,7 @@ func TestAPIViewPulls(t *testing.T) { if assert.EqualValues(t, 5, pull.ID) { resp = ctx.Session.MakeRequest(t, NewRequest(t, "GET", pull.DiffURL), http.StatusOK) _, err := io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) // TODO: use diff to generate stats to test against t.Run(fmt.Sprintf("APIGetPullFiles_%d", pull.ID), @@ -248,7 +249,7 @@ func TestAPIEditPull(t *testing.T) { // check comment history pull := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: apiPull.ID}) err := pull.LoadIssue(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{IssueID: pull.Issue.ID, OldTitle: title, NewTitle: newTitle}) unittest.AssertExistsAndLoadBean(t, &issues_model.ContentHistory{IssueID: pull.Issue.ID, ContentText: newBody, IsFirstCreated: false}) diff --git a/tests/integration/api_push_mirror_test.go b/tests/integration/api_push_mirror_test.go index 9b0497aa3b..f0ef670757 100644 --- a/tests/integration/api_push_mirror_test.go +++ b/tests/integration/api_push_mirror_test.go @@ -23,6 +23,7 @@ import ( repo_service "code.gitea.io/gitea/services/repository" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIPushMirror(t *testing.T) { @@ -35,7 +36,7 @@ func testAPIPushMirror(t *testing.T, u *url.URL) { defer test.MockProtect(&mirror_service.AddPushMirrorRemote)() defer test.MockProtect(&repo_model.DeletePushMirrors)() - assert.NoError(t, migrations.Init()) + require.NoError(t, migrations.Init()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) srcRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) @@ -47,7 +48,7 @@ func testAPIPushMirror(t *testing.T, u *url.URL) { mirrorRepo, err := repo_service.CreateRepositoryDirectly(db.DefaultContext, user, user, repo_service.CreateRepoOptions{ Name: "test-push-mirror", }) - assert.NoError(t, err) + require.NoError(t, err) remoteAddress := fmt.Sprintf("%s%s/%s", u.String(), url.PathEscape(user.Name), url.PathEscape(mirrorRepo.Name)) deletePushMirrors := repo_model.DeletePushMirrors diff --git a/tests/integration/api_releases_test.go b/tests/integration/api_releases_test.go index a5e769e39f..92b4845602 100644 --- a/tests/integration/api_releases_test.go +++ b/tests/integration/api_releases_test.go @@ -23,6 +23,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIListReleases(t *testing.T) { @@ -52,7 +53,7 @@ func TestAPIListReleases(t *testing.T) { assert.True(t, release.IsPrerelease) assert.True(t, strings.HasSuffix(release.UploadURL, "/api/v1/repos/user2/repo1/releases/5/assets"), release.UploadURL) default: - assert.NoError(t, fmt.Errorf("unexpected release: %v", release)) + require.NoError(t, fmt.Errorf("unexpected release: %v", release)) } } } @@ -111,14 +112,14 @@ func TestAPICreateAndUpdateRelease(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() err = gitRepo.CreateTag("v0.0.1", "master") - assert.NoError(t, err) + require.NoError(t, err) target, err := gitRepo.GetTagCommitID("v0.0.1") - assert.NoError(t, err) + require.NoError(t, err) newRelease := createNewReleaseUsingAPI(t, token, owner, repo, "v0.0.1", target, "v0.0.1", "test") @@ -168,11 +169,11 @@ func TestAPICreateProtectedTagRelease(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() commit, err := gitRepo.GetBranchCommit("master") - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithJSON(t, "POST", fmt.Sprintf("/api/v1/repos/%s/%s/releases", repo.OwnerName, repo.Name), &api.CreateReleaseOption{ TagName: "v0.0.1", @@ -204,11 +205,11 @@ func TestAPICreateReleaseToDefaultBranchOnExistingTag(t *testing.T) { token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() err = gitRepo.CreateTag("v0.0.1", "master") - assert.NoError(t, err) + require.NoError(t, err) createNewReleaseUsingAPI(t, token, owner, repo, "v0.0.1", "", "v0.0.1", "test") } @@ -302,11 +303,11 @@ func TestAPIUploadAssetRelease(t *testing.T) { writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("attachment", filename) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(part, bytes.NewReader(buff.Bytes())) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithBody(t, http.MethodPost, assetURL, bytes.NewReader(body.Bytes())). AddTokenAuth(token). @@ -426,11 +427,11 @@ func TestAPIDuplicateAssetRelease(t *testing.T) { writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("attachment", filename) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(part, &buff) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) req := NewRequestWithBody(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/releases/%d/assets?name=test-asset&external_url=https%%3A%%2F%%2Fforgejo.org%%2F", owner.Name, repo.Name, r.ID), body). AddTokenAuth(token) diff --git a/tests/integration/api_repo_archive_test.go b/tests/integration/api_repo_archive_test.go index a4ae599615..a16136a39b 100644 --- a/tests/integration/api_repo_archive_test.go +++ b/tests/integration/api_repo_archive_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIDownloadArchive(t *testing.T) { @@ -31,14 +32,14 @@ func TestAPIDownloadArchive(t *testing.T) { link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master.zip", user2.Name, repo.Name)) resp := MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err := io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, bs, 320) assert.EqualValues(t, "application/zip", resp.Header().Get("Content-Type")) link, _ = url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master.tar.gz", user2.Name, repo.Name)) resp = MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, bs, 266) assert.EqualValues(t, "application/gzip", resp.Header().Get("Content-Type")) @@ -48,14 +49,14 @@ func TestAPIDownloadArchive(t *testing.T) { assert.NotEmpty(t, m[1]) resp = MakeRequest(t, NewRequest(t, "GET", m[1]).AddTokenAuth(token), http.StatusOK) bs2, err := io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) // The locked URL should give the same bytes as the non-locked one assert.EqualValues(t, bs, bs2) link, _ = url.Parse(fmt.Sprintf("/api/v1/repos/%s/%s/archive/master.bundle", user2.Name, repo.Name)) resp = MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, bs, 382) assert.EqualValues(t, "application/octet-stream", resp.Header().Get("Content-Type")) diff --git a/tests/integration/api_repo_avatar_test.go b/tests/integration/api_repo_avatar_test.go index 6677885f7e..8ee256ec9f 100644 --- a/tests/integration/api_repo_avatar_test.go +++ b/tests/integration/api_repo_avatar_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIUpdateRepoAvatar(t *testing.T) { @@ -29,7 +30,7 @@ func TestAPIUpdateRepoAvatar(t *testing.T) { // Test what happens if you use a valid image avatar, err := os.ReadFile("tests/integration/avatar.png") - assert.NoError(t, err) + require.NoError(t, err) if err != nil { assert.FailNow(t, "Unable to open avatar.png") } @@ -53,7 +54,7 @@ func TestAPIUpdateRepoAvatar(t *testing.T) { // Test what happens if you use a file that is not an image text, err := os.ReadFile("tests/integration/README.md") - assert.NoError(t, err) + require.NoError(t, err) if err != nil { assert.FailNow(t, "Unable to open README.md") } diff --git a/tests/integration/api_repo_branch_test.go b/tests/integration/api_repo_branch_test.go index b0ac2286c9..5488eca1dc 100644 --- a/tests/integration/api_repo_branch_test.go +++ b/tests/integration/api_repo_branch_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIRepoBranchesPlain(t *testing.T) { @@ -33,10 +34,10 @@ func TestAPIRepoBranchesPlain(t *testing.T) { link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches", repo3.Name)) // a plain repo resp := MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err := io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) var branches []*api.Branch - assert.NoError(t, json.Unmarshal(bs, &branches)) + require.NoError(t, json.Unmarshal(bs, &branches)) assert.Len(t, branches, 2) assert.EqualValues(t, "test_branch", branches[0].Name) assert.EqualValues(t, "master", branches[1].Name) @@ -44,9 +45,9 @@ func TestAPIRepoBranchesPlain(t *testing.T) { link2, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches/test_branch", repo3.Name)) resp = MakeRequest(t, NewRequest(t, "GET", link2.String()).AddTokenAuth(token), http.StatusOK) bs, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) var branch api.Branch - assert.NoError(t, json.Unmarshal(bs, &branch)) + require.NoError(t, json.Unmarshal(bs, &branch)) assert.EqualValues(t, "test_branch", branch.Name) req := NewRequest(t, "POST", link.String()).AddTokenAuth(token) @@ -54,18 +55,18 @@ func TestAPIRepoBranchesPlain(t *testing.T) { req.Body = io.NopCloser(bytes.NewBufferString(`{"new_branch_name":"test_branch2", "old_branch_name": "test_branch", "old_ref_name":"refs/heads/test_branch"}`)) resp = MakeRequest(t, req, http.StatusCreated) bs, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) var branch2 api.Branch - assert.NoError(t, json.Unmarshal(bs, &branch2)) + require.NoError(t, json.Unmarshal(bs, &branch2)) assert.EqualValues(t, "test_branch2", branch2.Name) assert.EqualValues(t, branch.Commit.ID, branch2.Commit.ID) resp = MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) branches = []*api.Branch{} - assert.NoError(t, json.Unmarshal(bs, &branches)) + require.NoError(t, json.Unmarshal(bs, &branches)) assert.Len(t, branches, 3) assert.EqualValues(t, "test_branch", branches[0].Name) assert.EqualValues(t, "test_branch2", branches[1].Name) @@ -75,7 +76,7 @@ func TestAPIRepoBranchesPlain(t *testing.T) { MakeRequest(t, NewRequest(t, "DELETE", link3.String()), http.StatusNotFound) MakeRequest(t, NewRequest(t, "DELETE", link3.String()).AddTokenAuth(token), http.StatusNoContent) - assert.NoError(t, err) + require.NoError(t, err) }) } @@ -90,10 +91,10 @@ func TestAPIRepoBranchesMirror(t *testing.T) { link, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches", repo5.Name)) // a mirror repo resp := MakeRequest(t, NewRequest(t, "GET", link.String()).AddTokenAuth(token), http.StatusOK) bs, err := io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) var branches []*api.Branch - assert.NoError(t, json.Unmarshal(bs, &branches)) + require.NoError(t, json.Unmarshal(bs, &branches)) assert.Len(t, branches, 2) assert.EqualValues(t, "test_branch", branches[0].Name) assert.EqualValues(t, "master", branches[1].Name) @@ -101,9 +102,9 @@ func TestAPIRepoBranchesMirror(t *testing.T) { link2, _ := url.Parse(fmt.Sprintf("/api/v1/repos/org3/%s/branches/test_branch", repo5.Name)) resp = MakeRequest(t, NewRequest(t, "GET", link2.String()).AddTokenAuth(token), http.StatusOK) bs, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) var branch api.Branch - assert.NoError(t, json.Unmarshal(bs, &branch)) + require.NoError(t, json.Unmarshal(bs, &branch)) assert.EqualValues(t, "test_branch", branch.Name) req := NewRequest(t, "POST", link.String()).AddTokenAuth(token) @@ -111,11 +112,11 @@ func TestAPIRepoBranchesMirror(t *testing.T) { req.Body = io.NopCloser(bytes.NewBufferString(`{"new_branch_name":"test_branch2", "old_branch_name": "test_branch", "old_ref_name":"refs/heads/test_branch"}`)) resp = MakeRequest(t, req, http.StatusForbidden) bs, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "{\"message\":\"Git Repository is a mirror.\",\"url\":\""+setting.AppURL+"api/swagger\"}\n", string(bs)) resp = MakeRequest(t, NewRequest(t, "DELETE", link2.String()).AddTokenAuth(token), http.StatusForbidden) bs, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "{\"message\":\"Git Repository is a mirror.\",\"url\":\""+setting.AppURL+"api/swagger\"}\n", string(bs)) } diff --git a/tests/integration/api_repo_get_contents_list_test.go b/tests/integration/api_repo_get_contents_list_test.go index 1ba74490a3..e76ccd9932 100644 --- a/tests/integration/api_repo_get_contents_list_test.go +++ b/tests/integration/api_repo_get_contents_list_test.go @@ -20,6 +20,7 @@ import ( repo_service "code.gitea.io/gitea/services/repository" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func getExpectedContentsListResponseForContents(ref, refType, lastCommitSHA string) []*api.ContentsResponse { @@ -73,19 +74,19 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) { // Get the commit ID of the default branch gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo1) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() // Make a new branch in repo1 newBranch := "test_branch" err = repo_service.CreateNewBranch(git.DefaultContext, user2, repo1, gitRepo, repo1.DefaultBranch, newBranch) - assert.NoError(t, err) + require.NoError(t, err) commitID, _ := gitRepo.GetBranchCommitID(repo1.DefaultBranch) // Make a new tag in repo1 newTag := "test_tag" err = gitRepo.CreateTag(newTag, commitID) - assert.NoError(t, err) + require.NoError(t, err) /*** END SETUP ***/ // ref is default ref @@ -97,7 +98,7 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) { DecodeJSON(t, resp, &contentsListResponse) assert.NotNil(t, contentsListResponse) lastCommit, err := gitRepo.GetCommitByPath("README.md") - assert.NoError(t, err) + require.NoError(t, err) expectedContentsListResponse := getExpectedContentsListResponseForContents(ref, refType, lastCommit.ID.String()) assert.EqualValues(t, expectedContentsListResponse, contentsListResponse) @@ -119,9 +120,9 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) { DecodeJSON(t, resp, &contentsListResponse) assert.NotNil(t, contentsListResponse) branchCommit, err := gitRepo.GetBranchCommit(ref) - assert.NoError(t, err) + require.NoError(t, err) lastCommit, err = branchCommit.GetCommitByPath("README.md") - assert.NoError(t, err) + require.NoError(t, err) expectedContentsListResponse = getExpectedContentsListResponseForContents(ref, refType, lastCommit.ID.String()) assert.EqualValues(t, expectedContentsListResponse, contentsListResponse) @@ -133,9 +134,9 @@ func testAPIGetContentsList(t *testing.T, u *url.URL) { DecodeJSON(t, resp, &contentsListResponse) assert.NotNil(t, contentsListResponse) tagCommit, err := gitRepo.GetTagCommit(ref) - assert.NoError(t, err) + require.NoError(t, err) lastCommit, err = tagCommit.GetCommitByPath("README.md") - assert.NoError(t, err) + require.NoError(t, err) expectedContentsListResponse = getExpectedContentsListResponseForContents(ref, refType, lastCommit.ID.String()) assert.EqualValues(t, expectedContentsListResponse, contentsListResponse) diff --git a/tests/integration/api_repo_get_contents_test.go b/tests/integration/api_repo_get_contents_test.go index 68a8608117..cb321b8b1f 100644 --- a/tests/integration/api_repo_get_contents_test.go +++ b/tests/integration/api_repo_get_contents_test.go @@ -20,6 +20,7 @@ import ( repo_service "code.gitea.io/gitea/services/repository" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func getExpectedContentsResponseForContents(ref, refType, lastCommitSHA string) *api.ContentsResponse { @@ -75,20 +76,20 @@ func testAPIGetContents(t *testing.T, u *url.URL) { // Get the commit ID of the default branch gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo1) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() // Make a new branch in repo1 newBranch := "test_branch" err = repo_service.CreateNewBranch(git.DefaultContext, user2, repo1, gitRepo, repo1.DefaultBranch, newBranch) - assert.NoError(t, err) + require.NoError(t, err) commitID, err := gitRepo.GetBranchCommitID(repo1.DefaultBranch) - assert.NoError(t, err) + require.NoError(t, err) // Make a new tag in repo1 newTag := "test_tag" err = gitRepo.CreateTag(newTag, commitID) - assert.NoError(t, err) + require.NoError(t, err) /*** END SETUP ***/ // ref is default ref @@ -179,17 +180,17 @@ func TestAPIGetContentsRefFormats(t *testing.T) { resp := MakeRequest(t, NewRequest(t, http.MethodGet, noRef), http.StatusOK) raw, err := io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, content, string(raw)) resp = MakeRequest(t, NewRequest(t, http.MethodGet, refInPath), http.StatusOK) raw, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, content, string(raw)) resp = MakeRequest(t, NewRequest(t, http.MethodGet, refInQuery), http.StatusOK) raw, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, content, string(raw)) }) } diff --git a/tests/integration/api_repo_git_commits_test.go b/tests/integration/api_repo_git_commits_test.go index 3655206207..c4c626eb49 100644 --- a/tests/integration/api_repo_git_commits_test.go +++ b/tests/integration/api_repo_git_commits_test.go @@ -77,7 +77,7 @@ func TestAPIReposGitCommitList(t *testing.T) { assert.EqualValues(t, "c8e31bc7688741a5287fcde4fbb8fc129ca07027", apiData[1].CommitMeta.SHA) compareCommitFiles(t, []string{"test.csv"}, apiData[1].Files) - assert.EqualValues(t, resp.Header().Get("X-Total"), "2") + assert.EqualValues(t, "2", resp.Header().Get("X-Total")) } func TestAPIReposGitCommitListNotMaster(t *testing.T) { @@ -103,7 +103,7 @@ func TestAPIReposGitCommitListNotMaster(t *testing.T) { assert.EqualValues(t, "5099b81332712fe655e34e8dd63574f503f61811", apiData[2].CommitMeta.SHA) compareCommitFiles(t, []string{"readme.md"}, apiData[2].Files) - assert.EqualValues(t, resp.Header().Get("X-Total"), "3") + assert.EqualValues(t, "3", resp.Header().Get("X-Total")) } func TestAPIReposGitCommitListPage2Empty(t *testing.T) { @@ -121,7 +121,7 @@ func TestAPIReposGitCommitListPage2Empty(t *testing.T) { var apiData []api.Commit DecodeJSON(t, resp, &apiData) - assert.Len(t, apiData, 0) + assert.Empty(t, apiData) } func TestAPIReposGitCommitListDifferentBranch(t *testing.T) { @@ -208,7 +208,7 @@ func TestGetFileHistory(t *testing.T) { assert.Equal(t, "f27c2b2b03dcab38beaf89b0ab4ff61f6de63441", apiData[0].CommitMeta.SHA) compareCommitFiles(t, []string{"readme.md"}, apiData[0].Files) - assert.EqualValues(t, resp.Header().Get("X-Total"), "1") + assert.EqualValues(t, "1", resp.Header().Get("X-Total")) } func TestGetFileHistoryNotOnMaster(t *testing.T) { @@ -229,5 +229,5 @@ func TestGetFileHistoryNotOnMaster(t *testing.T) { assert.Equal(t, "c8e31bc7688741a5287fcde4fbb8fc129ca07027", apiData[0].CommitMeta.SHA) compareCommitFiles(t, []string{"test.csv"}, apiData[0].Files) - assert.EqualValues(t, resp.Header().Get("X-Total"), "1") + assert.EqualValues(t, "1", resp.Header().Get("X-Total")) } diff --git a/tests/integration/api_repo_lfs_locks_test.go b/tests/integration/api_repo_lfs_locks_test.go index 427e0b9fb1..4ba01e6d9b 100644 --- a/tests/integration/api_repo_lfs_locks_test.go +++ b/tests/integration/api_repo_lfs_locks_test.go @@ -176,6 +176,6 @@ func TestAPILFSLocksLogged(t *testing.T) { resp := session.MakeRequest(t, req, http.StatusOK) var lfsLocks api.LFSLockList DecodeJSON(t, resp, &lfsLocks) - assert.Len(t, lfsLocks.Locks, 0) + assert.Empty(t, lfsLocks.Locks) } } diff --git a/tests/integration/api_repo_lfs_migrate_test.go b/tests/integration/api_repo_lfs_migrate_test.go index 8b4d79db02..de85b9160d 100644 --- a/tests/integration/api_repo_lfs_migrate_test.go +++ b/tests/integration/api_repo_lfs_migrate_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIRepoLFSMigrateLocal(t *testing.T) { @@ -27,7 +28,7 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) { oldAllowLocalNetworks := setting.Migrations.AllowLocalNetworks setting.ImportLocalPaths = true setting.Migrations.AllowLocalNetworks = true - assert.NoError(t, migrations.Init()) + require.NoError(t, migrations.Init()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) session := loginUser(t, user.Name) @@ -50,5 +51,5 @@ func TestAPIRepoLFSMigrateLocal(t *testing.T) { setting.ImportLocalPaths = oldImportLocalPaths setting.Migrations.AllowLocalNetworks = oldAllowLocalNetworks - assert.NoError(t, migrations.Init()) // reset old migration settings + require.NoError(t, migrations.Init()) // reset old migration settings } diff --git a/tests/integration/api_repo_lfs_test.go b/tests/integration/api_repo_lfs_test.go index cea185a3d5..7a2a92d415 100644 --- a/tests/integration/api_repo_lfs_test.go +++ b/tests/integration/api_repo_lfs_test.go @@ -24,6 +24,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPILFSNotStarted(t *testing.T) { @@ -65,7 +66,7 @@ func createLFSTestRepository(t *testing.T, name string) *repo_model.Repository { t.Run("CreateRepo", doAPICreateRepository(ctx, false, git.Sha1ObjectFormat)) // FIXME: use forEachObjectFormat repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "lfs-"+name+"-repo") - assert.NoError(t, err) + require.NoError(t, err) return repo } @@ -91,7 +92,7 @@ func TestAPILFSBatch(t *testing.T) { decodeResponse := func(t *testing.T, b *bytes.Buffer) *lfs.BatchResponse { var br lfs.BatchResponse - assert.NoError(t, json.Unmarshal(b.Bytes(), &br)) + require.NoError(t, json.Unmarshal(b.Bytes(), &br)) return &br } @@ -184,10 +185,10 @@ func TestAPILFSBatch(t *testing.T) { contentStore := lfs.NewContentStore() exist, err := contentStore.Exists(p) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exist) err = contentStore.Put(p, bytes.NewReader([]byte("dummy0"))) - assert.NoError(t, err) + require.NoError(t, err) req := newRequest(t, &lfs.BatchRequest{ Operation: "download", @@ -255,7 +256,7 @@ func TestAPILFSBatch(t *testing.T) { contentStore := lfs.NewContentStore() exist, err := contentStore.Exists(p) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exist) repo2 := createLFSTestRepository(t, "batch2") @@ -278,12 +279,12 @@ func TestAPILFSBatch(t *testing.T) { assert.Empty(t, br.Objects[0].Actions) meta, err = git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, meta) // Cleanup err = contentStore.Delete(p.RelativePath()) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("AlreadyExists", func(t *testing.T) { @@ -361,10 +362,10 @@ func TestAPILFSUpload(t *testing.T) { contentStore := lfs.NewContentStore() exist, err := contentStore.Exists(p) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exist) err = contentStore.Put(p, bytes.NewReader([]byte("dummy5"))) - assert.NoError(t, err) + require.NoError(t, err) meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) assert.Nil(t, meta) @@ -380,13 +381,13 @@ func TestAPILFSUpload(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) meta, err = git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, meta) }) // Cleanup err = contentStore.Delete(p.RelativePath()) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("MetaAlreadyExists", func(t *testing.T) { @@ -424,11 +425,11 @@ func TestAPILFSUpload(t *testing.T) { contentStore := lfs.NewContentStore() exist, err := contentStore.Exists(p) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exist) meta, err := git_model.GetLFSMetaObjectByOid(db.DefaultContext, repo.ID, p.Oid) - assert.NoError(t, err) + require.NoError(t, err) assert.NotNil(t, meta) }) } diff --git a/tests/integration/api_repo_test.go b/tests/integration/api_repo_test.go index fe5e43eb2f..b635b7099e 100644 --- a/tests/integration/api_repo_test.go +++ b/tests/integration/api_repo_test.go @@ -23,6 +23,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIUserReposNotLogin(t *testing.T) { @@ -225,7 +226,7 @@ func TestAPISearchRepo(t *testing.T) { for _, repo := range body.Data { r := getRepo(t, repo.ID) hasAccess, err := access_model.HasAccess(db.DefaultContext, userID, r) - assert.NoError(t, err, "Error when checking if User: %d has access to %s: %v", userID, repo.FullName, err) + require.NoError(t, err, "Error when checking if User: %d has access to %s: %v", userID, repo.FullName, err) assert.True(t, hasAccess, "User: %d does not have access to %s", userID, repo.FullName) assert.NotEmpty(t, repo.Name) @@ -431,7 +432,7 @@ func testAPIRepoMigrateConflict(t *testing.T, u *url.URL) { t.Run("CreateRepo", doAPICreateRepository(httpContext, false, git.Sha1ObjectFormat)) // FIXME: use forEachObjectFormat user, err := user_model.GetUserByName(db.DefaultContext, httpContext.Username) - assert.NoError(t, err) + require.NoError(t, err) userID := user.ID cloneURL := "https://github.com/go-gitea/test_repo.git" diff --git a/tests/integration/api_repo_topic_test.go b/tests/integration/api_repo_topic_test.go index 528bd66eb2..dcb8ae09da 100644 --- a/tests/integration/api_repo_topic_test.go +++ b/tests/integration/api_repo_topic_test.go @@ -46,7 +46,7 @@ func TestAPITopicSearchPaging(t *testing.T) { res = MakeRequest(t, NewRequest(t, "GET", "/api/v1/topics/search?page=2"), http.StatusOK) DecodeJSON(t, res, &topics) - assert.Greater(t, len(topics.TopicNames), 0) + assert.NotEmpty(t, topics.TopicNames) } func TestAPITopicSearch(t *testing.T) { diff --git a/tests/integration/api_team_test.go b/tests/integration/api_team_test.go index 4df545284e..4fee39d687 100644 --- a/tests/integration/api_team_test.go +++ b/tests/integration/api_team_test.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPITeam(t *testing.T) { @@ -119,7 +120,7 @@ func TestAPITeam(t *testing.T) { // Read team. teamRead := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, teamRead.LoadUnits(db.DefaultContext)) + require.NoError(t, teamRead.LoadUnits(db.DefaultContext)) req = NewRequestf(t, "GET", "/api/v1/teams/%d", teamID). AddTokenAuth(token) resp = MakeRequest(t, req, http.StatusOK) @@ -195,7 +196,7 @@ func TestAPITeam(t *testing.T) { resp = MakeRequest(t, req, http.StatusOK) apiTeam = api.Team{} DecodeJSON(t, resp, &apiTeam) - assert.NoError(t, teamRead.LoadUnits(db.DefaultContext)) + require.NoError(t, teamRead.LoadUnits(db.DefaultContext)) checkTeamResponse(t, "ReadTeam2", &apiTeam, teamRead.Name, *teamToEditDesc.Description, teamRead.IncludesAllRepositories, teamRead.AccessMode.String(), teamRead.GetUnitNames(), teamRead.GetUnitsMap()) @@ -257,9 +258,9 @@ func checkTeamResponse(t *testing.T, testName string, apiTeam *api.Team, name, d func checkTeamBean(t *testing.T, id int64, name, description string, includesAllRepositories bool, permission string, units []string, unitsMap map[string]string) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: id}) - assert.NoError(t, team.LoadUnits(db.DefaultContext), "LoadUnits") + require.NoError(t, team.LoadUnits(db.DefaultContext), "LoadUnits") apiTeam, err := convert.ToTeam(db.DefaultContext, team) - assert.NoError(t, err) + require.NoError(t, err) checkTeamResponse(t, fmt.Sprintf("checkTeamBean/%s_%s", name, description), apiTeam, name, description, includesAllRepositories, permission, units, unitsMap) } diff --git a/tests/integration/api_twofa_test.go b/tests/integration/api_twofa_test.go index 3860eedde8..0bb20255a2 100644 --- a/tests/integration/api_twofa_test.go +++ b/tests/integration/api_twofa_test.go @@ -15,7 +15,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/pquerna/otp/totp" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPITwoFactor(t *testing.T) { @@ -32,21 +32,21 @@ func TestAPITwoFactor(t *testing.T) { Issuer: "gitea-test", AccountName: user.Name, }) - assert.NoError(t, err) + require.NoError(t, err) tfa := &auth_model.TwoFactor{ UID: user.ID, } - assert.NoError(t, tfa.SetSecret(otpKey.Secret())) + require.NoError(t, tfa.SetSecret(otpKey.Secret())) - assert.NoError(t, auth_model.NewTwoFactor(db.DefaultContext, tfa)) + require.NoError(t, auth_model.NewTwoFactor(db.DefaultContext, tfa)) req = NewRequest(t, "GET", "/api/v1/user"). AddBasicAuth(user.Name) MakeRequest(t, req, http.StatusUnauthorized) passcode, err := totp.GenerateCode(otpKey.Secret(), time.Now()) - assert.NoError(t, err) + require.NoError(t, err) req = NewRequest(t, "GET", "/api/v1/user"). AddBasicAuth(user.Name) diff --git a/tests/integration/api_user_avatar_test.go b/tests/integration/api_user_avatar_test.go index 5b4546f150..22dc09a6b7 100644 --- a/tests/integration/api_user_avatar_test.go +++ b/tests/integration/api_user_avatar_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIUpdateUserAvatar(t *testing.T) { @@ -25,7 +26,7 @@ func TestAPIUpdateUserAvatar(t *testing.T) { // Test what happens if you use a valid image avatar, err := os.ReadFile("tests/integration/avatar.png") - assert.NoError(t, err) + require.NoError(t, err) if err != nil { assert.FailNow(t, "Unable to open avatar.png") } @@ -49,7 +50,7 @@ func TestAPIUpdateUserAvatar(t *testing.T) { // Test what happens if you use a file that is not an image text, err := os.ReadFile("tests/integration/README.md") - assert.NoError(t, err) + require.NoError(t, err) if err != nil { assert.FailNow(t, "Unable to open README.md") } diff --git a/tests/integration/api_user_orgs_test.go b/tests/integration/api_user_orgs_test.go index b6b4b6f2b2..e31199406d 100644 --- a/tests/integration/api_user_orgs_test.go +++ b/tests/integration/api_user_orgs_test.go @@ -63,7 +63,7 @@ func TestUserOrgs(t *testing.T) { // unrelated user should not get private org membership of privateMemberUsername orgs = getUserOrgs(t, unrelatedUsername, privateMemberUsername) - assert.Len(t, orgs, 0) + assert.Empty(t, orgs) // not authenticated call should not be allowed testUserOrgsUnauthenticated(t, privateMemberUsername) diff --git a/tests/integration/api_user_search_test.go b/tests/integration/api_user_search_test.go index 0e01b504cc..2ecd338987 100644 --- a/tests/integration/api_user_search_test.go +++ b/tests/integration/api_user_search_test.go @@ -91,7 +91,7 @@ func TestAPIUserSearchSystemUsers(t *testing.T) { var results SearchResults DecodeJSON(t, resp, &results) assert.NotEmpty(t, results.Data) - if assert.EqualValues(t, 1, len(results.Data)) { + if assert.Len(t, results.Data, 1) { user := results.Data[0] assert.EqualValues(t, user.UserName, systemUser.Name) assert.EqualValues(t, user.ID, systemUser.ID) diff --git a/tests/integration/api_wiki_test.go b/tests/integration/api_wiki_test.go index 400cf068b4..5a033edb10 100644 --- a/tests/integration/api_wiki_test.go +++ b/tests/integration/api_wiki_test.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIRenameWikiBranch(t *testing.T) { @@ -282,7 +283,7 @@ func TestAPIEditOtherWikiPage(t *testing.T) { DefaultPermissions: repo_model.UnitAccessModeWrite, }) err := repo_service.UpdateRepositoryUnits(ctx, repo, units, nil) - assert.NoError(t, err) + require.NoError(t, err) // Creating a new Wiki page on user2's repo works now testCreateWiki(http.StatusCreated) diff --git a/tests/integration/attachment_test.go b/tests/integration/attachment_test.go index 8206d8f4dc..95c9c9f753 100644 --- a/tests/integration/attachment_test.go +++ b/tests/integration/attachment_test.go @@ -19,6 +19,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func generateImg() bytes.Buffer { @@ -35,11 +36,11 @@ func createAttachment(t *testing.T, session *TestSession, repoURL, filename stri // Setup multi-part writer := multipart.NewWriter(body) part, err := writer.CreateFormFile("file", filename) - assert.NoError(t, err) + require.NoError(t, err) _, err = io.Copy(part, &buff) - assert.NoError(t, err) + require.NoError(t, err) err = writer.Close() - assert.NoError(t, err) + require.NoError(t, err) csrf := GetCSRF(t, session, repoURL) @@ -126,7 +127,7 @@ func TestGetAttachment(t *testing.T) { // Write empty file to be available for response if tc.createFile { _, err := storage.Attachments.Save(repo_model.AttachmentRelativePath(tc.uuid), strings.NewReader("hello world"), -1) - assert.NoError(t, err) + require.NoError(t, err) } // Actual test req := NewRequest(t, "GET", "/attachments/"+tc.uuid) diff --git a/tests/integration/auth_ldap_test.go b/tests/integration/auth_ldap_test.go index f0492015b8..04c8a4b614 100644 --- a/tests/integration/auth_ldap_test.go +++ b/tests/integration/auth_ldap_test.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type ldapUser struct { @@ -245,12 +246,12 @@ func TestLDAPUserSync(t *testing.T) { defer tests.PrepareTestEnv(t)() addAuthSourceLDAP(t, "", "", "", "") err := auth.SyncExternalUsers(context.Background(), true) - assert.NoError(t, err) + require.NoError(t, err) // Check if users exists for _, gitLDAPUser := range gitLDAPUsers { dbUser, err := user_model.GetUserByName(db.DefaultContext, gitLDAPUser.UserName) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, gitLDAPUser.UserName, dbUser.Name) assert.Equal(t, gitLDAPUser.Email, dbUser.Email) assert.Equal(t, gitLDAPUser.IsAdmin, dbUser.IsAdmin) @@ -285,7 +286,7 @@ func TestLDAPUserSyncWithEmptyUsernameAttribute(t *testing.T) { htmlDoc := NewHTMLParser(t, resp.Body) tr := htmlDoc.doc.Find("table.table tbody tr") - assert.True(t, tr.Length() == 0) + assert.Equal(t, 0, tr.Length()) } for _, u := range gitLDAPUsers { @@ -427,9 +428,9 @@ func TestLDAPGroupTeamSyncAddMember(t *testing.T) { defer tests.PrepareTestEnv(t)() addAuthSourceLDAP(t, "", "", "", "", "on", `{"cn=ship_crew,ou=people,dc=planetexpress,dc=com":{"org26": ["team11"]},"cn=admin_staff,ou=people,dc=planetexpress,dc=com": {"non-existent": ["non-existent"]}}`) org, err := organization.GetOrgByName(db.DefaultContext, "org26") - assert.NoError(t, err) + require.NoError(t, err) team, err := organization.GetTeam(db.DefaultContext, org.ID, "team11") - assert.NoError(t, err) + require.NoError(t, err) auth.SyncExternalUsers(context.Background(), true) for _, gitLDAPUser := range gitLDAPUsers { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ @@ -439,25 +440,25 @@ func TestLDAPGroupTeamSyncAddMember(t *testing.T) { UserID: user.ID, IncludePrivate: true, }) - assert.NoError(t, err) + require.NoError(t, err) allOrgTeams, err := organization.GetUserOrgTeams(db.DefaultContext, org.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) if user.Name == "fry" || user.Name == "leela" || user.Name == "bender" { // assert members of LDAP group "cn=ship_crew" are added to mapped teams assert.Len(t, usersOrgs, 1, "User [%s] should be member of one organization", user.Name) assert.Equal(t, "org26", usersOrgs[0].Name, "Membership should be added to the right organization") isMember, err := organization.IsTeamMember(db.DefaultContext, usersOrgs[0].ID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isMember, "Membership should be added to the right team") err = models.RemoveTeamMember(db.DefaultContext, team, user.ID) - assert.NoError(t, err) + require.NoError(t, err) err = models.RemoveOrgUser(db.DefaultContext, usersOrgs[0].ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) } else { // assert members of LDAP group "cn=admin_staff" keep initial team membership since mapped team does not exist assert.Empty(t, usersOrgs, "User should be member of no organization") isMember, err := organization.IsTeamMember(db.DefaultContext, org.ID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isMember, "User should no be added to this team") assert.Empty(t, allOrgTeams, "User should not be added to any team") } @@ -472,30 +473,30 @@ func TestLDAPGroupTeamSyncRemoveMember(t *testing.T) { defer tests.PrepareTestEnv(t)() addAuthSourceLDAP(t, "", "", "", "", "on", `{"cn=dispatch,ou=people,dc=planetexpress,dc=com": {"org26": ["team11"]}}`) org, err := organization.GetOrgByName(db.DefaultContext, "org26") - assert.NoError(t, err) + require.NoError(t, err) team, err := organization.GetTeam(db.DefaultContext, org.ID, "team11") - assert.NoError(t, err) + require.NoError(t, err) loginUserWithPassword(t, gitLDAPUsers[0].UserName, gitLDAPUsers[0].Password) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ Name: gitLDAPUsers[0].UserName, }) err = organization.AddOrgUser(db.DefaultContext, org.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) err = models.AddTeamMember(db.DefaultContext, team, user.ID) - assert.NoError(t, err) + require.NoError(t, err) isMember, err := organization.IsOrganizationMember(db.DefaultContext, org.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isMember, "User should be member of this organization") isMember, err = organization.IsTeamMember(db.DefaultContext, org.ID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isMember, "User should be member of this team") // assert team member "professor" gets removed from org26 team11 loginUserWithPassword(t, gitLDAPUsers[0].UserName, gitLDAPUsers[0].Password) isMember, err = organization.IsOrganizationMember(db.DefaultContext, org.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isMember, "User membership should have been removed from organization") isMember, err = organization.IsTeamMember(db.DefaultContext, org.ID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isMember, "User membership should have been removed from team") } @@ -524,7 +525,7 @@ func TestLDAPUserSyncInvalidMail(t *testing.T) { // Check if users exists for _, gitLDAPUser := range gitLDAPUsers { dbUser, err := user_model.GetUserByName(db.DefaultContext, gitLDAPUser.UserName) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, gitLDAPUser.UserName, dbUser.Name) assert.Equal(t, gitLDAPUser.UserName+"@localhost.local", dbUser.Email) assert.Equal(t, gitLDAPUser.IsAdmin, dbUser.IsAdmin) @@ -550,7 +551,7 @@ func TestLDAPUserSyncInvalidMailDefaultDomain(t *testing.T) { // Check if users exists for _, gitLDAPUser := range gitLDAPUsers { dbUser, err := user_model.GetUserByName(db.DefaultContext, gitLDAPUser.UserName) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, gitLDAPUser.UserName, dbUser.Name) assert.Equal(t, gitLDAPUser.UserName+"@test.org", dbUser.Email) assert.Equal(t, gitLDAPUser.IsAdmin, dbUser.IsAdmin) diff --git a/tests/integration/auth_token_test.go b/tests/integration/auth_token_test.go index 24c66ee261..2c39c87da2 100644 --- a/tests/integration/auth_token_test.go +++ b/tests/integration/auth_token_test.go @@ -19,6 +19,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // GetSessionForLTACookie returns a new session with only the LTA cookie being set. @@ -31,7 +32,7 @@ func GetSessionForLTACookie(t *testing.T, ltaCookie *http.Cookie) *TestSession { session := emptyTestSession(t) baseURL, err := url.Parse(setting.AppURL) - assert.NoError(t, err) + require.NoError(t, err) session.jar.SetCookies(baseURL, cr.Cookies()) return session @@ -45,7 +46,7 @@ func GetLTACookieValue(t *testing.T, sess *TestSession) string { assert.NotNil(t, rememberCookie) cookieValue, err := url.QueryUnescape(rememberCookie.Value) - assert.NoError(t, err) + require.NoError(t, err) return cookieValue } @@ -82,7 +83,7 @@ func TestLTACookie(t *testing.T) { lookupKey, validator, found := strings.Cut(ltaCookieValue, ":") assert.True(t, found) rawValidator, err := hex.DecodeString(validator) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertExistsAndLoadBean(t, &auth.AuthorizationToken{LookupKey: lookupKey, HashedValidator: auth.HashValidator(rawValidator), UID: user.ID}) // Check if the LTA cookie it provides authentication. @@ -147,7 +148,7 @@ func TestLTAExpiry(t *testing.T) { // Manually stub LTA's expiry. _, err := db.GetEngine(db.DefaultContext).ID(lta.ID).Table("forgejo_auth_token").Cols("expiry").Update(&auth.AuthorizationToken{Expiry: timeutil.TimeStampNow()}) - assert.NoError(t, err) + require.NoError(t, err) // Ensure it's expired. lta = unittest.AssertExistsAndLoadBean(t, &auth.AuthorizationToken{UID: user.ID, LookupKey: lookupKey}) diff --git a/tests/integration/block_test.go b/tests/integration/block_test.go index f917d700da..7105472a09 100644 --- a/tests/integration/block_test.go +++ b/tests/integration/block_test.go @@ -257,7 +257,7 @@ func TestBlockActions(t *testing.T) { var respBody reactionResponse DecodeJSON(t, resp, &respBody) - assert.EqualValues(t, true, respBody.Empty) + assert.True(t, respBody.Empty) }) t.Run("On a comment", func(t *testing.T) { @@ -276,7 +276,7 @@ func TestBlockActions(t *testing.T) { var respBody reactionResponse DecodeJSON(t, resp, &respBody) - assert.EqualValues(t, true, respBody.Empty) + assert.True(t, respBody.Empty) }) }) diff --git a/tests/integration/cmd_admin_test.go b/tests/integration/cmd_admin_test.go index 6a85460450..576b09eefd 100644 --- a/tests/integration/cmd_admin_test.go +++ b/tests/integration/cmd_admin_test.go @@ -12,6 +12,7 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_Cmd_AdminUser(t *testing.T) { @@ -48,7 +49,7 @@ func Test_Cmd_AdminUser(t *testing.T) { options := []string{"user", "create", "--username", name, "--password", "password", "--email", name + "@example.com"} options = append(options, testCase.options...) output, err := runMainApp("admin", options...) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, output, "has been successfully created") user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: name}) assert.Equal(t, testCase.mustChangePassword, user.MustChangePassword) @@ -56,13 +57,13 @@ func Test_Cmd_AdminUser(t *testing.T) { options = []string{"user", "change-password", "--username", name, "--password", "password"} options = append(options, testCase.options...) output, err = runMainApp("admin", options...) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, output, "has been successfully updated") user = unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: name}) assert.Equal(t, testCase.mustChangePassword, user.MustChangePassword) _, err = runMainApp("admin", "user", "delete", "--username", name) - assert.NoError(t, err) + require.NoError(t, err) unittest.AssertNotExistsBean(t, &user_model.User{Name: name}) }) } @@ -135,7 +136,7 @@ func Test_Cmd_AdminFirstUser(t *testing.T) { options := []string{"user", "create", "--username", name, "--password", "password", "--email", name + "@example.com"} options = append(options, testCase.options...) output, err := runMainApp("admin", options...) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, output, "has been successfully created") user := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: name}) assert.Equal(t, testCase.mustChangePassword, user.MustChangePassword) diff --git a/tests/integration/cmd_forgejo_actions_test.go b/tests/integration/cmd_forgejo_actions_test.go index e45526ac7a..067cdefb88 100644 --- a/tests/integration/cmd_forgejo_actions_test.go +++ b/tests/integration/cmd_forgejo_actions_test.go @@ -4,7 +4,6 @@ package integration import ( gocontext "context" - "errors" "io" "net/url" "os" @@ -18,21 +17,22 @@ import ( user_model "code.gitea.io/gitea/models/user" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_CmdForgejo_Actions(t *testing.T) { onGiteaRun(t, func(*testing.T, *url.URL) { token, err := runMainApp("forgejo-cli", "actions", "generate-runner-token") - assert.NoError(t, err) - assert.EqualValues(t, 40, len(token)) + require.NoError(t, err) + assert.Len(t, token, 40) secret, err := runMainApp("forgejo-cli", "actions", "generate-secret") - assert.NoError(t, err) - assert.EqualValues(t, 40, len(secret)) + require.NoError(t, err) + assert.Len(t, secret, 40) _, err = runMainApp("forgejo-cli", "actions", "register") var exitErr *exec.ExitError - assert.True(t, errors.As(err, &exitErr)) + require.ErrorAs(t, err, &exitErr) assert.Contains(t, string(exitErr.Stderr), "at least one of the --secret") for _, testCase := range []struct { @@ -71,7 +71,7 @@ func Test_CmdForgejo_Actions(t *testing.T) { assert.EqualValues(t, "", output) var exitErr *exec.ExitError - assert.True(t, errors.As(err, &exitErr)) + require.ErrorAs(t, err, &exitErr) assert.Contains(t, string(exitErr.Stderr), testCase.errorMessage) }) } @@ -101,14 +101,14 @@ func Test_CmdForgejo_Actions(t *testing.T) { testName: "secret from file", secretOption: func() string { secretFile := t.TempDir() + "/secret" - assert.NoError(t, os.WriteFile(secretFile, []byte(secret), 0o644)) + require.NoError(t, os.WriteFile(secretFile, []byte(secret), 0o644)) return "--secret-file=" + secretFile }, }, } { t.Run(testCase.testName, func(t *testing.T) { uuid, err := runMainAppWithStdin(testCase.stdin, "forgejo-cli", "actions", "register", testCase.secretOption(), "--scope=org26") - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, expecteduuid, uuid) }) } @@ -184,11 +184,11 @@ func Test_CmdForgejo_Actions(t *testing.T) { // for i := 0; i < 2; i++ { uuid, err := runMainApp("forgejo-cli", cmd...) - assert.NoError(t, err) + require.NoError(t, err) if assert.EqualValues(t, testCase.uuid, uuid) { ownerName, repoName, found := strings.Cut(testCase.scope, "/") action, err := actions_model.GetRunnerByUUID(gocontext.Background(), uuid) - assert.NoError(t, err) + require.NoError(t, err) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: action.OwnerID}) assert.Equal(t, ownerName, user.Name, action.OwnerID) diff --git a/tests/integration/cmd_forgejo_f3_test.go b/tests/integration/cmd_forgejo_f3_test.go index 1cbf6cc1df..9156405220 100644 --- a/tests/integration/cmd_forgejo_f3_test.go +++ b/tests/integration/cmd_forgejo_f3_test.go @@ -24,7 +24,6 @@ import ( f3_generic "code.forgejo.org/f3/gof3/v3/tree/generic" f3_tests "code.forgejo.org/f3/gof3/v3/tree/tests/f3" f3_tests_forge "code.forgejo.org/f3/gof3/v3/tree/tests/f3/forge" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/urfave/cli/v2" ) @@ -129,7 +128,7 @@ func TestF3_CmdMirror_LocalForgejo(t *testing.T) { "--to-type", options.Name, "--to-path", toPath, ) - assert.NoError(t, err) + require.NoError(t, err) log.Trace("======= assert") require.Contains(t, output, fmt.Sprintf("mirror %s", fromPath)) projects.List(ctx) diff --git a/tests/integration/cmd_keys_test.go b/tests/integration/cmd_keys_test.go index a3220c13ce..e93a8b5b57 100644 --- a/tests/integration/cmd_keys_test.go +++ b/tests/integration/cmd_keys_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/modules/util" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_CmdKeys(t *testing.T) { @@ -42,9 +43,9 @@ func Test_CmdKeys(t *testing.T) { t.Log(string(exitErr.Stderr)) } if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } assert.Equal(t, tt.expectedOutput, out) }) diff --git a/tests/integration/codeowner_test.go b/tests/integration/codeowner_test.go index 76b292e3cb..7bb6cc9dcf 100644 --- a/tests/integration/codeowner_test.go +++ b/tests/integration/codeowner_test.go @@ -22,7 +22,7 @@ import ( files_service "code.gitea.io/gitea/services/repository/files" "code.gitea.io/gitea/tests" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCodeOwner(t *testing.T) { @@ -46,16 +46,16 @@ func TestCodeOwner(t *testing.T) { r := fmt.Sprintf("%suser2/%s.git", u.String(), repo.Name) cloneURL, _ := url.Parse(r) cloneURL.User = url.UserPassword("user2", userPassword) - assert.NoError(t, git.CloneWithArgs(context.Background(), nil, cloneURL.String(), dstPath, git.CloneRepoOptions{})) + require.NoError(t, git.CloneWithArgs(context.Background(), nil, cloneURL.String(), dstPath, git.CloneRepoOptions{})) t.Run("Normal", func(t *testing.T) { defer tests.PrintCurrentTest(t)() err := os.WriteFile(path.Join(dstPath, "README.md"), []byte("## test content"), 0o666) - assert.NoError(t, err) + require.NoError(t, err) err = git.AddChanges(dstPath, true) - assert.NoError(t, err) + require.NoError(t, err) err = git.CommitChanges(dstPath, git.CommitChangesOptions{ Committer: &git.Signature{ @@ -70,10 +70,10 @@ func TestCodeOwner(t *testing.T) { }, Message: "Add README.", }) - assert.NoError(t, err) + require.NoError(t, err) err = git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/main", "-o", "topic=codeowner-normal").Run(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{BaseRepoID: repo.ID, HeadBranch: "user2/codeowner-normal"}) unittest.AssertExistsIf(t, true, &issues_model.Review{IssueID: pr.IssueID, Type: issues_model.ReviewTypeRequest, ReviewerID: 5}) @@ -93,7 +93,7 @@ func TestCodeOwner(t *testing.T) { doGitAddRemote(dstPath, "forked", remoteURL)(t) err := git.NewCommand(git.DefaultContext, "push", "forked", "HEAD:refs/for/main", "-o", "topic=codeowner-forked").Run(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{BaseRepoID: repo.ID, HeadBranch: "user2/codeowner-forked"}) unittest.AssertExistsIf(t, false, &issues_model.Review{IssueID: pr.IssueID, Type: issues_model.ReviewTypeRequest, ReviewerID: 5}) @@ -103,16 +103,16 @@ func TestCodeOwner(t *testing.T) { defer tests.PrintCurrentTest(t)() // Push the changes made from the previous subtest. - assert.NoError(t, git.NewCommand(git.DefaultContext, "push", "origin").Run(&git.RunOpts{Dir: dstPath})) + require.NoError(t, git.NewCommand(git.DefaultContext, "push", "origin").Run(&git.RunOpts{Dir: dstPath})) // Reset the tree to the previous commit. - assert.NoError(t, git.NewCommand(git.DefaultContext, "reset", "--hard", "HEAD~1").Run(&git.RunOpts{Dir: dstPath})) + require.NoError(t, git.NewCommand(git.DefaultContext, "reset", "--hard", "HEAD~1").Run(&git.RunOpts{Dir: dstPath})) err := os.WriteFile(path.Join(dstPath, "test-file"), []byte("## test content"), 0o666) - assert.NoError(t, err) + require.NoError(t, err) err = git.AddChanges(dstPath, true) - assert.NoError(t, err) + require.NoError(t, err) err = git.CommitChanges(dstPath, git.CommitChangesOptions{ Committer: &git.Signature{ @@ -127,10 +127,10 @@ func TestCodeOwner(t *testing.T) { }, Message: "Add test-file.", }) - assert.NoError(t, err) + require.NoError(t, err) err = git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/main", "-o", "topic=codeowner-out-of-date").Run(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{BaseRepoID: repo.ID, HeadBranch: "user2/codeowner-out-of-date"}) unittest.AssertExistsIf(t, true, &issues_model.Review{IssueID: pr.IssueID, Type: issues_model.ReviewTypeRequest, ReviewerID: 4}) diff --git a/tests/integration/compare_test.go b/tests/integration/compare_test.go index 5d585e061d..b0c6633cc5 100644 --- a/tests/integration/compare_test.go +++ b/tests/integration/compare_test.go @@ -24,6 +24,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestCompareTag(t *testing.T) { @@ -139,7 +140,7 @@ func TestCompareWithPRsDisabled(t *testing.T) { testEditFile(t, session, "user1", "repo1", "recent-push", "README.md", "Hello recently!\n") repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user1", "repo1") - assert.NoError(t, err) + require.NoError(t, err) defer func() { // Re-enable PRs on the repo @@ -149,13 +150,13 @@ func TestCompareWithPRsDisabled(t *testing.T) { Type: unit_model.TypePullRequests, }}, nil) - assert.NoError(t, err) + require.NoError(t, err) }() // Disable PRs on the repo err = repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, nil, []unit_model.Type{unit_model.TypePullRequests}) - assert.NoError(t, err) + require.NoError(t, err) t.Run("branch view doesn't offer creating PRs", func(t *testing.T) { defer tests.PrintCurrentTest(t)() @@ -199,11 +200,11 @@ func TestCompareCrossRepo(t *testing.T) { repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerName: "user1", Name: "repo1-copy"}) gitRepo, err := gitrepo.OpenRepository(db.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() lastCommit, err := gitRepo.GetBranchCommitID("recent-push") - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, lastCommit) t.Run("view file button links to correct file in fork", func(t *testing.T) { diff --git a/tests/integration/create_no_session_test.go b/tests/integration/create_no_session_test.go index 601f5e1733..044b823737 100644 --- a/tests/integration/create_no_session_test.go +++ b/tests/integration/create_no_session_test.go @@ -17,6 +17,7 @@ import ( "gitea.com/go-chi/session" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func getSessionID(t *testing.T, resp *httptest.ResponseRecorder) string { @@ -45,7 +46,7 @@ func sessionFileExist(t *testing.T, tmpDir, sessionID string) bool { if os.IsNotExist(err) { return false } - assert.NoError(t, err) + require.NoError(t, err) } return true } @@ -62,7 +63,7 @@ func TestSessionFileCreation(t *testing.T) { var config session.Options err := json.Unmarshal([]byte(oldSessionConfig), &config) - assert.NoError(t, err) + require.NoError(t, err) config.Provider = "file" @@ -71,7 +72,7 @@ func TestSessionFileCreation(t *testing.T) { config.ProviderConfig = tmpDir newConfigBytes, err := json.Marshal(config) - assert.NoError(t, err) + require.NoError(t, err) setting.SessionConfig.ProviderConfig = string(newConfigBytes) diff --git a/tests/integration/db_collation_test.go b/tests/integration/db_collation_test.go index 4d822c45a6..0e5bf00ed7 100644 --- a/tests/integration/db_collation_test.go +++ b/tests/integration/db_collation_test.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/xorm" ) @@ -52,12 +53,12 @@ func TestDatabaseCollation(t *testing.T) { // all created tables should use case-sensitive collation by default _, _ = x.Exec("DROP TABLE IF EXISTS test_collation_tbl") err := x.Sync(&TestCollationTbl{}) - assert.NoError(t, err) + require.NoError(t, err) _, _ = x.Exec("INSERT INTO test_collation_tbl (txt) VALUES ('main')") _, _ = x.Exec("INSERT INTO test_collation_tbl (txt) VALUES ('Main')") // case-sensitive, so it inserts a new row _, _ = x.Exec("INSERT INTO test_collation_tbl (txt) VALUES ('main')") // duplicate, so it doesn't insert cnt, err := x.Count(&TestCollationTbl{}) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 2, cnt) _, _ = x.Exec("DROP TABLE IF EXISTS test_collation_tbl") @@ -71,7 +72,7 @@ func TestDatabaseCollation(t *testing.T) { defer tests.PrintCurrentTest(t)() r, err := db.CheckCollations(x) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, r.IsCollationCaseSensitive(r.DatabaseCollation)) assert.True(t, r.CollationEquals(r.ExpectedCollation, r.DatabaseCollation)) assert.NotEmpty(t, r.AvailableCollation) @@ -94,20 +95,20 @@ func TestDatabaseCollation(t *testing.T) { defer tests.PrintCurrentTest(t)() defer test.MockVariableValue(&setting.Database.CharsetCollation, "utf8mb4_bin")() - assert.NoError(t, db.ConvertDatabaseTable()) + require.NoError(t, db.ConvertDatabaseTable()) time.Sleep(5 * time.Second) r, err := db.CheckCollations(x) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "utf8mb4_bin", r.DatabaseCollation) assert.True(t, r.CollationEquals(r.ExpectedCollation, r.DatabaseCollation)) assert.Empty(t, r.InconsistentCollationColumns) _, _ = x.Exec("DROP TABLE IF EXISTS test_tbl") _, err = x.Exec("CREATE TABLE test_tbl (txt varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL)") - assert.NoError(t, err) + require.NoError(t, err) r, err = db.CheckCollations(x) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, r.InconsistentCollationColumns, "test_tbl.txt") }) @@ -115,20 +116,20 @@ func TestDatabaseCollation(t *testing.T) { defer tests.PrintCurrentTest(t)() defer test.MockVariableValue(&setting.Database.CharsetCollation, "utf8mb4_general_ci")() - assert.NoError(t, db.ConvertDatabaseTable()) + require.NoError(t, db.ConvertDatabaseTable()) time.Sleep(5 * time.Second) r, err := db.CheckCollations(x) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "utf8mb4_general_ci", r.DatabaseCollation) assert.True(t, r.CollationEquals(r.ExpectedCollation, r.DatabaseCollation)) assert.Empty(t, r.InconsistentCollationColumns) _, _ = x.Exec("DROP TABLE IF EXISTS test_tbl") _, err = x.Exec("CREATE TABLE test_tbl (txt varchar(10) COLLATE utf8mb4_bin NOT NULL)") - assert.NoError(t, err) + require.NoError(t, err) r, err = db.CheckCollations(x) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, r.InconsistentCollationColumns, "test_tbl.txt") }) @@ -136,11 +137,11 @@ func TestDatabaseCollation(t *testing.T) { defer tests.PrintCurrentTest(t)() defer test.MockVariableValue(&setting.Database.CharsetCollation, "")() - assert.NoError(t, db.ConvertDatabaseTable()) + require.NoError(t, db.ConvertDatabaseTable()) time.Sleep(5 * time.Second) r, err := db.CheckCollations(x) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, r.IsCollationCaseSensitive(r.DatabaseCollation)) assert.True(t, r.CollationEquals(r.ExpectedCollation, r.DatabaseCollation)) assert.Empty(t, r.InconsistentCollationColumns) diff --git a/tests/integration/doctor_packages_nuget_test.go b/tests/integration/doctor_packages_nuget_test.go index 29e4f6055f..a012567efc 100644 --- a/tests/integration/doctor_packages_nuget_test.go +++ b/tests/integration/doctor_packages_nuget_test.go @@ -24,6 +24,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDoctorPackagesNuget(t *testing.T) { @@ -65,11 +66,11 @@ func TestDoctorPackagesNuget(t *testing.T) { pkg := createPackage(packageName, packageVersion) pkgBuf, err := packages_module.CreateHashedBufferFromReader(pkg) - assert.NoError(t, err, "Error creating hashed buffer from nupkg") + require.NoError(t, err, "Error creating hashed buffer from nupkg") defer pkgBuf.Close() doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) - assert.NoError(t, err, "Error getting user by ID 2") + require.NoError(t, err, "Error getting user by ID 2") t.Run("PackagesNugetNuspecCheck", func(t *testing.T) { defer tests.PrintCurrentTest(t)() @@ -96,9 +97,9 @@ func TestDoctorPackagesNuget(t *testing.T) { IsLead: true, }, ) - assert.NoError(t, err, "Error creating package and adding file") + require.NoError(t, err, "Error creating package and adding file") - assert.NoError(t, doctor.PackagesNugetNuspecCheck(ctx, logger, true), "Doctor check failed") + require.NoError(t, doctor.PackagesNugetNuspecCheck(ctx, logger, true), "Doctor check failed") s, _, pf, err := packages_service.GetFileStreamByPackageNameAndVersion( ctx, @@ -113,7 +114,7 @@ func TestDoctorPackagesNuget(t *testing.T) { }, ) - assert.NoError(t, err, "Error getting nuspec file stream by package name and version") + require.NoError(t, err, "Error getting nuspec file stream by package name and version") defer s.Close() assert.Equal(t, fmt.Sprintf("%s.nuspec", packageName), pf.Name, "Not a nuspec") diff --git a/tests/integration/dump_restore_test.go b/tests/integration/dump_restore_test.go index 47bb6f76e9..fa65695150 100644 --- a/tests/integration/dump_restore_test.go +++ b/tests/integration/dump_restore_test.go @@ -25,6 +25,7 @@ import ( "code.gitea.io/gitea/services/migrations" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gopkg.in/yaml.v3" ) @@ -40,12 +41,12 @@ func TestDumpRestore(t *testing.T) { setting.AppVer = AppVer }() - assert.NoError(t, migrations.Init()) + require.NoError(t, migrations.Init()) reponame := "repo1" basePath, err := os.MkdirTemp("", reponame) - assert.NoError(t, err) + require.NoError(t, err) defer util.RemoveAll(basePath) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) @@ -70,7 +71,7 @@ func TestDumpRestore(t *testing.T) { RepoName: reponame, } err = migrations.DumpRepository(ctx, basePath, repoOwner.Name, opts) - assert.NoError(t, err) + require.NoError(t, err) // // Verify desired side effects of the dump @@ -88,7 +89,7 @@ func TestDumpRestore(t *testing.T) { err = migrations.RestoreRepository(ctx, d, repo.OwnerName, newreponame, []string{ "labels", "issues", "comments", "milestones", "pull_requests", }, false) - assert.NoError(t, err) + require.NoError(t, err) newrepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: newreponame}) @@ -98,7 +99,7 @@ func TestDumpRestore(t *testing.T) { opts.RepoName = newreponame opts.CloneAddr = newrepo.CloneLink().HTTPS err = migrations.DumpRepository(ctx, basePath, repoOwner.Name, opts) - assert.NoError(t, err) + require.NoError(t, err) // // Verify the dump of restored is the same as the dump of repo1 @@ -224,11 +225,11 @@ func (c *compareDump) assertLoadYAMLFiles(beforeFilename, afterFilename string, } beforeBytes, err := os.ReadFile(beforeFilename) - assert.NoError(c.t, err) - assert.NoError(c.t, yaml.Unmarshal(beforeBytes, before)) + require.NoError(c.t, err) + require.NoError(c.t, yaml.Unmarshal(beforeBytes, before)) afterBytes, err := os.ReadFile(afterFilename) - assert.NoError(c.t, err) - assert.NoError(c.t, yaml.Unmarshal(afterBytes, after)) + require.NoError(c.t, err) + require.NoError(c.t, yaml.Unmarshal(afterBytes, after)) } func (c *compareDump) assertLoadFiles(beforeFilename, afterFilename string, t reflect.Type) (before, after reflect.Value) { diff --git a/tests/integration/editor_test.go b/tests/integration/editor_test.go index fdffdcec40..4ed6485717 100644 --- a/tests/integration/editor_test.go +++ b/tests/integration/editor_test.go @@ -106,7 +106,7 @@ func TestCreateFileOnProtectedBranch(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusOK) res := make(map[string]string) - assert.NoError(t, json.NewDecoder(resp.Body).Decode(&res)) + require.NoError(t, json.NewDecoder(resp.Body).Decode(&res)) assert.EqualValues(t, "/user2/repo1/settings/branches", res["redirect"]) // Check if master branch has been locked successfully @@ -309,7 +309,7 @@ func TestCommitMail(t *testing.T) { } commit, err := gitRepo.GetCommitByPath(case1.fileName) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "user2", commit.Author.Name) assert.EqualValues(t, "user2@noreply.example.org", commit.Author.Email) @@ -334,7 +334,7 @@ func TestCommitMail(t *testing.T) { } commit, err := gitRepo.GetCommitByPath(case2.fileName) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "user2", commit.Author.Name) assert.EqualValues(t, primaryEmail.Email, commit.Author.Email) @@ -495,9 +495,9 @@ index 0000000000..4475433e27 defer tests.PrintCurrentTest(t)() commitID1, err := gitRepo.GetCommitByPath("diff-file-1.txt") - assert.NoError(t, err) + require.NoError(t, err) commitID2, err := gitRepo.GetCommitByPath("diff-file-2.txt") - assert.NoError(t, err) + require.NoError(t, err) assertCase(t, caseOpts{ fileName: "diff-file-1.txt", diff --git a/tests/integration/empty_repo_test.go b/tests/integration/empty_repo_test.go index 8ab755c4fa..4122c78ec2 100644 --- a/tests/integration/empty_repo_test.go +++ b/tests/integration/empty_repo_test.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestEmptyRepo(t *testing.T) { @@ -86,7 +87,7 @@ func TestEmptyRepoUploadFile(t *testing.T) { req.Header.Add("Content-Type", mpForm.FormDataContentType()) resp = session.MakeRequest(t, req, http.StatusOK) respMap := map[string]string{} - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), &respMap)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), &respMap)) req = NewRequestWithValues(t, "POST", "/user30/empty/_upload/"+setting.Repository.DefaultBranch, map[string]string{ "_csrf": GetCSRF(t, session, "/user/settings"), diff --git a/tests/integration/eventsource_test.go b/tests/integration/eventsource_test.go index 2ef4218977..e081df0e57 100644 --- a/tests/integration/eventsource_test.go +++ b/tests/integration/eventsource_test.go @@ -20,6 +20,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestEventSourceManagerRun(t *testing.T) { @@ -58,7 +59,7 @@ func TestEventSourceManagerRun(t *testing.T) { user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) thread5 := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{ID: 5}) - assert.NoError(t, thread5.LoadAttributes(db.DefaultContext)) + require.NoError(t, thread5.LoadAttributes(db.DefaultContext)) session := loginUser(t, user2.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteNotification, auth_model.AccessTokenScopeWriteRepository) diff --git a/tests/integration/explore_code_test.go b/tests/integration/explore_code_test.go index cf3939b093..1634f70d39 100644 --- a/tests/integration/explore_code_test.go +++ b/tests/integration/explore_code_test.go @@ -21,5 +21,5 @@ func TestExploreCodeSearchIndexer(t *testing.T) { doc := NewHTMLParser(t, resp.Body) msg := doc.Find(".explore").Find(".ui.container").Find(".ui.message[data-test-tag=grep]") - assert.EqualValues(t, 0, len(msg.Nodes)) + assert.Empty(t, msg.Nodes) } diff --git a/tests/integration/forgejo_confirmation_repo_test.go b/tests/integration/forgejo_confirmation_repo_test.go index 53bd32f1a6..598baa48b4 100644 --- a/tests/integration/forgejo_confirmation_repo_test.go +++ b/tests/integration/forgejo_confirmation_repo_test.go @@ -55,7 +55,7 @@ func TestDangerZoneConfirmation(t *testing.T) { flashCookie := session.GetCookie(gitea_context.CookieNameFlash) assert.NotNil(t, flashCookie) - assert.EqualValues(t, flashCookie.Value, "success%3DThis%2Brepository%2Bhas%2Bbeen%2Bmarked%2Bfor%2Btransfer%2Band%2Bawaits%2Bconfirmation%2Bfrom%2B%2522User%2BOne%2522") + assert.EqualValues(t, "success%3DThis%2Brepository%2Bhas%2Bbeen%2Bmarked%2Bfor%2Btransfer%2Band%2Bawaits%2Bconfirmation%2Bfrom%2B%2522User%2BOne%2522", flashCookie.Value) }) }) @@ -85,7 +85,7 @@ func TestDangerZoneConfirmation(t *testing.T) { flashCookie := session.GetCookie(gitea_context.CookieNameFlash) assert.NotNil(t, flashCookie) - assert.EqualValues(t, flashCookie.Value, "success%3DThe%2Bfork%2Bhas%2Bbeen%2Bconverted%2Binto%2Ba%2Bregular%2Brepository.") + assert.EqualValues(t, "success%3DThe%2Bfork%2Bhas%2Bbeen%2Bconverted%2Binto%2Ba%2Bregular%2Brepository.", flashCookie.Value) }) }) @@ -148,7 +148,7 @@ func TestDangerZoneConfirmation(t *testing.T) { flashCookie := session.GetCookie(gitea_context.CookieNameFlash) assert.NotNil(t, flashCookie) - assert.EqualValues(t, flashCookie.Value, "success%3DThe%2Brepository%2Bwiki%2Bdata%2Bhas%2Bbeen%2Bdeleted.") + assert.EqualValues(t, "success%3DThe%2Brepository%2Bwiki%2Bdata%2Bhas%2Bbeen%2Bdeleted.", flashCookie.Value) }) }) @@ -178,7 +178,7 @@ func TestDangerZoneConfirmation(t *testing.T) { flashCookie := session.GetCookie(gitea_context.CookieNameFlash) assert.NotNil(t, flashCookie) - assert.EqualValues(t, flashCookie.Value, "success%3DThe%2Brepository%2Bhas%2Bbeen%2Bdeleted.") + assert.EqualValues(t, "success%3DThe%2Brepository%2Bhas%2Bbeen%2Bdeleted.", flashCookie.Value) }) }) } diff --git a/tests/integration/forgejo_git_test.go b/tests/integration/forgejo_git_test.go index bd0fb207eb..ebad074e14 100644 --- a/tests/integration/forgejo_git_test.go +++ b/tests/integration/forgejo_git_test.go @@ -21,7 +21,7 @@ import ( api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestActionsUserGit(t *testing.T) { @@ -90,12 +90,10 @@ func doActionsUserPopulateBranch(dstPath string, ctx *APITestContext, baseBranch t.Run("AddCommit", func(t *testing.T) { err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0o666) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) err = git.AddChanges(dstPath, true) - assert.NoError(t, err) + require.NoError(t, err) err = git.CommitChanges(dstPath, git.CommitChangesOptions{ Committer: &git.Signature{ @@ -110,12 +108,12 @@ func doActionsUserPopulateBranch(dstPath string, ctx *APITestContext, baseBranch }, Message: "Testing commit 1", }) - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("Push", func(t *testing.T) { err := git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments("HEAD:refs/heads/" + headBranch).Run(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) }) } } @@ -129,7 +127,7 @@ func doActionsUserPR(ctx, doerCtx APITestContext, baseBranch, headBranch string) // Create a test pullrequest t.Run("CreatePullRequest", func(t *testing.T) { pr, err = doAPICreatePullRequest(doerCtx, ctx.Username, ctx.Reponame, baseBranch, headBranch)(t) - assert.NoError(t, err) + require.NoError(t, err) }) doerCtx.ExpectedCode = http.StatusCreated t.Run("AutoMergePR", doAPIAutoMergePullRequest(doerCtx, ctx.Username, ctx.Reponame, pr.Index)) diff --git a/tests/integration/git_clone_wiki_test.go b/tests/integration/git_clone_wiki_test.go index d7949dfe25..ec99374c81 100644 --- a/tests/integration/git_clone_wiki_test.go +++ b/tests/integration/git_clone_wiki_test.go @@ -16,17 +16,18 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func assertFileExist(t *testing.T, p string) { exist, err := util.IsExist(p) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exist) } func assertFileEqual(t *testing.T, p string, content []byte) { bs, err := os.ReadFile(p) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, content, bs) } @@ -40,7 +41,7 @@ func TestRepoCloneWiki(t *testing.T) { u, _ = url.Parse(r) u.User = url.UserPassword("user2", userPassword) t.Run("Clone", func(t *testing.T) { - assert.NoError(t, git.CloneWithArgs(context.Background(), git.AllowLFSFiltersArgs(), u.String(), dstPath, git.CloneRepoOptions{})) + require.NoError(t, git.CloneWithArgs(context.Background(), git.AllowLFSFiltersArgs(), u.String(), dstPath, git.CloneRepoOptions{})) assertFileEqual(t, filepath.Join(dstPath, "Home.md"), []byte("# Home page\n\nThis is the home page!\n")) assertFileExist(t, filepath.Join(dstPath, "Page-With-Image.md")) assertFileExist(t, filepath.Join(dstPath, "Page-With-Spaced-Name.md")) diff --git a/tests/integration/git_helper_for_declarative_test.go b/tests/integration/git_helper_for_declarative_test.go index 795fd0d005..490d4caae0 100644 --- a/tests/integration/git_helper_for_declarative_test.go +++ b/tests/integration/git_helper_for_declarative_test.go @@ -23,21 +23,22 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func withKeyFile(t *testing.T, keyname string, callback func(string)) { tmpDir := t.TempDir() err := os.Chmod(tmpDir, 0o700) - assert.NoError(t, err) + require.NoError(t, err) keyFile := filepath.Join(tmpDir, keyname) err = ssh.GenKeyPair(keyFile) - assert.NoError(t, err) + require.NoError(t, err) err = os.WriteFile(path.Join(tmpDir, "ssh"), []byte("#!/bin/bash\n"+ "ssh -o \"UserKnownHostsFile=/dev/null\" -o \"StrictHostKeyChecking=no\" -o \"IdentitiesOnly=yes\" -i \""+keyFile+"\" \"$@\""), 0o700) - assert.NoError(t, err) + require.NoError(t, err) // Setup ssh wrapper t.Setenv("GIT_SSH", path.Join(tmpDir, "ssh")) @@ -64,7 +65,7 @@ func onGiteaRun[T testing.TB](t T, callback func(T, *url.URL)) { } u, err := url.Parse(setting.AppURL) - assert.NoError(t, err) + require.NoError(t, err) listener, err := net.Listen("tcp", u.Host) i := 0 for err != nil && i <= 10 { @@ -72,7 +73,7 @@ func onGiteaRun[T testing.TB](t T, callback func(T, *url.URL)) { listener, err = net.Listen("tcp", u.Host) i++ } - assert.NoError(t, err) + require.NoError(t, err) u.Host = listener.Addr().String() defer func() { @@ -90,9 +91,9 @@ func onGiteaRun[T testing.TB](t T, callback func(T, *url.URL)) { func doGitClone(dstLocalPath string, u *url.URL) func(*testing.T) { return func(t *testing.T) { t.Helper() - assert.NoError(t, git.CloneWithArgs(context.Background(), git.AllowLFSFiltersArgs(), u.String(), dstLocalPath, git.CloneRepoOptions{})) + require.NoError(t, git.CloneWithArgs(context.Background(), git.AllowLFSFiltersArgs(), u.String(), dstLocalPath, git.CloneRepoOptions{})) exist, err := util.IsExist(filepath.Join(dstLocalPath, "README.md")) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exist) } } @@ -100,11 +101,11 @@ func doGitClone(dstLocalPath string, u *url.URL) func(*testing.T) { func doPartialGitClone(dstLocalPath string, u *url.URL) func(*testing.T) { return func(t *testing.T) { t.Helper() - assert.NoError(t, git.CloneWithArgs(context.Background(), git.AllowLFSFiltersArgs(), u.String(), dstLocalPath, git.CloneRepoOptions{ + require.NoError(t, git.CloneWithArgs(context.Background(), git.AllowLFSFiltersArgs(), u.String(), dstLocalPath, git.CloneRepoOptions{ Filter: "blob:none", })) exist, err := util.IsExist(filepath.Join(dstLocalPath, "README.md")) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, exist) } } @@ -113,9 +114,9 @@ func doGitCloneFail(u *url.URL) func(*testing.T) { return func(t *testing.T) { t.Helper() tmpDir := t.TempDir() - assert.Error(t, git.Clone(git.DefaultContext, u.String(), tmpDir, git.CloneRepoOptions{})) + require.Error(t, git.Clone(git.DefaultContext, u.String(), tmpDir, git.CloneRepoOptions{})) exist, err := util.IsExist(filepath.Join(tmpDir, "README.md")) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exist) } } @@ -124,18 +125,18 @@ func doGitInitTestRepository(dstPath string, objectFormat git.ObjectFormat) func return func(t *testing.T) { t.Helper() // Init repository in dstPath - assert.NoError(t, git.InitRepository(git.DefaultContext, dstPath, false, objectFormat.Name())) + require.NoError(t, git.InitRepository(git.DefaultContext, dstPath, false, objectFormat.Name())) // forcibly set default branch to master _, _, err := git.NewCommand(git.DefaultContext, "symbolic-ref", "HEAD", git.BranchPrefix+"master").RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) - assert.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644)) - assert.NoError(t, git.AddChanges(dstPath, true)) + require.NoError(t, err) + require.NoError(t, os.WriteFile(filepath.Join(dstPath, "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", dstPath)), 0o644)) + require.NoError(t, git.AddChanges(dstPath, true)) signature := git.Signature{ Email: "test@example.com", Name: "test", When: time.Now(), } - assert.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{ + require.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{ Committer: &signature, Author: &signature, Message: "Initial Commit", @@ -147,7 +148,7 @@ func doGitAddRemote(dstPath, remoteName string, u *url.URL) func(*testing.T) { return func(t *testing.T) { t.Helper() _, _, err := git.NewCommand(git.DefaultContext, "remote", "add").AddDynamicArguments(remoteName, u.String()).RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -155,7 +156,7 @@ func doGitPushTestRepository(dstPath string, args ...string) func(*testing.T) { return func(t *testing.T) { t.Helper() _, _, err := git.NewCommand(git.DefaultContext, "push", "-u").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -163,7 +164,7 @@ func doGitPushTestRepositoryFail(dstPath string, args ...string) func(*testing.T return func(t *testing.T) { t.Helper() _, _, err := git.NewCommand(git.DefaultContext, "push").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(&git.RunOpts{Dir: dstPath}) - assert.Error(t, err) + require.Error(t, err) } } @@ -171,13 +172,13 @@ func doGitAddSomeCommits(dstPath, branch string) func(*testing.T) { return func(t *testing.T) { doGitCheckoutBranch(dstPath, branch)(t) - assert.NoError(t, os.WriteFile(filepath.Join(dstPath, fmt.Sprintf("file-%s.txt", branch)), []byte(fmt.Sprintf("file %s", branch)), 0o644)) - assert.NoError(t, git.AddChanges(dstPath, true)) + require.NoError(t, os.WriteFile(filepath.Join(dstPath, fmt.Sprintf("file-%s.txt", branch)), []byte(fmt.Sprintf("file %s", branch)), 0o644)) + require.NoError(t, git.AddChanges(dstPath, true)) signature := git.Signature{ Email: "test@test.test", Name: "test", } - assert.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{ + require.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{ Committer: &signature, Author: &signature, Message: fmt.Sprintf("update %s", branch), @@ -189,7 +190,7 @@ func doGitCreateBranch(dstPath, branch string) func(*testing.T) { return func(t *testing.T) { t.Helper() _, _, err := git.NewCommand(git.DefaultContext, "checkout", "-b").AddDynamicArguments(branch).RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -197,7 +198,7 @@ func doGitCheckoutBranch(dstPath string, args ...string) func(*testing.T) { return func(t *testing.T) { t.Helper() _, _, err := git.NewCommandContextNoGlobals(git.DefaultContext, git.AllowLFSFiltersArgs()...).AddArguments("checkout").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) } } @@ -205,6 +206,6 @@ func doGitPull(dstPath string, args ...string) func(*testing.T) { return func(t *testing.T) { t.Helper() _, _, err := git.NewCommandContextNoGlobals(git.DefaultContext, git.AllowLFSFiltersArgs()...).AddArguments("pull").AddArguments(git.ToTrustedCmdArgs(args)...).RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) } } diff --git a/tests/integration/git_smart_http_test.go b/tests/integration/git_smart_http_test.go index 15336b9b81..2b904ed99f 100644 --- a/tests/integration/git_smart_http_test.go +++ b/tests/integration/git_smart_http_test.go @@ -10,6 +10,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGitSmartHTTP(t *testing.T) { @@ -55,14 +56,14 @@ func testGitSmartHTTP(t *testing.T, u *url.URL) { t.Run(kase.p, func(t *testing.T) { p := u.String() + kase.p req, err := http.NewRequest("GET", p, nil) - assert.NoError(t, err) + require.NoError(t, err) req.SetBasicAuth("user2", userPassword) resp, err := http.DefaultClient.Do(req) - assert.NoError(t, err) + require.NoError(t, err) defer resp.Body.Close() assert.EqualValues(t, kase.code, resp.StatusCode) _, err = io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) }) } } diff --git a/tests/integration/git_test.go b/tests/integration/git_test.go index af6b825f0e..120e4834b6 100644 --- a/tests/integration/git_test.go +++ b/tests/integration/git_test.go @@ -162,11 +162,11 @@ func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS strin defer tests.PrintCurrentTest(t)() prefix := "lfs-data-file-" err := git.NewCommand(git.DefaultContext, "lfs").AddArguments("install").Run(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("track").AddDynamicArguments(prefix + "*").RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) err = git.AddChanges(dstPath, false, ".gitattributes") - assert.NoError(t, err) + require.NoError(t, err) err = git.CommitChangesWithArgs(dstPath, git.AllowLFSFiltersArgs(), git.CommitChangesOptions{ Committer: &git.Signature{ @@ -181,7 +181,7 @@ func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS strin }, Message: fmt.Sprintf("Testing commit @ %v", time.Now()), }) - assert.NoError(t, err) + require.NoError(t, err) littleLFS, bigLFS = commitAndPushTest(t, dstPath, prefix) @@ -290,20 +290,20 @@ func lockTest(t *testing.T, repoPath string) { func lockFileTest(t *testing.T, filename, repoPath string) { _, _, err := git.NewCommand(git.DefaultContext, "lfs").AddArguments("locks").RunStdString(&git.RunOpts{Dir: repoPath}) - assert.NoError(t, err) + require.NoError(t, err) _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("lock").AddDynamicArguments(filename).RunStdString(&git.RunOpts{Dir: repoPath}) - assert.NoError(t, err) + require.NoError(t, err) _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("locks").RunStdString(&git.RunOpts{Dir: repoPath}) - assert.NoError(t, err) + require.NoError(t, err) _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("unlock").AddDynamicArguments(filename).RunStdString(&git.RunOpts{Dir: repoPath}) - assert.NoError(t, err) + require.NoError(t, err) } func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string { name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix) - assert.NoError(t, err) + require.NoError(t, err) _, _, err = git.NewCommand(git.DefaultContext, "push", "origin", "master").RunStdString(&git.RunOpts{Dir: repoPath}) // Push - assert.NoError(t, err) + require.NoError(t, err) return name } @@ -374,7 +374,7 @@ func doBranchProtect(baseCtx *APITestContext, dstPath string) func(t *testing.T) t.Run("Create modified-protected-branch", doGitCheckoutBranch(dstPath, "-b", "modified-protected-branch", "protected")) t.Run("GenerateCommit", func(t *testing.T) { _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-") - assert.NoError(t, err) + require.NoError(t, err) }) doGitPushTestRepositoryFail(dstPath, "origin", "modified-protected-branch:protected")(t) @@ -386,7 +386,7 @@ func doBranchProtect(baseCtx *APITestContext, dstPath string) func(t *testing.T) t.Run("Create modified-protected-file-protected-branch", doGitCheckoutBranch(dstPath, "-b", "modified-protected-file-protected-branch", "protected")) t.Run("GenerateCommit", func(t *testing.T) { _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "protected-file-") - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("ProtectedFilePathsApplyToAdmins", doProtectBranch(ctx, "protected")) @@ -403,7 +403,7 @@ func doBranchProtect(baseCtx *APITestContext, dstPath string) func(t *testing.T) })) t.Run("GenerateCommit", func(t *testing.T) { _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "unprotected-file-") - assert.NoError(t, err) + require.NoError(t, err) }) doGitPushTestRepository(dstPath, "origin", "modified-unprotected-file-protected-branch:protected")(t) doGitCheckoutBranch(dstPath, "protected")(t) @@ -411,7 +411,7 @@ func doBranchProtect(baseCtx *APITestContext, dstPath string) func(t *testing.T) }) user, err := user_model.GetUserByName(db.DefaultContext, baseCtx.Username) - assert.NoError(t, err) + require.NoError(t, err) t.Run("WhitelistUsers", doProtectBranch(ctx, "protected", parameterProtectBranch{ "enable_push": "whitelist", "enable_whitelist": "on", @@ -422,7 +422,7 @@ func doBranchProtect(baseCtx *APITestContext, dstPath string) func(t *testing.T) t.Run("Create toforce", doGitCheckoutBranch(dstPath, "-b", "toforce", "master")) t.Run("GenerateCommit", func(t *testing.T) { _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-") - assert.NoError(t, err) + require.NoError(t, err) }) doGitPushTestRepositoryFail(dstPath, "-f", "origin", "toforce:protected")(t) }) @@ -431,7 +431,7 @@ func doBranchProtect(baseCtx *APITestContext, dstPath string) func(t *testing.T) t.Run("Create topush", doGitCheckoutBranch(dstPath, "-b", "topush", "protected")) t.Run("GenerateCommit", func(t *testing.T) { _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-") - assert.NoError(t, err) + require.NoError(t, err) }) doGitPushTestRepository(dstPath, "origin", "topush:protected")(t) }) @@ -479,7 +479,7 @@ func doMergeFork(ctx, baseCtx APITestContext, baseBranch, headBranch string) fun // Create a test pull request t.Run("CreatePullRequest", func(t *testing.T) { pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t) - assert.NoError(t, err) + require.NoError(t, err) }) // Ensure the PR page works. @@ -527,7 +527,7 @@ func doMergeFork(ctx, baseCtx APITestContext, baseBranch, headBranch string) fun t.Run("CheckPR", func(t *testing.T) { oldMergeBase := pr.MergeBase pr2, err := doAPIGetPullRequest(baseCtx, baseCtx.Username, baseCtx.Reponame, pr.Index)(t) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, oldMergeBase, pr2.MergeBase) }) t.Run("EnsurDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffHash, diffLength)) @@ -566,7 +566,7 @@ func doCreatePRAndSetManuallyMerged(ctx, baseCtx APITestContext, dstPath, baseBr t.Run("PushToHeadBranch", doGitPushTestRepository(dstPath, "origin", headBranch)) t.Run("CreateEmptyPullRequest", func(t *testing.T) { pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t) - assert.NoError(t, err) + require.NoError(t, err) }) lastCommitID = pr.Base.Sha t.Run("ManuallyMergePR", doAPIManuallyMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, lastCommitID, pr.Index)) @@ -582,7 +582,7 @@ func doEnsureCanSeePull(ctx APITestContext, pr api.PullRequest, editable bool) f doc := NewHTMLParser(t, resp.Body) editButtonCount := doc.doc.Find("div.diff-file-header-actions a[href*='/_edit/']").Length() if editable { - assert.Greater(t, editButtonCount, 0, "Expected to find a button to edit a file in the PR diff view but there were none") + assert.Positive(t, editButtonCount, 0, "Expected to find a button to edit a file in the PR diff view but there were none") } else { assert.Equal(t, 0, editButtonCount, "Expected not to find any buttons to edit files in PR diff view but there were some") } @@ -636,7 +636,7 @@ func doPushCreate(ctx APITestContext, u *url.URL, objectFormat git.ObjectFormat) // Finally, fetch repo from database and ensure the correct repository has been created repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, ctx.Username, ctx.Reponame) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, repo.IsEmpty) assert.True(t, repo.IsPrivate) @@ -672,14 +672,14 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) { t.Run("PullProtected", doGitPull(dstPath, "origin", "protected")) t.Run("GenerateCommit", func(t *testing.T) { _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-") - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("PushToUnprotectedBranch", doGitPushTestRepository(dstPath, "origin", "protected:unprotected3")) var pr api.PullRequest var err error t.Run("CreatePullRequest", func(t *testing.T) { pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, "protected", "unprotected3")(t) - assert.NoError(t, err) + require.NoError(t, err) }) // Request repository commits page @@ -729,7 +729,7 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) { // Check pr status ctx.ExpectedCode = 0 pr, err = doAPIGetPullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index)(t) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, pr.HasMerged) // Call API to add Failure status for commit @@ -737,7 +737,7 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) { // Check pr status pr, err = doAPIGetPullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index)(t) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, pr.HasMerged) // Call API to add Success status for commit @@ -748,7 +748,7 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) { // test pr status pr, err = doAPIGetPullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index)(t) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, pr.HasMerged) } } @@ -761,7 +761,7 @@ func doInternalReferences(ctx *APITestContext, dstPath string) func(t *testing.T pr1 := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{HeadRepoID: repo.ID}) _, stdErr, gitErr := git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments(fmt.Sprintf(":refs/pull/%d/head", pr1.Index)).RunStdString(&git.RunOpts{Dir: dstPath}) - assert.Error(t, gitErr) + require.Error(t, gitErr) assert.Contains(t, stdErr, fmt.Sprintf("remote: Forgejo: The deletion of refs/pull/%d/head is skipped as it's an internal reference.", pr1.Index)) assert.Contains(t, stdErr, fmt.Sprintf("[remote rejected] refs/pull/%d/head (hook declined)", pr1.Index)) } @@ -777,9 +777,8 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string } gitRepo, err := git.OpenRepository(git.DefaultContext, dstPath) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + defer gitRepo.Close() var ( @@ -787,9 +786,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string commit string ) repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, ctx.Username, ctx.Reponame) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) pullNum := unittest.GetCount(t, &issues_model.PullRequest{}) @@ -797,12 +794,10 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string t.Run("AddCommit", func(t *testing.T) { err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0o666) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) err = git.AddChanges(dstPath, true) - assert.NoError(t, err) + require.NoError(t, err) err = git.CommitChanges(dstPath, git.CommitChangesOptions{ Committer: &git.Signature{ @@ -817,16 +812,15 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string }, Message: "Testing commit 1", }) - assert.NoError(t, err) + require.NoError(t, err) commit, err = gitRepo.GetRefCommitID("HEAD") - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("Push", func(t *testing.T) { err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic=" + headBranch).Run(&git.RunOpts{Dir: dstPath}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+1) pr1 = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ HeadRepoID: repo.ID, @@ -836,18 +830,16 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string return } prMsg, err := doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr1.Index)(t) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, "user2/"+headBranch, pr1.HeadBranch) assert.False(t, prMsg.HasMerged) assert.Contains(t, "Testing commit 1", prMsg.Body) assert.Equal(t, commit, prMsg.Head.Sha) _, _, err = git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments("HEAD:refs/for/master/test/" + headBranch).RunStdString(&git.RunOpts{Dir: dstPath}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+2) pr2 = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ HeadRepoID: repo.ID, @@ -858,9 +850,8 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string return } prMsg, err = doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr2.Index)(t) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.Equal(t, "user2/test/"+headBranch, pr2.HeadBranch) assert.False(t, prMsg.HasMerged) }) @@ -882,12 +873,10 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string t.Run("AddCommit2", func(t *testing.T) { err := os.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0o666) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) err = git.AddChanges(dstPath, true) - assert.NoError(t, err) + require.NoError(t, err) err = git.CommitChanges(dstPath, git.CommitChangesOptions{ Committer: &git.Signature{ @@ -902,33 +891,29 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string }, Message: "Testing commit 2\n\nLonger description.", }) - assert.NoError(t, err) + require.NoError(t, err) commit, err = gitRepo.GetRefCommitID("HEAD") - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("Push2", func(t *testing.T) { err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic=" + headBranch).Run(&git.RunOpts{Dir: dstPath}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+2) prMsg, err := doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr1.Index)(t) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.False(t, prMsg.HasMerged) assert.Equal(t, commit, prMsg.Head.Sha) _, _, err = git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments("HEAD:refs/for/master/test/" + headBranch).RunStdString(&git.RunOpts{Dir: dstPath}) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+2) prMsg, err = doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr2.Index)(t) - if !assert.NoError(t, err) { - return - } + require.NoError(t, err) + assert.False(t, prMsg.HasMerged) assert.Equal(t, commit, prMsg.Head.Sha) }) @@ -939,7 +924,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string defer tests.PrintCurrentTest(t)() _, _, gitErr := git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments("HEAD:refs/for/master/" + headBranch + "-implicit").RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, gitErr) + require.NoError(t, gitErr) unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+3) pr3 := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ @@ -949,7 +934,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string }) assert.NotEmpty(t, pr3) err := pr3.LoadIssue(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) _, err2 := doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr3.Index)(t) require.NoError(t, err2) @@ -961,7 +946,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string defer tests.PrintCurrentTest(t)() _, _, gitErr := git.NewCommand(git.DefaultContext, "push", "origin", "-o", "title=my-shiny-title").AddDynamicArguments("HEAD:refs/for/master/" + headBranch + "-implicit-2").RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, gitErr) + require.NoError(t, gitErr) unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+4) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ @@ -971,7 +956,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string }) assert.NotEmpty(t, pr) err := pr.LoadIssue(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) _, err = doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr.Index)(t) require.NoError(t, err) @@ -984,7 +969,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string defer tests.PrintCurrentTest(t)() _, _, gitErr := git.NewCommand(git.DefaultContext, "push", "origin", "-o", "description=custom").AddDynamicArguments("HEAD:refs/for/master/" + headBranch + "-implicit-3").RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, gitErr) + require.NoError(t, gitErr) unittest.AssertCount(t, &issues_model.PullRequest{}, pullNum+5) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ @@ -994,7 +979,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string }) assert.NotEmpty(t, pr) err := pr.LoadIssue(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) _, err = doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr.Index)(t) require.NoError(t, err) @@ -1031,22 +1016,22 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string defer tests.PrintCurrentTest(t)() _, stdErr, gitErr := git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments("HEAD:refs/for/master/" + headBranch + "-force-push").RunStdString(&git.RunOpts{Dir: dstPath}) - assert.Error(t, gitErr) + require.Error(t, gitErr) assert.Contains(t, stdErr, "-o force-push=true") currentHeadCommitID, err := upstreamGitRepo.GetRefCommitID(pr.GetGitRefName()) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, headCommitID, currentHeadCommitID) }) t.Run("Succeeds", func(t *testing.T) { defer tests.PrintCurrentTest(t)() _, _, gitErr := git.NewCommand(git.DefaultContext, "push", "origin", "-o", "force-push").AddDynamicArguments("HEAD:refs/for/master/" + headBranch + "-force-push").RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, gitErr) + require.NoError(t, gitErr) currentHeadCommitID, err := upstreamGitRepo.GetRefCommitID(pr.GetGitRefName()) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqualValues(t, headCommitID, currentHeadCommitID) }) }) @@ -1061,7 +1046,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, headBranch string require.NoError(t, gitErr) _, stdErr, gitErr := git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments("HEAD:refs/for/master/" + headBranch + "-already-contains").RunStdString(&git.RunOpts{Dir: dstPath}) - assert.Error(t, gitErr) + require.Error(t, gitErr) assert.Contains(t, stdErr, "already contains this commit") }) @@ -1099,28 +1084,28 @@ func TestDataAsync_Issue29101(t *testing.T) { OldBranch: repo.DefaultBranch, NewBranch: repo.DefaultBranch, }) - assert.NoError(t, err) + require.NoError(t, err) sha := resp.Commit.SHA gitRepo, err := gitrepo.OpenRepository(db.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() commit, err := gitRepo.GetCommit(sha) - assert.NoError(t, err) + require.NoError(t, err) entry, err := commit.GetTreeEntryByPath("test.txt") - assert.NoError(t, err) + require.NoError(t, err) b := entry.Blob() r, err := b.DataAsync() - assert.NoError(t, err) + require.NoError(t, err) defer r.Close() r2, err := b.DataAsync() - assert.NoError(t, err) + require.NoError(t, err) defer r2.Close() }) } diff --git a/tests/integration/gpg_git_test.go b/tests/integration/gpg_git_test.go index 5b23b6bd31..5302997f6d 100644 --- a/tests/integration/gpg_git_test.go +++ b/tests/integration/gpg_git_test.go @@ -23,21 +23,20 @@ import ( "github.com/ProtonMail/go-crypto/openpgp" "github.com/ProtonMail/go-crypto/openpgp/armor" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestGPGGit(t *testing.T) { tmpDir := t.TempDir() // use a temp dir to avoid messing with the user's GPG keyring err := os.Chmod(tmpDir, 0o700) - assert.NoError(t, err) + require.NoError(t, err) t.Setenv("GNUPGHOME", tmpDir) - assert.NoError(t, err) + require.NoError(t, err) // Need to create a root key rootKeyPair, err := importTestingKey() - if !assert.NoError(t, err, "importTestingKey") { - return - } + require.NoError(t, err, "importTestingKey") defer test.MockVariableValue(&setting.Repository.Signing.SigningKey, rootKeyPair.PrimaryKey.KeyIdShortString())() defer test.MockVariableValue(&setting.Repository.Signing.SigningName, "gitea")() @@ -215,7 +214,7 @@ func TestGPGGit(t *testing.T) { testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) t.Run("CreatePullRequest", func(t *testing.T) { pr, err := doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "never2")(t) - assert.NoError(t, err) + require.NoError(t, err) t.Run("MergePR", doAPIMergePullRequest(testCtx, testCtx.Username, testCtx.Reponame, pr.Index)) }) t.Run("CheckMasterBranchUnsigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) { @@ -232,7 +231,7 @@ func TestGPGGit(t *testing.T) { testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) t.Run("CreatePullRequest", func(t *testing.T) { pr, err := doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "parentsigned2")(t) - assert.NoError(t, err) + require.NoError(t, err) t.Run("MergePR", doAPIMergePullRequest(testCtx, testCtx.Username, testCtx.Reponame, pr.Index)) }) t.Run("CheckMasterBranchUnsigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) { @@ -249,7 +248,7 @@ func TestGPGGit(t *testing.T) { testCtx := NewAPITestContext(t, username, "initial-unsigned", auth_model.AccessTokenScopeWriteRepository, auth_model.AccessTokenScopeWriteUser) t.Run("CreatePullRequest", func(t *testing.T) { pr, err := doAPICreatePullRequest(testCtx, testCtx.Username, testCtx.Reponame, "master", "always-parentsigned")(t) - assert.NoError(t, err) + require.NoError(t, err) t.Run("MergePR", doAPIMergePullRequest(testCtx, testCtx.Username, testCtx.Reponame, pr.Index)) }) t.Run("CheckMasterBranchUnsigned", doAPIGetBranch(testCtx, "master", func(t *testing.T, branch api.Branch) { diff --git a/tests/integration/html_helper.go b/tests/integration/html_helper.go index 6c7c8e7467..f6768714a6 100644 --- a/tests/integration/html_helper.go +++ b/tests/integration/html_helper.go @@ -10,6 +10,7 @@ import ( "github.com/PuerkitoBio/goquery" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) // HTMLDoc struct @@ -21,7 +22,7 @@ type HTMLDoc struct { func NewHTMLParser(t testing.TB, body *bytes.Buffer) *HTMLDoc { t.Helper() doc, err := goquery.NewDocumentFromReader(body) - assert.NoError(t, err) + require.NoError(t, err) return &HTMLDoc{doc: doc} } @@ -41,7 +42,7 @@ func (doc *HTMLDoc) AssertDropdown(t testing.TB, name string) *goquery.Selection t.Helper() dropdownGroup := doc.Find(fmt.Sprintf(".dropdown:has(input[name='%s'])", name)) - assert.Equal(t, dropdownGroup.Length(), 1, fmt.Sprintf("%s dropdown does not exist", name)) + assert.Equal(t, 1, dropdownGroup.Length(), fmt.Sprintf("%s dropdown does not exist", name)) return dropdownGroup } @@ -50,7 +51,7 @@ func (doc *HTMLDoc) AssertDropdownHasOptions(t testing.TB, dropdownName string) t.Helper() options := doc.AssertDropdown(t, dropdownName).Find(".menu [data-value]:not([data-value=''])") - assert.Greater(t, options.Length(), 0, fmt.Sprintf("%s dropdown has no options", dropdownName)) + assert.Positive(t, options.Length(), 0, fmt.Sprintf("%s dropdown has no options", dropdownName)) } func (doc *HTMLDoc) AssertDropdownHasSelectedOption(t testing.TB, dropdownName, expectedValue string) { diff --git a/tests/integration/incoming_email_test.go b/tests/integration/incoming_email_test.go index 543e620dbf..fdc0425b54 100644 --- a/tests/integration/incoming_email_test.go +++ b/tests/integration/incoming_email_test.go @@ -22,6 +22,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "gopkg.in/gomail.v2" ) @@ -37,23 +38,23 @@ func TestIncomingEmail(t *testing.T) { comment := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 1}) _, err := incoming_payload.CreateReferencePayload(user) - assert.Error(t, err) + require.Error(t, err) issuePayload, err := incoming_payload.CreateReferencePayload(issue) - assert.NoError(t, err) + require.NoError(t, err) commentPayload, err := incoming_payload.CreateReferencePayload(comment) - assert.NoError(t, err) + require.NoError(t, err) _, err = incoming_payload.GetReferenceFromPayload(db.DefaultContext, []byte{1, 2, 3}) - assert.Error(t, err) + require.Error(t, err) ref, err := incoming_payload.GetReferenceFromPayload(db.DefaultContext, issuePayload) - assert.NoError(t, err) + require.NoError(t, err) assert.IsType(t, ref, new(issues_model.Issue)) assert.EqualValues(t, issue.ID, ref.(*issues_model.Issue).ID) ref, err = incoming_payload.GetReferenceFromPayload(db.DefaultContext, commentPayload) - assert.NoError(t, err) + require.NoError(t, err) assert.IsType(t, ref, new(issues_model.Comment)) assert.EqualValues(t, comment.ID, ref.(*issues_model.Comment).ID) }) @@ -64,11 +65,11 @@ func TestIncomingEmail(t *testing.T) { payload := []byte{1, 2, 3, 4, 5} token, err := token_service.CreateToken(token_service.ReplyHandlerType, user, payload) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, token) ht, u, p, err := token_service.ExtractToken(db.DefaultContext, token) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, token_service.ReplyHandlerType, ht) assert.Equal(t, user.ID, u.ID) assert.Equal(t, payload, p) @@ -81,8 +82,8 @@ func TestIncomingEmail(t *testing.T) { handler := &incoming.ReplyHandler{} - assert.Error(t, handler.Handle(db.DefaultContext, &incoming.MailContent{}, nil, payload)) - assert.NoError(t, handler.Handle(db.DefaultContext, &incoming.MailContent{}, user, payload)) + require.Error(t, handler.Handle(db.DefaultContext, &incoming.MailContent{}, nil, payload)) + require.NoError(t, handler.Handle(db.DefaultContext, &incoming.MailContent{}, user, payload)) content := &incoming.MailContent{ Content: "reply by mail", @@ -94,18 +95,18 @@ func TestIncomingEmail(t *testing.T) { }, } - assert.NoError(t, handler.Handle(db.DefaultContext, content, user, payload)) + require.NoError(t, handler.Handle(db.DefaultContext, content, user, payload)) comments, err := issues_model.FindComments(db.DefaultContext, &issues_model.FindCommentsOptions{ IssueID: issue.ID, Type: commentType, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, comments) comment := comments[len(comments)-1] assert.Equal(t, user.ID, comment.PosterID) assert.Equal(t, content.Content, comment.Content) - assert.NoError(t, comment.LoadAttachments(db.DefaultContext)) + require.NoError(t, comment.LoadAttachments(db.DefaultContext)) assert.Len(t, comment.Attachments, 1) attachment := comment.Attachments[0] assert.Equal(t, content.Attachments[0].Name, attachment.Name) @@ -115,7 +116,7 @@ func TestIncomingEmail(t *testing.T) { defer tests.PrintCurrentTest(t)() payload, err := incoming_payload.CreateReferencePayload(issue) - assert.NoError(t, err) + require.NoError(t, err) checkReply(t, payload, issue, issues_model.CommentTypeComment) }) @@ -127,7 +128,7 @@ func TestIncomingEmail(t *testing.T) { issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: comment.IssueID}) payload, err := incoming_payload.CreateReferencePayload(comment) - assert.NoError(t, err) + require.NoError(t, err) checkReply(t, payload, issue, issues_model.CommentTypeCode) }) @@ -139,7 +140,7 @@ func TestIncomingEmail(t *testing.T) { issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: comment.IssueID}) payload, err := incoming_payload.CreateReferencePayload(comment) - assert.NoError(t, err) + require.NoError(t, err) checkReply(t, payload, issue, issues_model.CommentTypeComment) }) @@ -149,7 +150,7 @@ func TestIncomingEmail(t *testing.T) { defer tests.PrintCurrentTest(t)() watching, err := issues_model.CheckIssueWatch(db.DefaultContext, user, issue) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, watching) handler := &incoming.UnsubscribeHandler{} @@ -159,12 +160,12 @@ func TestIncomingEmail(t *testing.T) { } payload, err := incoming_payload.CreateReferencePayload(issue) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, handler.Handle(db.DefaultContext, content, user, payload)) + require.NoError(t, handler.Handle(db.DefaultContext, content, user, payload)) watching, err = issues_model.CheckIssueWatch(db.DefaultContext, user, issue) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, watching) }) }) @@ -176,23 +177,23 @@ func TestIncomingEmail(t *testing.T) { defer tests.PrintCurrentTest(t)() payload, err := incoming_payload.CreateReferencePayload(issue) - assert.NoError(t, err) + require.NoError(t, err) token, err := token_service.CreateToken(token_service.ReplyHandlerType, user, payload) - assert.NoError(t, err) + require.NoError(t, err) msg := gomail.NewMessage() msg.SetHeader("To", strings.Replace(setting.IncomingEmail.ReplyToAddress, setting.IncomingEmail.TokenPlaceholder, token, 1)) msg.SetHeader("From", user.Email) msg.SetBody("text/plain", token) err = gomail.Send(&smtpTestSender{}, msg) - assert.NoError(t, err) + require.NoError(t, err) assert.Eventually(t, func() bool { comments, err := issues_model.FindComments(db.DefaultContext, &issues_model.FindCommentsOptions{ IssueID: issue.ID, Type: issues_model.CommentTypeComment, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, comments) comment := comments[len(comments)-1] diff --git a/tests/integration/integration_test.go b/tests/integration/integration_test.go index 6876619969..dafc000ff7 100644 --- a/tests/integration/integration_test.go +++ b/tests/integration/integration_test.go @@ -58,6 +58,7 @@ import ( goth_gitlab "github.com/markbates/goth/providers/gitlab" "github.com/santhosh-tekuri/jsonschema/v6" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var testWebRoutes *web.Route @@ -235,7 +236,7 @@ func (s *TestSession) MakeRequest(t testing.TB, rw *RequestWrapper, expectedStat t.Helper() req := rw.Request baseURL, err := url.Parse(setting.AppURL) - assert.NoError(t, err) + require.NoError(t, err) for _, c := range s.jar.Cookies(baseURL) { req.AddCookie(c) } @@ -253,7 +254,7 @@ func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, rw *RequestWr t.Helper() req := rw.Request baseURL, err := url.Parse(setting.AppURL) - assert.NoError(t, err) + require.NoError(t, err) for _, c := range s.jar.Cookies(baseURL) { req.AddCookie(c) } @@ -271,7 +272,7 @@ func (s *TestSession) MakeRequestNilResponseHashSumRecorder(t testing.TB, rw *Re t.Helper() req := rw.Request baseURL, err := url.Parse(setting.AppURL) - assert.NoError(t, err) + require.NoError(t, err) for _, c := range s.jar.Cookies(baseURL) { req.AddCookie(c) } @@ -290,7 +291,7 @@ const userPassword = "password" func emptyTestSession(t testing.TB) *TestSession { t.Helper() jar, err := cookiejar.New(nil) - assert.NoError(t, err) + require.NoError(t, err) return &TestSession{jar: jar} } @@ -313,7 +314,7 @@ func addAuthSource(t *testing.T, payload map[string]string) *auth.Source { req := NewRequestWithValues(t, "POST", "/admin/auths/new", payload) session.MakeRequest(t, req, http.StatusSeeOther) source, err := auth.GetSourceByName(context.Background(), payload["name"]) - assert.NoError(t, err) + require.NoError(t, err) return source } @@ -363,7 +364,7 @@ func authSourcePayloadGitHubCustom(name string) map[string]string { } func createRemoteAuthSource(t *testing.T, name, url, matchingSource string) *auth.Source { - assert.NoError(t, auth.CreateSource(context.Background(), &auth.Source{ + require.NoError(t, auth.CreateSource(context.Background(), &auth.Source{ Type: auth.Remote, Name: name, IsActive: true, @@ -373,7 +374,7 @@ func createRemoteAuthSource(t *testing.T, name, url, matchingSource string) *aut }, })) source, err := auth.GetSourceByName(context.Background(), name) - assert.NoError(t, err) + require.NoError(t, err) return source } @@ -381,14 +382,14 @@ func createUser(ctx context.Context, t testing.TB, user *user_model.User) func() user.MustChangePassword = false user.LowerName = strings.ToLower(user.Name) - assert.NoError(t, db.Insert(ctx, user)) + require.NoError(t, db.Insert(ctx, user)) if len(user.Email) > 0 { - assert.NoError(t, user_service.ReplacePrimaryEmailAddress(ctx, user, user.Email)) + require.NoError(t, user_service.ReplacePrimaryEmailAddress(ctx, user, user.Email)) } return func() { - assert.NoError(t, user_service.DeleteUser(ctx, user, true)) + require.NoError(t, user_service.DeleteUser(ctx, user, true)) } } @@ -425,7 +426,7 @@ func loginUserWithPasswordRemember(t testing.TB, userName, password string, reme session := emptyTestSession(t) baseURL, err := url.Parse(setting.AppURL) - assert.NoError(t, err) + require.NoError(t, err) session.jar.SetCookies(baseURL, cr.Cookies()) return session @@ -465,7 +466,7 @@ func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...auth. resp = session.MakeRequest(t, req, http.StatusSeeOther) // Log the flash values on failure - if !assert.Equal(t, resp.Result().Header["Location"], []string{"/user/settings/applications"}) { + if !assert.Equal(t, []string{"/user/settings/applications"}, resp.Result().Header["Location"]) { for _, cookie := range resp.Result().Cookies() { if cookie.Name != gitea_context.CookieNameFlash { continue @@ -539,7 +540,7 @@ func NewRequestWithJSON(t testing.TB, method, urlStr string, v any) *RequestWrap t.Helper() jsonBytes, err := json.Marshal(v) - assert.NoError(t, err) + require.NoError(t, err) return NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes)). SetHeader("Content-Type", "application/json") } @@ -550,7 +551,7 @@ func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *Re urlStr = "/" + urlStr } req, err := http.NewRequest(method, urlStr, body) - assert.NoError(t, err) + require.NoError(t, err) req.RequestURI = urlStr return &RequestWrapper{req} @@ -649,7 +650,7 @@ func DecodeJSON(t testing.TB, resp *httptest.ResponseRecorder, v any) { t.Helper() decoder := json.NewDecoder(resp.Body) - assert.NoError(t, decoder.Decode(v)) + require.NoError(t, decoder.Decode(v)) } func VerifyJSONSchema(t testing.TB, resp *httptest.ResponseRecorder, schemaFile string) { @@ -657,17 +658,17 @@ func VerifyJSONSchema(t testing.TB, resp *httptest.ResponseRecorder, schemaFile schemaFilePath := filepath.Join(filepath.Dir(setting.AppPath), "tests", "integration", "schemas", schemaFile) _, schemaFileErr := os.Stat(schemaFilePath) - assert.Nil(t, schemaFileErr) + require.NoError(t, schemaFileErr) schema, err := jsonschema.NewCompiler().Compile(schemaFilePath) - assert.NoError(t, err) + require.NoError(t, err) var data any err = json.Unmarshal(resp.Body.Bytes(), &data) - assert.NoError(t, err) + require.NoError(t, err) schemaValidation := schema.Validate(data) - assert.Nil(t, schemaValidation) + require.NoError(t, schemaValidation) } func GetCSRF(t testing.TB, session *TestSession, urlStr string) string { @@ -731,7 +732,7 @@ func CreateDeclarativeRepoWithOptions(t *testing.T, owner *user_model.User, opts Readme: "Default", DefaultBranch: "main", }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, repo) // Populate `enabledUnits` if we have any enabled. @@ -751,7 +752,7 @@ func CreateDeclarativeRepoWithOptions(t *testing.T, owner *user_model.User, opts // Adjust the repo units according to our parameters. if opts.EnabledUnits.Has() || opts.DisabledUnits.Has() { err := repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, enabledUnits, opts.DisabledUnits.ValueOrDefault(nil)) - assert.NoError(t, err) + require.NoError(t, err) } // Add files, if any. @@ -778,7 +779,7 @@ func CreateDeclarativeRepoWithOptions(t *testing.T, owner *user_model.User, opts Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, resp) sha = resp.Commit.SHA @@ -789,15 +790,15 @@ func CreateDeclarativeRepoWithOptions(t *testing.T, owner *user_model.User, opts // Set the wiki branch in the database first repo.WikiBranch = opts.WikiBranch.Value() err := repo_model.UpdateRepositoryCols(db.DefaultContext, repo, "wiki_branch") - assert.NoError(t, err) + require.NoError(t, err) // Initialize the wiki err = wiki_service.InitWiki(db.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) // Add a new wiki page err = wiki_service.AddWikiPage(db.DefaultContext, owner, repo, "Home", "Welcome to the wiki!", "Add a Home page") - assert.NoError(t, err) + require.NoError(t, err) } // Return the repo, the top commit, and a defer-able function to delete the diff --git a/tests/integration/issue_test.go b/tests/integration/issue_test.go index bf05c3c0a6..846de8f42c 100644 --- a/tests/integration/issue_test.go +++ b/tests/integration/issue_test.go @@ -35,6 +35,7 @@ import ( "github.com/PuerkitoBio/goquery" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func getIssuesSelection(t testing.TB, htmlDoc *HTMLDoc) *goquery.Selection { @@ -48,7 +49,7 @@ func getIssue(t *testing.T, repoID int64, issueSelection *goquery.Selection) *is assert.True(t, exists) indexStr := href[strings.LastIndexByte(href, '/')+1:] index, err := strconv.Atoi(indexStr) - assert.NoError(t, err, "Invalid issue href: %s", href) + require.NoError(t, err, "Invalid issue href: %s", href) return unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{RepoID: repoID, Index: int64(index)}) } @@ -203,7 +204,7 @@ func TestViewIssuesSearchOptions(t *testing.T) { issue := getIssue(t, repo.ID, selection) found[issue.ID] = true }) - assert.EqualValues(t, 2, len(found)) + assert.Len(t, found, 2) assert.True(t, found[1]) assert.True(t, found[5]) }) @@ -276,7 +277,7 @@ func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content, idStr := idAttr[strings.LastIndexByte(idAttr, '-')+1:] assert.True(t, has) id, err := strconv.Atoi(idStr) - assert.NoError(t, err) + require.NoError(t, err) return int64(id) } @@ -317,7 +318,7 @@ Description`) // Issues list should show the correct numbers of checked and total checkboxes repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") - assert.NoError(t, err) + require.NoError(t, err) req = NewRequestf(t, "GET", "%s/issues", repo.Link()) resp = MakeRequest(t, req, http.StatusOK) @@ -521,7 +522,7 @@ func TestIssueCommentAttachment(t *testing.T) { idStr := idAttr[strings.LastIndexByte(idAttr, '-')+1:] assert.True(t, has) id, err := strconv.Atoi(idStr) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, 0, id) req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s/comments/%d/attachments", "user2", "repo1", id)) @@ -716,7 +717,7 @@ func testIssueWithBean(t *testing.T, user string, repoID int64, title, content s issueURL := testNewIssue(t, session, user, fmt.Sprintf("repo%d", repoID), title, content) indexStr := issueURL[strings.LastIndexByte(issueURL, '/')+1:] index, err := strconv.Atoi(indexStr) - assert.NoError(t, err, "Invalid issue href: %s", issueURL) + require.NoError(t, err, "Invalid issue href: %s", issueURL) issue := &issues_model.Issue{RepoID: repoID, Index: int64(index)} unittest.AssertExistsAndLoadBean(t, issue) return issueURL, issue @@ -918,7 +919,7 @@ func TestGetIssueInfo(t *testing.T) { issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 10}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) - assert.NoError(t, issue.LoadAttributes(db.DefaultContext)) + require.NoError(t, issue.LoadAttributes(db.DefaultContext)) assert.Equal(t, int64(1019307200), int64(issue.DeadlineUnix)) assert.Equal(t, api.StateOpen, issue.State()) @@ -981,7 +982,7 @@ func TestUpdateIssueDeadline(t *testing.T) { issueBefore := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 10}) repoBefore := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issueBefore.RepoID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repoBefore.OwnerID}) - assert.NoError(t, issueBefore.LoadAttributes(db.DefaultContext)) + require.NoError(t, issueBefore.LoadAttributes(db.DefaultContext)) assert.Equal(t, int64(1019307200), int64(issueBefore.DeadlineUnix)) assert.Equal(t, api.StateOpen, issueBefore.State()) @@ -1111,7 +1112,7 @@ func TestIssueFilterNoFollow(t *testing.T) { // Check that every link in the filter list has rel="nofollow". filterLinks := htmlDoc.Find(".issue-list-toolbar-right a[href*=\"?q=\"]") - assert.True(t, filterLinks.Length() > 0) + assert.Positive(t, filterLinks.Length()) filterLinks.Each(func(i int, link *goquery.Selection) { rel, has := link.Attr("rel") assert.True(t, has) diff --git a/tests/integration/last_updated_time_test.go b/tests/integration/last_updated_time_test.go index c1b3f515e1..e7bf3a4a07 100644 --- a/tests/integration/last_updated_time_test.go +++ b/tests/integration/last_updated_time_test.go @@ -30,7 +30,7 @@ func TestRepoLastUpdatedTime(t *testing.T) { // Relative time should be present as a descendent { relativeTime := node.Find("relative-time").Text() - assert.Equal(t, true, strings.HasPrefix(relativeTime, "19")) // ~1970, might underflow with timezone + assert.True(t, strings.HasPrefix(relativeTime, "19")) // ~1970, might underflow with timezone } }) } @@ -49,12 +49,12 @@ func TestBranchLastUpdatedTime(t *testing.T) { { buf := "" findTextNonNested(t, node, &buf) - assert.Equal(t, true, strings.Contains(buf, "Updated")) + assert.True(t, strings.Contains(buf, "Updated")) } { relativeTime := node.Find("relative-time").Text() - assert.Equal(t, true, strings.HasPrefix(relativeTime, "2017")) + assert.True(t, strings.HasPrefix(relativeTime, "2017")) } }) } diff --git a/tests/integration/lfs_getobject_test.go b/tests/integration/lfs_getobject_test.go index dad05890a9..351c1a38a4 100644 --- a/tests/integration/lfs_getobject_test.go +++ b/tests/integration/lfs_getobject_test.go @@ -23,27 +23,28 @@ import ( "github.com/klauspost/compress/gzhttp" gzipp "github.com/klauspost/compress/gzip" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func storeObjectInRepo(t *testing.T, repositoryID int64, content *[]byte) string { pointer, err := lfs.GeneratePointer(bytes.NewReader(*content)) - assert.NoError(t, err) + require.NoError(t, err) _, err = git_model.NewLFSMetaObject(db.DefaultContext, repositoryID, pointer) - assert.NoError(t, err) + require.NoError(t, err) contentStore := lfs.NewContentStore() exist, err := contentStore.Exists(pointer) - assert.NoError(t, err) + require.NoError(t, err) if !exist { err := contentStore.Put(pointer, bytes.NewReader(*content)) - assert.NoError(t, err) + require.NoError(t, err) } return pointer.Oid } func storeAndGetLfsToken(t *testing.T, content *[]byte, extraHeader *http.Header, expectedStatus int, ts ...auth.AccessTokenScope) *httptest.ResponseRecorder { repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") - assert.NoError(t, err) + require.NoError(t, err) oid := storeObjectInRepo(t, repo.ID, content) defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) @@ -68,7 +69,7 @@ func storeAndGetLfsToken(t *testing.T, content *[]byte, extraHeader *http.Header func storeAndGetLfs(t *testing.T, content *[]byte, extraHeader *http.Header, expectedStatus int) *httptest.ResponseRecorder { repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") - assert.NoError(t, err) + require.NoError(t, err) oid := storeObjectInRepo(t, repo.ID, content) defer git_model.RemoveLFSMetaObjectByOid(db.DefaultContext, repo.ID, oid) @@ -100,9 +101,9 @@ func checkResponseTestContentEncoding(t *testing.T, content *[]byte, resp *httpt } else { assert.Contains(t, contentEncoding, "gzip") gzippReader, err := gzipp.NewReader(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) result, err := io.ReadAll(gzippReader) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, *content, result) } } @@ -166,7 +167,7 @@ func TestGetLFSZip(t *testing.T) { outputBuffer := bytes.NewBuffer([]byte{}) zipWriter := zip.NewWriter(outputBuffer) fileWriter, err := zipWriter.Create("default") - assert.NoError(t, err) + require.NoError(t, err) fileWriter.Write(b) zipWriter.Close() content := outputBuffer.Bytes() @@ -219,7 +220,7 @@ func TestGetLFSRange(t *testing.T) { } else { var er lfs.ErrorResponse err := json.Unmarshal(resp.Body.Bytes(), &er) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, tt.out, er.Message) } }) diff --git a/tests/integration/lfs_view_test.go b/tests/integration/lfs_view_test.go index 9dfcb3e698..8817986b79 100644 --- a/tests/integration/lfs_view_test.go +++ b/tests/integration/lfs_view_test.go @@ -92,7 +92,7 @@ func TestLFSRender(t *testing.T) { filesTable := NewHTMLParser(t, resp.Body).doc.Find("#lfs-files-table") assert.Contains(t, filesTable.Text(), "Find commits") lfsFind := filesTable.Find(`.primary.button[href^="/user2"]`) - assert.Greater(t, lfsFind.Length(), 0) + assert.Positive(t, lfsFind.Length()) lfsFindPath, exists := lfsFind.First().Attr("href") assert.True(t, exists) diff --git a/tests/integration/linguist_test.go b/tests/integration/linguist_test.go index 4c8ae4bdb3..332f6a8ea4 100644 --- a/tests/integration/linguist_test.go +++ b/tests/integration/linguist_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestLinguistSupport(t *testing.T) { @@ -79,15 +80,15 @@ func TestLinguistSupport(t *testing.T) { t.Helper() err := stats.UpdateRepoIndexer(repo) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, queue.GetManager().FlushAll(context.Background(), 10*time.Second)) + require.NoError(t, queue.GetManager().FlushAll(context.Background(), 10*time.Second)) status, err := repo_model.GetIndexerStatus(db.DefaultContext, repo, repo_model.RepoIndexerTypeStats) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, sha, status.CommitSha) langs, err := repo_model.GetTopLanguageStats(db.DefaultContext, repo, 5) - assert.NoError(t, err) + require.NoError(t, err) return langs } diff --git a/tests/integration/markup_external_test.go b/tests/integration/markup_external_test.go index e50f5c1356..0eaa9669f4 100644 --- a/tests/integration/markup_external_test.go +++ b/tests/integration/markup_external_test.go @@ -14,6 +14,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestExternalMarkupRenderer(t *testing.T) { @@ -29,11 +30,11 @@ func TestExternalMarkupRenderer(t *testing.T) { assert.EqualValues(t, "text/html; charset=utf-8", resp.Header()["Content-Type"][0]) bs, err := io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) doc := NewHTMLParser(t, bytes.NewBuffer(bs)) div := doc.Find("div.file-view") data, err := div.Html() - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, "
\n\ttest external renderer\n
", strings.TrimSpace(data)) } diff --git a/tests/integration/migrate_test.go b/tests/integration/migrate_test.go index 44fc890abf..949bcd47bb 100644 --- a/tests/integration/migrate_test.go +++ b/tests/integration/migrate_test.go @@ -24,10 +24,11 @@ import ( "code.gitea.io/gitea/services/repository" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMigrateLocalPath(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) adminUser := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user1"}) @@ -38,17 +39,17 @@ func TestMigrateLocalPath(t *testing.T) { lowercasePath := filepath.Join(basePath, "lowercase") err := os.Mkdir(lowercasePath, 0o700) - assert.NoError(t, err) + require.NoError(t, err) err = migrations.IsMigrateURLAllowed(lowercasePath, adminUser) - assert.NoError(t, err, "case lowercase path") + require.NoError(t, err, "case lowercase path") mixedcasePath := filepath.Join(basePath, "mIxeDCaSe") err = os.Mkdir(mixedcasePath, 0o700) - assert.NoError(t, err) + require.NoError(t, err) err = migrations.IsMigrateURLAllowed(mixedcasePath, adminUser) - assert.NoError(t, err, "case mixedcase path") + require.NoError(t, err, "case mixedcase path") setting.ImportLocalPaths = old } @@ -65,7 +66,7 @@ func TestMigrate(t *testing.T) { setting.AppVer = AppVer migrations.Init() }() - assert.NoError(t, migrations.Init()) + require.NoError(t, migrations.Init()) ownerName := "user2" repoName := "repo1" @@ -110,14 +111,14 @@ func TestMigrate(t *testing.T) { // Step 7: delete the repository, so we can test with other services err := repository.DeleteRepository(context.Background(), repoOwner, repo, false) - assert.NoError(t, err) + require.NoError(t, err) } }) } func Test_UpdateCommentsMigrationsByType(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) err := issues_model.UpdateCommentsMigrationsByType(db.DefaultContext, structs.GithubService, "1", 1) - assert.NoError(t, err) + require.NoError(t, err) } diff --git a/tests/integration/migration-test/migration_test.go b/tests/integration/migration-test/migration_test.go index 0a3b38c987..a391296c35 100644 --- a/tests/integration/migration-test/migration_test.go +++ b/tests/integration/migration-test/migration_test.go @@ -31,6 +31,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "xorm.io/xorm" ) @@ -63,12 +64,12 @@ func initMigrationTest(t *testing.T) func() { unittest.InitSettings() - assert.True(t, len(setting.RepoRootPath) != 0) - assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) - assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath)) + assert.NotEmpty(t, setting.RepoRootPath) + require.NoError(t, util.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() { @@ -76,7 +77,7 @@ func initMigrationTest(t *testing.T) func() { } 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) @@ -86,7 +87,7 @@ func initMigrationTest(t *testing.T) func() { } } - assert.NoError(t, git.InitFull(context.Background())) + require.NoError(t, git.InitFull(context.Background())) setting.LoadDBSetting() setting.InitLoggersForTest() return deferFn @@ -149,7 +150,7 @@ func readSQLFromFile(version string) (string, error) { func restoreOldDB(t *testing.T, version string) bool { data, err := readSQLFromFile(version) - assert.NoError(t, err) + require.NoError(t, err) if len(data) == 0 { tests.Printf("No db found to restore for %s version: %s\n", setting.Database.Type, version) return false @@ -159,38 +160,38 @@ func restoreOldDB(t *testing.T, version string) bool { case setting.Database.Type.IsSQLite3(): util.Remove(setting.Database.Path) err := os.MkdirAll(path.Dir(setting.Database.Path), os.ModePerm) - assert.NoError(t, err) + require.NoError(t, err) db, err := sql.Open("sqlite3", fmt.Sprintf("file:%s?cache=shared&mode=rwc&_busy_timeout=%d&_txlock=immediate", setting.Database.Path, setting.Database.Timeout)) - assert.NoError(t, err) + require.NoError(t, err) defer db.Close() _, err = db.Exec(data) - assert.NoError(t, err) + require.NoError(t, err) db.Close() case setting.Database.Type.IsMySQL(): db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/", setting.Database.User, setting.Database.Passwd, setting.Database.Host)) - assert.NoError(t, err) + require.NoError(t, err) defer db.Close() databaseName := strings.SplitN(setting.Database.Name, "?", 2)[0] _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", databaseName)) - assert.NoError(t, err) + require.NoError(t, err) _, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", databaseName)) - assert.NoError(t, err) + require.NoError(t, err) db.Close() db, err = sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/%s", setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.Name)) - assert.NoError(t, err) + require.NoError(t, err) defer db.Close() _, err = db.Exec(data) - assert.NoError(t, err) + require.NoError(t, err) db.Close() case setting.Database.Type.IsPostgreSQL(): @@ -199,19 +200,19 @@ func restoreOldDB(t *testing.T, version string) bool { if setting.Database.Host[0] == '/' { db, err = sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@/?sslmode=%s&host=%s", setting.Database.User, setting.Database.Passwd, setting.Database.SSLMode, setting.Database.Host)) - assert.NoError(t, err) + require.NoError(t, err) } else { db, err = sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s", setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.SSLMode)) - assert.NoError(t, err) + require.NoError(t, err) } defer db.Close() _, err = db.Exec(fmt.Sprintf("DROP DATABASE IF EXISTS %s", setting.Database.Name)) - assert.NoError(t, err) + require.NoError(t, err) _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", setting.Database.Name)) - assert.NoError(t, err) + require.NoError(t, err) db.Close() // Check if we need to setup a specific schema @@ -223,26 +224,26 @@ func restoreOldDB(t *testing.T, version string) bool { db, err = sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s", setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.Name, setting.Database.SSLMode)) } - if !assert.NoError(t, err) { - return false - } + require.NoError(t, err) + defer db.Close() schrows, err := db.Query(fmt.Sprintf("SELECT 1 FROM information_schema.schemata WHERE schema_name = '%s'", setting.Database.Schema)) - if !assert.NoError(t, err) || !assert.NotEmpty(t, schrows) { + require.NoError(t, err) + if !assert.NotEmpty(t, schrows) { return false } if !schrows.Next() { // Create and setup a DB schema _, err = db.Exec(fmt.Sprintf("CREATE SCHEMA %s", setting.Database.Schema)) - assert.NoError(t, err) + require.NoError(t, err) } schrows.Close() // Make the user's default search path the created schema; this will affect new connections _, err = db.Exec(fmt.Sprintf(`ALTER USER "%s" SET search_path = %s`, setting.Database.User, setting.Database.Schema)) - assert.NoError(t, err) + require.NoError(t, err) db.Close() } @@ -254,11 +255,11 @@ func restoreOldDB(t *testing.T, version string) bool { db, err = sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s", setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.Name, setting.Database.SSLMode)) } - assert.NoError(t, err) + require.NoError(t, err) defer db.Close() _, err = db.Exec(data) - assert.NoError(t, err) + require.NoError(t, err) db.Close() } return true @@ -279,7 +280,7 @@ func doMigrationTest(t *testing.T, version string) { setting.InitSQLLoggersForCli(log.INFO) err := db.InitEngineWithMigration(context.Background(), wrappedMigrate) - assert.NoError(t, err) + require.NoError(t, err) currentEngine.Close() beans, _ := db.NamesToBean() @@ -288,7 +289,7 @@ func doMigrationTest(t *testing.T, version string) { currentEngine = x return migrate_base.RecreateTables(beans...)(x) }) - assert.NoError(t, err) + require.NoError(t, err) currentEngine.Close() // We do this a second time to ensure that there is not a problem with retained indices @@ -296,7 +297,7 @@ func doMigrationTest(t *testing.T, version string) { currentEngine = x return migrate_base.RecreateTables(beans...)(x) }) - assert.NoError(t, err) + require.NoError(t, err) currentEngine.Close() } @@ -306,7 +307,7 @@ func TestMigrations(t *testing.T) { dialect := setting.Database.Type versions, err := availableVersions() - assert.NoError(t, err) + require.NoError(t, err) if len(versions) == 0 { tests.Printf("No old database versions available to migration test for %s\n", dialect) diff --git a/tests/integration/mirror_pull_test.go b/tests/integration/mirror_pull_test.go index ced828f002..60fb47e94b 100644 --- a/tests/integration/mirror_pull_test.go +++ b/tests/integration/mirror_pull_test.go @@ -20,6 +20,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMirrorPull(t *testing.T) { @@ -46,16 +47,16 @@ func TestMirrorPull(t *testing.T) { IsMirror: opts.Mirror, Status: repo_model.RepositoryBeingMigrated, }) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, mirrorRepo.IsMirror, "expected pull-mirror repo to be marked as a mirror immediately after its creation") ctx := context.Background() mirror, err := repo_service.MigrateRepositoryGitData(ctx, user, mirrorRepo, opts, nil) - assert.NoError(t, err) + require.NoError(t, err) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() findOptions := repo_model.FindReleasesOptions{ @@ -64,9 +65,9 @@ func TestMirrorPull(t *testing.T) { RepoID: mirror.ID, } initCount, err := db.Count[repo_model.Release](db.DefaultContext, findOptions) - assert.NoError(t, err) + require.NoError(t, err) - assert.NoError(t, release_service.CreateRelease(gitRepo, &repo_model.Release{ + require.NoError(t, release_service.CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -81,23 +82,23 @@ func TestMirrorPull(t *testing.T) { }, "", []*release_service.AttachmentChange{})) _, err = repo_model.GetMirrorByRepoID(ctx, mirror.ID) - assert.NoError(t, err) + require.NoError(t, err) ok := mirror_service.SyncPullMirror(ctx, mirror.ID) assert.True(t, ok) count, err := db.Count[repo_model.Release](db.DefaultContext, findOptions) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, initCount+1, count) release, err := repo_model.GetRelease(db.DefaultContext, repo.ID, "v0.2") - assert.NoError(t, err) - assert.NoError(t, release_service.DeleteReleaseByID(ctx, repo, release, user, true)) + require.NoError(t, err) + require.NoError(t, release_service.DeleteReleaseByID(ctx, repo, release, user, true)) ok = mirror_service.SyncPullMirror(ctx, mirror.ID) assert.True(t, ok) count, err = db.Count[repo_model.Release](db.DefaultContext, findOptions) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, initCount, count) } diff --git a/tests/integration/mirror_push_test.go b/tests/integration/mirror_push_test.go index 7fb6414b4f..a8c654f69e 100644 --- a/tests/integration/mirror_push_test.go +++ b/tests/integration/mirror_push_test.go @@ -26,6 +26,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestMirrorPush(t *testing.T) { @@ -36,7 +37,7 @@ func testMirrorPush(t *testing.T, u *url.URL) { defer tests.PrepareTestEnv(t)() setting.Migrations.AllowLocalNetworks = true - assert.NoError(t, migrations.Init()) + require.NoError(t, migrations.Init()) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) srcRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) @@ -44,7 +45,7 @@ func testMirrorPush(t *testing.T, u *url.URL) { mirrorRepo, err := repo_service.CreateRepositoryDirectly(db.DefaultContext, user, user, repo_service.CreateRepoOptions{ Name: "test-push-mirror", }) - assert.NoError(t, err) + require.NoError(t, err) ctx := NewAPITestContext(t, user.LowerName, srcRepo.Name) @@ -52,25 +53,25 @@ func testMirrorPush(t *testing.T, u *url.URL) { doCreatePushMirror(ctx, fmt.Sprintf("%s%s/%s", u.String(), url.PathEscape(ctx.Username), url.PathEscape("does-not-matter")), user.LowerName, userPassword)(t) mirrors, _, err := repo_model.GetPushMirrorsByRepoID(db.DefaultContext, srcRepo.ID, db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, mirrors, 2) ok := mirror_service.SyncPushMirror(context.Background(), mirrors[0].ID) assert.True(t, ok) srcGitRepo, err := gitrepo.OpenRepository(git.DefaultContext, srcRepo) - assert.NoError(t, err) + require.NoError(t, err) defer srcGitRepo.Close() srcCommit, err := srcGitRepo.GetBranchCommit("master") - assert.NoError(t, err) + require.NoError(t, err) mirrorGitRepo, err := gitrepo.OpenRepository(git.DefaultContext, mirrorRepo) - assert.NoError(t, err) + require.NoError(t, err) defer mirrorGitRepo.Close() mirrorCommit, err := mirrorGitRepo.GetBranchCommit("master") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, srcCommit.ID, mirrorCommit.ID) @@ -78,31 +79,31 @@ func testMirrorPush(t *testing.T, u *url.URL) { // To do that, we artificially remove the remote... cmd := git.NewCommand(db.DefaultContext, "remote", "rm").AddDynamicArguments(mirrors[0].RemoteName) _, _, err = cmd.RunStdString(&git.RunOpts{Dir: srcRepo.RepoPath()}) - assert.NoError(t, err) + require.NoError(t, err) // ...then ensure that trying to get its remote address fails _, err = repo_model.GetPushMirrorRemoteAddress(srcRepo.OwnerName, srcRepo.Name, mirrors[0].RemoteName) - assert.Error(t, err) + require.Error(t, err) // ...and that we can fix it. err = doctor.FixPushMirrorsWithoutGitRemote(db.DefaultContext, nil, true) - assert.NoError(t, err) + require.NoError(t, err) // ...and after fixing, we only have one remote mirrors, _, err = repo_model.GetPushMirrorsByRepoID(db.DefaultContext, srcRepo.ID, db.ListOptions{}) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, mirrors, 1) // ...one we can get the address of, and it's not the one we removed remoteAddress, err := repo_model.GetPushMirrorRemoteAddress(srcRepo.OwnerName, srcRepo.Name, mirrors[0].RemoteName) - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, remoteAddress, "does-not-matter") // Cleanup doRemovePushMirror(ctx, fmt.Sprintf("%s%s/%s", u.String(), url.PathEscape(ctx.Username), url.PathEscape(mirrorRepo.Name)), user.LowerName, userPassword, int(mirrors[0].ID))(t) mirrors, _, err = repo_model.GetPushMirrorsByRepoID(db.DefaultContext, srcRepo.ID, db.ListOptions{}) - assert.NoError(t, err) - assert.Len(t, mirrors, 0) + require.NoError(t, err) + assert.Empty(t, mirrors) } func doCreatePushMirror(ctx APITestContext, address, username, password string) func(t *testing.T) { diff --git a/tests/integration/oauth_test.go b/tests/integration/oauth_test.go index 83a92be83a..240d374945 100644 --- a/tests/integration/oauth_test.go +++ b/tests/integration/oauth_test.go @@ -25,6 +25,7 @@ import ( "github.com/markbates/goth" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAuthorizeNoClientID(t *testing.T) { @@ -49,7 +50,7 @@ func TestAuthorizeUnsupportedResponseType(t *testing.T) { ctx := loginUser(t, "user1") resp := ctx.MakeRequest(t, req, http.StatusSeeOther) u, err := resp.Result().Location() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "unsupported_response_type", u.Query().Get("error")) assert.Equal(t, "Only code response type is supported.", u.Query().Get("error_description")) } @@ -60,7 +61,7 @@ func TestAuthorizeUnsupportedCodeChallengeMethod(t *testing.T) { ctx := loginUser(t, "user1") resp := ctx.MakeRequest(t, req, http.StatusSeeOther) u, err := resp.Result().Location() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "invalid_request", u.Query().Get("error")) assert.Equal(t, "unsupported code challenge method", u.Query().Get("error_description")) } @@ -147,9 +148,9 @@ func TestAuthorizeRedirectWithExistingGrant(t *testing.T) { ctx := loginUser(t, "user1") resp := ctx.MakeRequest(t, req, http.StatusSeeOther) u, err := resp.Result().Location() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "thestate", u.Query().Get("state")) - assert.Truef(t, len(u.Query().Get("code")) > 30, "authorization code '%s' should be longer then 30", u.Query().Get("code")) + assert.Greaterf(t, len(u.Query().Get("code")), 30, "authorization code '%s' should be longer then 30", u.Query().Get("code")) u.RawQuery = "" assert.Equal(t, "https://example.com/xyzzy", u.String()) } @@ -160,7 +161,7 @@ func TestAuthorizePKCERequiredForPublicClient(t *testing.T) { ctx := loginUser(t, "user1") resp := ctx.MakeRequest(t, req, http.StatusSeeOther) u, err := resp.Result().Location() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "invalid_request", u.Query().Get("error")) assert.Equal(t, "PKCE is required for public clients", u.Query().Get("error_description")) } @@ -184,9 +185,9 @@ func TestAccessTokenExchange(t *testing.T) { } parsed := new(response) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) - assert.True(t, len(parsed.AccessToken) > 10) - assert.True(t, len(parsed.RefreshToken) > 10) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) + assert.Greater(t, len(parsed.AccessToken), 10) + assert.Greater(t, len(parsed.RefreshToken), 10) } func TestAccessTokenExchangeWithPublicClient(t *testing.T) { @@ -207,9 +208,9 @@ func TestAccessTokenExchangeWithPublicClient(t *testing.T) { } parsed := new(response) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) - assert.True(t, len(parsed.AccessToken) > 10) - assert.True(t, len(parsed.RefreshToken) > 10) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) + assert.Greater(t, len(parsed.AccessToken), 10) + assert.Greater(t, len(parsed.RefreshToken), 10) } func TestAccessTokenExchangeJSON(t *testing.T) { @@ -231,9 +232,9 @@ func TestAccessTokenExchangeJSON(t *testing.T) { } parsed := new(response) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) - assert.True(t, len(parsed.AccessToken) > 10) - assert.True(t, len(parsed.RefreshToken) > 10) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) + assert.Greater(t, len(parsed.AccessToken), 10) + assert.Greater(t, len(parsed.RefreshToken), 10) } func TestAccessTokenExchangeWithoutPKCE(t *testing.T) { @@ -247,7 +248,7 @@ func TestAccessTokenExchangeWithoutPKCE(t *testing.T) { }) resp := MakeRequest(t, req, http.StatusBadRequest) parsedError := new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode)) assert.Equal(t, "failed PKCE code challenge", parsedError.ErrorDescription) } @@ -265,7 +266,7 @@ func TestAccessTokenExchangeWithInvalidCredentials(t *testing.T) { }) resp := MakeRequest(t, req, http.StatusBadRequest) parsedError := new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "invalid_client", string(parsedError.ErrorCode)) assert.Equal(t, "cannot load client with client id: '???'", parsedError.ErrorDescription) @@ -280,7 +281,7 @@ func TestAccessTokenExchangeWithInvalidCredentials(t *testing.T) { }) resp = MakeRequest(t, req, http.StatusBadRequest) parsedError = new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode)) assert.Equal(t, "invalid client secret", parsedError.ErrorDescription) @@ -295,7 +296,7 @@ func TestAccessTokenExchangeWithInvalidCredentials(t *testing.T) { }) resp = MakeRequest(t, req, http.StatusBadRequest) parsedError = new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode)) assert.Equal(t, "unexpected redirect URI", parsedError.ErrorDescription) @@ -310,7 +311,7 @@ func TestAccessTokenExchangeWithInvalidCredentials(t *testing.T) { }) resp = MakeRequest(t, req, http.StatusBadRequest) parsedError = new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode)) assert.Equal(t, "client is not authorized", parsedError.ErrorDescription) @@ -325,7 +326,7 @@ func TestAccessTokenExchangeWithInvalidCredentials(t *testing.T) { }) resp = MakeRequest(t, req, http.StatusBadRequest) parsedError = new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "unsupported_grant_type", string(parsedError.ErrorCode)) assert.Equal(t, "Only refresh_token or authorization_code grant type is supported", parsedError.ErrorDescription) } @@ -348,9 +349,9 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) { } parsed := new(response) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) - assert.True(t, len(parsed.AccessToken) > 10) - assert.True(t, len(parsed.RefreshToken) > 10) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) + assert.Greater(t, len(parsed.AccessToken), 10) + assert.Greater(t, len(parsed.RefreshToken), 10) // use wrong client_secret req = NewRequestWithValues(t, "POST", "/login/oauth/access_token", map[string]string{ @@ -362,7 +363,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) { req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OmJsYWJsYQ==") resp = MakeRequest(t, req, http.StatusBadRequest) parsedError := new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode)) assert.Equal(t, "invalid client secret", parsedError.ErrorDescription) @@ -375,7 +376,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) { }) resp = MakeRequest(t, req, http.StatusBadRequest) parsedError = new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "invalid_client", string(parsedError.ErrorCode)) assert.Equal(t, "cannot load client with client id: ''", parsedError.ErrorDescription) @@ -389,7 +390,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) { req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OjRNSzhOYTZSNTVzbWRDWTBXdUNDdW1aNmhqUlBuR1k1c2FXVlJISGpKaUE9") resp = MakeRequest(t, req, http.StatusBadRequest) parsedError = new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "invalid_request", string(parsedError.ErrorCode)) assert.Equal(t, "client_id in request body inconsistent with Authorization header", parsedError.ErrorDescription) @@ -403,7 +404,7 @@ func TestAccessTokenExchangeWithBasicAuth(t *testing.T) { req.Header.Add("Authorization", "Basic ZGE3ZGEzYmEtOWExMy00MTY3LTg1NmYtMzg5OWRlMGIwMTM4OjRNSzhOYTZSNTVzbWRDWTBXdUNDdW1aNmhqUlBuR1k1c2FXVlJISGpKaUE9") resp = MakeRequest(t, req, http.StatusBadRequest) parsedError = new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "invalid_request", string(parsedError.ErrorCode)) assert.Equal(t, "client_secret in request body inconsistent with Authorization header", parsedError.ErrorDescription) } @@ -427,7 +428,7 @@ func TestRefreshTokenInvalidation(t *testing.T) { } parsed := new(response) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsed)) // test without invalidation setting.OAuth2.InvalidateRefreshTokens = false @@ -441,7 +442,7 @@ func TestRefreshTokenInvalidation(t *testing.T) { }) resp = MakeRequest(t, req, http.StatusBadRequest) parsedError := new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "invalid_client", string(parsedError.ErrorCode)) assert.Equal(t, "invalid empty client secret", parsedError.ErrorDescription) @@ -454,7 +455,7 @@ func TestRefreshTokenInvalidation(t *testing.T) { }) resp = MakeRequest(t, req, http.StatusBadRequest) parsedError = new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode)) assert.Equal(t, "unable to parse refresh token", parsedError.ErrorDescription) @@ -467,7 +468,7 @@ func TestRefreshTokenInvalidation(t *testing.T) { }) bs, err := io.ReadAll(req.Body) - assert.NoError(t, err) + require.NoError(t, err) req.Body = io.NopCloser(bytes.NewReader(bs)) MakeRequest(t, req, http.StatusOK) @@ -484,7 +485,7 @@ func TestRefreshTokenInvalidation(t *testing.T) { req.Body = io.NopCloser(bytes.NewReader(bs)) resp = MakeRequest(t, req, http.StatusBadRequest) parsedError = new(auth.AccessTokenError) - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), parsedError)) assert.Equal(t, "unauthorized_client", string(parsedError.ErrorCode)) assert.Equal(t, "token was already used", parsedError.ErrorDescription) } @@ -527,7 +528,7 @@ func TestSignInOAuthCallbackSignIn(t *testing.T) { })() req := NewRequest(t, "GET", fmt.Sprintf("/user/oauth2/%s/callback?code=XYZ&state=XYZ", gitlabName)) resp := MakeRequest(t, req, http.StatusSeeOther) - assert.Equal(t, test.RedirectURL(resp), "/") + assert.Equal(t, "/", test.RedirectURL(resp)) userAfterLogin := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userGitLab.ID}) assert.Greater(t, userAfterLogin.LastLoginUnix, userGitLab.LastLoginUnix) } @@ -557,7 +558,7 @@ func TestSignInOAuthCallbackWithoutPKCEWhenUnsupported(t *testing.T) { req := NewRequest(t, "GET", fmt.Sprintf("/user/oauth2/%s", gitlabName)) resp := session.MakeRequest(t, req, http.StatusTemporaryRedirect) dest, err := url.Parse(resp.Header().Get("Location")) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, dest.Query().Get("code_challenge_method")) assert.Empty(t, dest.Query().Get("code_challenge")) @@ -599,7 +600,7 @@ func TestSignInOAuthCallbackPKCE(t *testing.T) { req := NewRequest(t, "GET", fmt.Sprintf("/user/oauth2/%s", sourceName)) resp := session.MakeRequest(t, req, http.StatusTemporaryRedirect) dest, err := url.Parse(resp.Header().Get("Location")) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "S256", dest.Query().Get("code_challenge_method")) codeChallenge := dest.Query().Get("code_challenge") assert.NotEmpty(t, codeChallenge) @@ -709,7 +710,7 @@ func TestSignUpViaOAuthWithMissingFields(t *testing.T) { })() req := NewRequest(t, "GET", fmt.Sprintf("/user/oauth2/%s/callback?code=XYZ&state=XYZ", gitlabName)) resp := MakeRequest(t, req, http.StatusSeeOther) - assert.Equal(t, test.RedirectURL(resp), "/user/link_account") + assert.Equal(t, "/user/link_account", test.RedirectURL(resp)) } func TestOAuth_GrantApplicationOAuth(t *testing.T) { diff --git a/tests/integration/org_count_test.go b/tests/integration/org_count_test.go index 6386f53f05..e3de9257f0 100644 --- a/tests/integration/org_count_test.go +++ b/tests/integration/org_count_test.go @@ -16,6 +16,7 @@ import ( api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestOrgCounts(t *testing.T) { @@ -122,7 +123,7 @@ func doCheckOrgCounts(username string, orgCounts map[string]int, strict bool, ca UserID: user.ID, IncludePrivate: true, }) - assert.NoError(t, err) + require.NoError(t, err) calcOrgCounts := map[string]int{} @@ -130,7 +131,7 @@ func doCheckOrgCounts(username string, orgCounts map[string]int, strict bool, ca calcOrgCounts[org.LowerName] = org.NumRepos count, ok := canonicalCounts[org.LowerName] if ok { - assert.True(t, count == org.NumRepos, "Number of Repos in %s is %d when we expected %d", org.Name, org.NumRepos, count) + assert.Equal(t, count, org.NumRepos, "Number of Repos in %s is %d when we expected %d", org.Name, org.NumRepos, count) } else { assert.False(t, strict, "Did not expect to see %s with count %d", org.Name, org.NumRepos) } diff --git a/tests/integration/org_team_invite_test.go b/tests/integration/org_team_invite_test.go index 919769a61a..d04199a2c1 100644 --- a/tests/integration/org_team_invite_test.go +++ b/tests/integration/org_team_invite_test.go @@ -19,6 +19,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestOrgTeamEmailInvite(t *testing.T) { @@ -34,7 +35,7 @@ func TestOrgTeamEmailInvite(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) isMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isMember) session := loginUser(t, "user1") @@ -52,7 +53,7 @@ func TestOrgTeamEmailInvite(t *testing.T) { // get the invite token invites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, invites, 1) session = loginUser(t, user.Name) @@ -68,7 +69,7 @@ func TestOrgTeamEmailInvite(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) isMember, err = organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isMember) } @@ -86,7 +87,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) isMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isMember) // create the invite @@ -104,7 +105,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) { // get the invite token invites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, invites, 1) // accept the invite @@ -132,7 +133,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) { session = emptyTestSession(t) baseURL, err := url.Parse(setting.AppURL) - assert.NoError(t, err) + require.NoError(t, err) session.jar.SetCookies(baseURL, cr.Cookies()) // make the request @@ -144,7 +145,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) isMember, err = organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isMember) } @@ -175,7 +176,7 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) { // get the invite token invites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, invites, 1) // accept the invite @@ -205,7 +206,7 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) { session = emptyTestSession(t) baseURL, err := url.Parse(setting.AppURL) - assert.NoError(t, err) + require.NoError(t, err) session.jar.SetCookies(baseURL, cr.Cookies()) // make the redirected request @@ -218,10 +219,10 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) { // get the new user newUser, err := user_model.GetUserByName(db.DefaultContext, "doesnotexist") - assert.NoError(t, err) + require.NoError(t, err) isMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, newUser.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isMember) } @@ -258,7 +259,7 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) { // get the invite token invites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, invites, 1) // accept the invite @@ -281,7 +282,7 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) { resp = MakeRequest(t, req, http.StatusOK) user, err := user_model.GetUserByName(db.DefaultContext, "doesnotexist") - assert.NoError(t, err) + require.NoError(t, err) ch := http.Header{} ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";")) @@ -289,7 +290,7 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) { session = emptyTestSession(t) baseURL, err := url.Parse(setting.AppURL) - assert.NoError(t, err) + require.NoError(t, err) session.jar.SetCookies(baseURL, cr.Cookies()) activateURL := fmt.Sprintf("/user/activate?code=%s", user.GenerateEmailActivateCode("doesnotexist@example.com")) @@ -314,7 +315,7 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) isMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isMember) } @@ -334,7 +335,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) { user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) isMember, err := organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, isMember) // create the invite @@ -352,7 +353,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) { // get the invite token invites, err := organization.GetInvitesByTeamID(db.DefaultContext, team.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, invites, 1) // note: the invited user has logged in @@ -373,6 +374,6 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) { session.MakeRequest(t, req, http.StatusOK) isMember, err = organization.IsTeamMember(db.DefaultContext, team.OrgID, team.ID, user.ID) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, isMember) } diff --git a/tests/integration/project_test.go b/tests/integration/project_test.go index 09f47baae8..fc2986e1eb 100644 --- a/tests/integration/project_test.go +++ b/tests/integration/project_test.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPrivateRepoProject(t *testing.T) { @@ -41,18 +42,18 @@ func TestMoveRepoProjectColumns(t *testing.T) { TemplateType: project_model.TemplateTypeNone, } err := project_model.NewProject(db.DefaultContext, &project1) - assert.NoError(t, err) + require.NoError(t, err) for i := 0; i < 3; i++ { err = project_model.NewColumn(db.DefaultContext, &project_model.Column{ Title: fmt.Sprintf("column %d", i+1), ProjectID: project1.ID, }) - assert.NoError(t, err) + require.NoError(t, err) } 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) assert.EqualValues(t, 1, columns[1].Sorting) @@ -73,11 +74,11 @@ func TestMoveRepoProjectColumns(t *testing.T) { sess.MakeRequest(t, req, http.StatusOK) columnsAfter, err := project1.GetColumns(db.DefaultContext) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, columns, 3) assert.EqualValues(t, columns[1].ID, columnsAfter[0].ID) assert.EqualValues(t, columns[2].ID, columnsAfter[1].ID) assert.EqualValues(t, columns[0].ID, columnsAfter[2].ID) - assert.NoError(t, project_model.DeleteProjectByID(db.DefaultContext, project1.ID)) + require.NoError(t, project_model.DeleteProjectByID(db.DefaultContext, project1.ID)) } diff --git a/tests/integration/pull_create_test.go b/tests/integration/pull_create_test.go index fd98a3f05c..c042a75753 100644 --- a/tests/integration/pull_create_test.go +++ b/tests/integration/pull_create_test.go @@ -27,6 +27,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testPullCreate(t *testing.T, session *TestSession, user, repo string, toSelf bool, targetBranch, sourceBranch, title string) *httptest.ResponseRecorder { @@ -167,7 +168,7 @@ func TestPullCreateWithPullTemplate(t *testing.T) { // Apply a change to the fork err := createOrReplaceFileInBranch(forkUser, forkedRepo, "README.md", forkedRepo.DefaultBranch, fmt.Sprintf("Hello, World (%d)\n", i)) - assert.NoError(t, err) + require.NoError(t, err) testPullPreview(t, session, forkUser.Name, forkedRepo.Name, message+" "+template) }) @@ -188,7 +189,7 @@ func TestPullCreateWithPullTemplate(t *testing.T) { // Apply a change to the fork err := createOrReplaceFileInBranch(forkUser, forkedRepo, "README.md", forkedRepo.DefaultBranch, "Hello, World (%d)\n") - assert.NoError(t, err) + require.NoError(t, err) // Unlike issues, where all candidates are considered and shown, for // pull request, there's a priority: if there are multiple @@ -226,10 +227,10 @@ func TestPullCreate_TitleEscape(t *testing.T) { resp = session.MakeRequest(t, req, http.StatusOK) htmlDoc = NewHTMLParser(t, resp.Body) titleHTML, err := htmlDoc.doc.Find(".comment-list .timeline-item.event .text b").First().Html() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "<i>XSS PR</i>", titleHTML) titleHTML, err = htmlDoc.doc.Find(".comment-list .timeline-item.event .text b").Next().Html() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "<u>XSS PR</u>", titleHTML) }) } @@ -300,9 +301,9 @@ func TestRecentlyPushed(t *testing.T) { testEditFile(t, session, "user2", "repo1", "recent-push-base", "README.md", "Hello, recently, from base!\n") baseRepo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") - assert.NoError(t, err) + require.NoError(t, err) repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user1", "repo1") - assert.NoError(t, err) + require.NoError(t, err) enablePRs := func(t *testing.T, repo *repo_model.Repository) { t.Helper() @@ -313,7 +314,7 @@ func TestRecentlyPushed(t *testing.T) { Type: unit_model.TypePullRequests, }}, nil) - assert.NoError(t, err) + require.NoError(t, err) } disablePRs := func(t *testing.T, repo *repo_model.Repository) { @@ -321,7 +322,7 @@ func TestRecentlyPushed(t *testing.T) { err := repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, nil, []unit_model.Type{unit_model.TypePullRequests}) - assert.NoError(t, err) + require.NoError(t, err) } testBanner := func(t *testing.T) { @@ -459,20 +460,20 @@ func TestRecentlyPushed(t *testing.T) { // 1. Create a new Tree object cmd := git.NewCommand(db.DefaultContext, "write-tree") treeID, _, gitErr := cmd.RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) - assert.NoError(t, gitErr) + require.NoError(t, gitErr) treeID = strings.TrimSpace(treeID) // 2. Create a new (empty) commit cmd = git.NewCommand(db.DefaultContext, "commit-tree", "-m", "Initial orphan commit").AddDynamicArguments(treeID) commitID, _, gitErr := cmd.RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) - assert.NoError(t, gitErr) + require.NoError(t, gitErr) commitID = strings.TrimSpace(commitID) // 3. Create a new ref pointing to the orphaned commit cmd = git.NewCommand(db.DefaultContext, "update-ref", "refs/heads/orphan1").AddDynamicArguments(commitID) _, _, gitErr = cmd.RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) - assert.NoError(t, gitErr) + require.NoError(t, gitErr) // 4. Sync the git repo to the database syncErr := repo_service.AddAllRepoBranchesToSyncQueue(graceful.GetManager().ShutdownContext()) - assert.NoError(t, syncErr) + require.NoError(t, syncErr) // 5. Add a fresh commit, so that FindRecentlyPushedBranches has // something to find. owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: "user1"}) @@ -489,7 +490,7 @@ func TestRecentlyPushed(t *testing.T) { OldBranch: "orphan1", NewBranch: "orphan1", }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, changeResp) // Check that we only have 1 message on the main repo, the orphaned diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index 93bd89afdb..b13ae60c45 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -44,6 +44,7 @@ import ( webhook_service "code.gitea.io/gitea/services/webhook" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) type optionsPullMerge map[string]string @@ -122,11 +123,11 @@ func retrieveHookTasks(t *testing.T, hookID int64, activateWebhook bool) []*webh webhook_service.Init() assert.Equal(t, int64(1), updated) - assert.NoError(t, err) + require.NoError(t, err) } hookTasks, err := webhook.HookTasks(db.DefaultContext, hookID, 1) - assert.NoError(t, err) + require.NoError(t, err) return hookTasks } @@ -298,14 +299,14 @@ func TestCantMergeConflict(t *testing.T) { }) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo1) - assert.NoError(t, err) + require.NoError(t, err) err = pull.Merge(context.Background(), pr, user1, gitRepo, repo_model.MergeStyleMerge, "", "CONFLICT", false) - assert.Error(t, err, "Merge should return an error due to conflict") + require.Error(t, err, "Merge should return an error due to conflict") assert.True(t, models.IsErrMergeConflicts(err), "Merge error is not a conflict error") err = pull.Merge(context.Background(), pr, user1, gitRepo, repo_model.MergeStyleRebase, "", "CONFLICT", false) - assert.Error(t, err, "Merge should return an error due to conflict") + require.Error(t, err, "Merge should return an error due to conflict") assert.True(t, models.IsErrRebaseConflicts(err), "Merge error is not a conflict error") gitRepo.Close() }) @@ -329,7 +330,7 @@ func TestCantMergeUnrelated(t *testing.T) { path := repo_model.RepoPath(user1.Name, repo1.Name) err := git.NewCommand(git.DefaultContext, "read-tree", "--empty").Run(&git.RunOpts{Dir: path}) - assert.NoError(t, err) + require.NoError(t, err) stdin := bytes.NewBufferString("Unrelated File") var stdout strings.Builder @@ -339,14 +340,14 @@ func TestCantMergeUnrelated(t *testing.T) { Stdout: &stdout, }) - assert.NoError(t, err) + require.NoError(t, err) sha := strings.TrimSpace(stdout.String()) _, _, err = git.NewCommand(git.DefaultContext, "update-index", "--add", "--replace", "--cacheinfo").AddDynamicArguments("100644", sha, "somewher-over-the-rainbow").RunStdString(&git.RunOpts{Dir: path}) - assert.NoError(t, err) + require.NoError(t, err) treeSha, _, err := git.NewCommand(git.DefaultContext, "write-tree").RunStdString(&git.RunOpts{Dir: path}) - assert.NoError(t, err) + require.NoError(t, err) treeSha = strings.TrimSpace(treeSha) commitTimeStr := time.Now().Format(time.RFC3339) @@ -372,11 +373,11 @@ func TestCantMergeUnrelated(t *testing.T) { Stdin: messageBytes, Stdout: &stdout, }) - assert.NoError(t, err) + require.NoError(t, err) commitSha := strings.TrimSpace(stdout.String()) _, _, err = git.NewCommand(git.DefaultContext, "branch", "unrelated").AddDynamicArguments(commitSha).RunStdString(&git.RunOpts{Dir: path}) - assert.NoError(t, err) + require.NoError(t, err) testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n") @@ -391,7 +392,7 @@ func TestCantMergeUnrelated(t *testing.T) { // Now this PR could be marked conflict - or at least a race may occur - so drop down to pure code at this point... gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo1) - assert.NoError(t, err) + require.NoError(t, err) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ HeadRepoID: repo1.ID, BaseRepoID: repo1.ID, @@ -400,7 +401,7 @@ func TestCantMergeUnrelated(t *testing.T) { }) err = pull.Merge(context.Background(), pr, user1, gitRepo, repo_model.MergeStyleMerge, "", "UNRELATED", false) - assert.Error(t, err, "Merge should return an error due to unrelated") + require.Error(t, err, "Merge should return an error due to unrelated") assert.True(t, models.IsErrMergeUnrelatedHistories(err), "Merge error is not a unrelated histories error") gitRepo.Close() }) @@ -437,11 +438,11 @@ func TestFastForwardOnlyMerge(t *testing.T) { }) gitRepo, err := git.OpenRepository(git.DefaultContext, repo_model.RepoPath(user1.Name, repo1.Name)) - assert.NoError(t, err) + require.NoError(t, err) err = pull.Merge(context.Background(), pr, user1, gitRepo, repo_model.MergeStyleFastForwardOnly, "", "FAST-FORWARD-ONLY", false) - assert.NoError(t, err) + require.NoError(t, err) gitRepo.Close() }) @@ -479,11 +480,11 @@ func TestCantFastForwardOnlyMergeDiverging(t *testing.T) { }) gitRepo, err := git.OpenRepository(git.DefaultContext, repo_model.RepoPath(user1.Name, repo1.Name)) - assert.NoError(t, err) + require.NoError(t, err) err = pull.Merge(context.Background(), pr, user1, gitRepo, repo_model.MergeStyleFastForwardOnly, "", "DIVERGING", false) - assert.Error(t, err, "Merge should return an error due to being for a diverging branch") + require.Error(t, err, "Merge should return an error due to being for a diverging branch") assert.True(t, models.IsErrMergeDivergingFastForwardOnly(err), "Merge error is not a diverging fast-forward-only error") gitRepo.Close() @@ -511,7 +512,7 @@ func TestConflictChecking(t *testing.T) { OldBranch: "main", NewBranch: "important-secrets", }) - assert.NoError(t, err) + require.NoError(t, err) // create a commit on main branch. _, err = files_service.ChangeRepoFiles(git.DefaultContext, baseRepo, user, &files_service.ChangeRepoFilesOptions{ @@ -526,7 +527,7 @@ func TestConflictChecking(t *testing.T) { OldBranch: "main", NewBranch: "main", }) - assert.NoError(t, err) + require.NoError(t, err) // create Pull to merge the important-secrets branch into main branch. pullIssue := &issues_model.Issue{ @@ -547,10 +548,10 @@ func TestConflictChecking(t *testing.T) { Type: issues_model.PullRequestGitea, } err = pull.NewPullRequest(git.DefaultContext, baseRepo, pullIssue, nil, nil, pullRequest, nil) - assert.NoError(t, err) + require.NoError(t, err) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: "PR with conflict!"}) - assert.NoError(t, issue.LoadPullRequest(db.DefaultContext)) + require.NoError(t, issue.LoadPullRequest(db.DefaultContext)) conflictingPR := issue.PullRequest // Ensure conflictedFiles is populated. @@ -630,7 +631,7 @@ func TestPullMergeIndexerNotifier(t *testing.T) { testEditFile(t, session, "user1", "repo1", "master", "README.md", "Hello, World (Edited)\n") createPullResp := testPullCreate(t, session, "user1", "repo1", false, "master", "master", "Indexer notifier test pull") - assert.NoError(t, queue.GetManager().FlushAll(context.Background(), 0)) + require.NoError(t, queue.GetManager().FlushAll(context.Background(), 0)) time.Sleep(time.Second) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ @@ -656,7 +657,7 @@ func TestPullMergeIndexerNotifier(t *testing.T) { searchIssuesResp := session.MakeRequest(t, NewRequest(t, "GET", link.String()), http.StatusOK) var apiIssuesBefore []*api.Issue DecodeJSON(t, searchIssuesResp, &apiIssuesBefore) - assert.Len(t, apiIssuesBefore, 0) + assert.Empty(t, apiIssuesBefore) // merge the pull request elem := strings.Split(test.RedirectURL(createPullResp), "/") @@ -669,7 +670,7 @@ func TestPullMergeIndexerNotifier(t *testing.T) { }) assert.True(t, issue.IsClosed) - assert.NoError(t, queue.GetManager().FlushAll(context.Background(), 0)) + require.NoError(t, queue.GetManager().FlushAll(context.Background(), 0)) time.Sleep(time.Second) // search issues again @@ -684,16 +685,16 @@ func TestPullMergeIndexerNotifier(t *testing.T) { func testResetRepo(t *testing.T, repoPath, branch, commitID string) { f, err := os.OpenFile(filepath.Join(repoPath, "refs", "heads", branch), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o644) - assert.NoError(t, err) + require.NoError(t, err) _, err = f.WriteString(commitID + "\n") - assert.NoError(t, err) + require.NoError(t, err) f.Close() repo, err := git.OpenRepository(context.Background(), repoPath) - assert.NoError(t, err) + require.NoError(t, err) defer repo.Close() id, err := repo.GetBranchCommitID(branch) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, commitID, id) } @@ -832,10 +833,10 @@ func TestPullMergeBranchProtect(t *testing.T) { ctx.Username = owner ctx.Reponame = repo _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", testCase.filename) - assert.NoError(t, err) + require.NoError(t, err) doGitPushTestRepository(dstPath, "origin", branch+":"+unprotected)(t) pr, err := doAPICreatePullRequest(ctx, owner, repo, branch, unprotected)(t) - assert.NoError(t, err) + require.NoError(t, err) mergeWith(t, ctx, withAPIOrWeb, testCase.expectedCode[withAPIOrWeb], pr.Index) }) } @@ -879,12 +880,12 @@ func TestPullAutoMergeAfterCommitStatusSucceed(t *testing.T) { // first time insert automerge record, return true scheduled, err := automerge.ScheduleAutoMerge(db.DefaultContext, user1, pr, repo_model.MergeStyleMerge, "auto merge test") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, scheduled) // second time insert automerge record, return false because it does exist scheduled, err = automerge.ScheduleAutoMerge(db.DefaultContext, user1, pr, repo_model.MergeStyleMerge, "auto merge test") - assert.Error(t, err) + require.Error(t, err) assert.False(t, scheduled) // reload pr again @@ -894,14 +895,14 @@ func TestPullAutoMergeAfterCommitStatusSucceed(t *testing.T) { // update commit status to success, then it should be merged automatically baseGitRepo, err := gitrepo.OpenRepository(db.DefaultContext, baseRepo) - assert.NoError(t, err) + require.NoError(t, err) sha, err := baseGitRepo.GetRefCommitID(pr.GetGitRefName()) - assert.NoError(t, err) + require.NoError(t, err) masterCommitID, err := baseGitRepo.GetBranchCommitID("master") - assert.NoError(t, err) + require.NoError(t, err) branches, _, err := baseGitRepo.GetBranchNames(0, 100) - assert.NoError(t, err) + require.NoError(t, err) assert.ElementsMatch(t, []string{"sub-home-md-img-check", "home-md-img-check", "pr-to-update", "branch2", "DefaultBranch", "develop", "feature/1", "master"}, branches) baseGitRepo.Close() defer func() { @@ -913,7 +914,7 @@ func TestPullAutoMergeAfterCommitStatusSucceed(t *testing.T) { TargetURL: "https://gitea.com", Context: "gitea/actions", }) - assert.NoError(t, err) + require.NoError(t, err) time.Sleep(2 * time.Second) @@ -963,12 +964,12 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApproval(t *testing.T) { // first time insert automerge record, return true scheduled, err := automerge.ScheduleAutoMerge(db.DefaultContext, user1, pr, repo_model.MergeStyleMerge, "auto merge test") - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, scheduled) // second time insert automerge record, return false because it does exist scheduled, err = automerge.ScheduleAutoMerge(db.DefaultContext, user1, pr, repo_model.MergeStyleMerge, "auto merge test") - assert.Error(t, err) + require.Error(t, err) assert.False(t, scheduled) // reload pr again @@ -978,11 +979,11 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApproval(t *testing.T) { // update commit status to success, then it should be merged automatically baseGitRepo, err := gitrepo.OpenRepository(db.DefaultContext, baseRepo) - assert.NoError(t, err) + require.NoError(t, err) sha, err := baseGitRepo.GetRefCommitID(pr.GetGitRefName()) - assert.NoError(t, err) + require.NoError(t, err) masterCommitID, err := baseGitRepo.GetBranchCommitID("master") - assert.NoError(t, err) + require.NoError(t, err) baseGitRepo.Close() defer func() { testResetRepo(t, baseRepo.RepoPath(), "master", masterCommitID) @@ -993,7 +994,7 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApproval(t *testing.T) { TargetURL: "https://gitea.com", Context: "gitea/actions", }) - assert.NoError(t, err) + require.NoError(t, err) time.Sleep(2 * time.Second) diff --git a/tests/integration/pull_reopen_test.go b/tests/integration/pull_reopen_test.go index 8faba5e742..ff86f80f46 100644 --- a/tests/integration/pull_reopen_test.go +++ b/tests/integration/pull_reopen_test.go @@ -28,6 +28,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPullrequestReopen(t *testing.T) { @@ -66,14 +67,14 @@ func TestPullrequestReopen(t *testing.T) { Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) // Create an head repository. headRepo, err := repo_service.ForkRepository(git.DefaultContext, user2, org26, repo_service.ForkRepoOptions{ BaseRepo: baseRepo, Name: "reopen-head", }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, headRepo) // Add a change to the head repository, so a pull request can be opened. @@ -101,7 +102,7 @@ func TestPullrequestReopen(t *testing.T) { Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) // Create the pull request. pullIssue := &issues_model.Issue{ @@ -121,13 +122,13 @@ func TestPullrequestReopen(t *testing.T) { Type: issues_model.PullRequestGitea, } err = pull_service.NewPullRequest(git.DefaultContext, baseRepo, pullIssue, nil, nil, pullRequest, nil) - assert.NoError(t, err) + require.NoError(t, err) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: "Testing reopen functionality"}) // Close the PR. err = issue_service.ChangeStatus(db.DefaultContext, issue, user2, "", true) - assert.NoError(t, err) + require.NoError(t, err) session := loginUser(t, "user2") diff --git a/tests/integration/pull_review_test.go b/tests/integration/pull_review_test.go index db1fb7ef15..314e614092 100644 --- a/tests/integration/pull_review_test.go +++ b/tests/integration/pull_review_test.go @@ -27,6 +27,7 @@ import ( "github.com/PuerkitoBio/goquery" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPullView_ReviewerMissed(t *testing.T) { @@ -45,9 +46,9 @@ func TestPullView_ReviewerMissed(t *testing.T) { reviews, err := issues_model.FindReviews(db.DefaultContext, issues_model.FindReviewOptions{ IssueID: 2, }) - assert.NoError(t, err) + require.NoError(t, err) for _, r := range reviews { - assert.NoError(t, issues_model.DeleteReview(db.DefaultContext, r)) + require.NoError(t, issues_model.DeleteReview(db.DefaultContext, r)) } req = NewRequest(t, "GET", "/user2/repo1/pulls/2") resp = session.MakeRequest(t, req, http.StatusOK) @@ -57,7 +58,7 @@ func TestPullView_ReviewerMissed(t *testing.T) { func loadComment(t *testing.T, commentID string) *issues_model.Comment { t.Helper() id, err := strconv.ParseInt(commentID, 10, 64) - assert.NoError(t, err) + require.NoError(t, err) return unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: id}) } @@ -107,7 +108,7 @@ func TestPullView_ResolveInvalidatedReviewComment(t *testing.T) { // (to invalidate it properly, one should push a commit which should trigger this logic, // in the meantime, use this quick-and-dirty trick) comment := loadComment(t, commentID) - assert.NoError(t, issues_model.UpdateCommentInvalidate(context.Background(), &issues_model.Comment{ + require.NoError(t, issues_model.UpdateCommentInvalidate(context.Background(), &issues_model.Comment{ ID: comment.ID, Invalidated: true, })) @@ -169,7 +170,7 @@ func TestPullView_ResolveInvalidatedReviewComment(t *testing.T) { // (to invalidate it properly, one should push a commit which should trigger this logic, // in the meantime, use this quick-and-dirty trick) comment := loadComment(t, commentID) - assert.NoError(t, issues_model.UpdateCommentInvalidate(context.Background(), &issues_model.Comment{ + require.NoError(t, issues_model.UpdateCommentInvalidate(context.Background(), &issues_model.Comment{ ID: comment.ID, Invalidated: true, })) @@ -289,7 +290,7 @@ func TestPullView_CodeOwner(t *testing.T) { ObjectFormatName: git.Sha1ObjectFormat.Name(), DefaultBranch: "master", }) - assert.NoError(t, err) + require.NoError(t, err) // add CODEOWNERS to default branch _, err = files_service.ChangeRepoFiles(db.DefaultContext, repo, user2, &files_service.ChangeRepoFilesOptions{ @@ -302,7 +303,7 @@ func TestPullView_CodeOwner(t *testing.T) { }, }, }) - assert.NoError(t, err) + require.NoError(t, err) t.Run("First Pull Request", func(t *testing.T) { // create a new branch to prepare for pull request @@ -316,7 +317,7 @@ func TestPullView_CodeOwner(t *testing.T) { }, }, }) - assert.NoError(t, err) + require.NoError(t, err) // Create a pull request. session := loginUser(t, "user2") @@ -324,18 +325,18 @@ func TestPullView_CodeOwner(t *testing.T) { pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{BaseRepoID: repo.ID, HeadRepoID: repo.ID, HeadBranch: "codeowner-basebranch"}) unittest.AssertExistsIf(t, true, &issues_model.Review{IssueID: pr.IssueID, Type: issues_model.ReviewTypeRequest, ReviewerID: 5}) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + require.NoError(t, pr.LoadIssue(db.DefaultContext)) err := issue_service.ChangeTitle(db.DefaultContext, pr.Issue, user2, "[WIP] Test Pull Request") - assert.NoError(t, err) + require.NoError(t, err) prUpdated1 := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID}) - assert.NoError(t, prUpdated1.LoadIssue(db.DefaultContext)) + require.NoError(t, prUpdated1.LoadIssue(db.DefaultContext)) assert.EqualValues(t, "[WIP] Test Pull Request", prUpdated1.Issue.Title) err = issue_service.ChangeTitle(db.DefaultContext, prUpdated1.Issue, user2, "Test Pull Request2") - assert.NoError(t, err) + require.NoError(t, err) prUpdated2 := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID}) - assert.NoError(t, prUpdated2.LoadIssue(db.DefaultContext)) + require.NoError(t, prUpdated2.LoadIssue(db.DefaultContext)) assert.EqualValues(t, "Test Pull Request2", prUpdated2.Issue.Title) }) @@ -349,7 +350,7 @@ func TestPullView_CodeOwner(t *testing.T) { }, }, }) - assert.NoError(t, err) + require.NoError(t, err) t.Run("Second Pull Request", func(t *testing.T) { // create a new branch to prepare for pull request @@ -363,7 +364,7 @@ func TestPullView_CodeOwner(t *testing.T) { }, }, }) - assert.NoError(t, err) + require.NoError(t, err) // Create a pull request. session := loginUser(t, "user2") @@ -379,7 +380,7 @@ func TestPullView_CodeOwner(t *testing.T) { BaseRepo: repo, Name: "test_codeowner_fork", }) - assert.NoError(t, err) + require.NoError(t, err) // create a new branch to prepare for pull request _, err = files_service.ChangeRepoFiles(db.DefaultContext, forkedRepo, user5, &files_service.ChangeRepoFilesOptions{ @@ -392,7 +393,7 @@ func TestPullView_CodeOwner(t *testing.T) { }, }, }) - assert.NoError(t, err) + require.NoError(t, err) session := loginUser(t, "user5") testPullCreate(t, session, "user5", "test_codeowner_fork", false, forkedRepo.DefaultBranch, "codeowner-basebranch-forked", "Test Pull Request2") diff --git a/tests/integration/pull_update_test.go b/tests/integration/pull_update_test.go index d59d2641f5..558c2f794c 100644 --- a/tests/integration/pull_update_test.go +++ b/tests/integration/pull_update_test.go @@ -21,6 +21,7 @@ import ( files_service "code.gitea.io/gitea/services/repository/files" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestAPIPullUpdate(t *testing.T) { @@ -32,11 +33,11 @@ func TestAPIPullUpdate(t *testing.T) { // Test GetDiverging diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, diffCount.Behind) assert.EqualValues(t, 1, diffCount.Ahead) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + require.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) + require.NoError(t, pr.LoadIssue(db.DefaultContext)) session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) @@ -46,7 +47,7 @@ func TestAPIPullUpdate(t *testing.T) { // Test GetDiverging after update diffCount, err = pull_service.GetDiverging(git.DefaultContext, pr) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, diffCount.Behind) assert.EqualValues(t, 2, diffCount.Ahead) }) @@ -61,11 +62,11 @@ func TestAPIPullUpdateByRebase(t *testing.T) { // Test GetDiverging diffCount, err := pull_service.GetDiverging(git.DefaultContext, pr) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 1, diffCount.Behind) assert.EqualValues(t, 1, diffCount.Ahead) - assert.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) - assert.NoError(t, pr.LoadIssue(db.DefaultContext)) + require.NoError(t, pr.LoadBaseRepo(db.DefaultContext)) + require.NoError(t, pr.LoadIssue(db.DefaultContext)) session := loginUser(t, "user2") token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) @@ -75,7 +76,7 @@ func TestAPIPullUpdateByRebase(t *testing.T) { // Test GetDiverging after update diffCount, err = pull_service.GetDiverging(git.DefaultContext, pr) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, 0, diffCount.Behind) assert.EqualValues(t, 1, diffCount.Ahead) }) @@ -89,7 +90,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_mod Name: "repo-pr-update", Description: "desc", }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, headRepo) // create a commit on base Repo @@ -117,7 +118,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_mod Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) // create a commit on head Repo _, err = files_service.ChangeRepoFiles(git.DefaultContext, headRepo, actor, &files_service.ChangeRepoFilesOptions{ @@ -144,7 +145,7 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_mod Committer: time.Now(), }, }) - assert.NoError(t, err) + require.NoError(t, err) // create Pull pullIssue := &issues_model.Issue{ @@ -164,10 +165,10 @@ func createOutdatedPR(t *testing.T, actor, forkOrg *user_model.User) *issues_mod Type: issues_model.PullRequestGitea, } err = pull_service.NewPullRequest(git.DefaultContext, baseRepo, pullIssue, nil, nil, pullRequest, nil) - assert.NoError(t, err) + require.NoError(t, err) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: "Test Pull -to-update-"}) - assert.NoError(t, issue.LoadPullRequest(db.DefaultContext)) + require.NoError(t, issue.LoadPullRequest(db.DefaultContext)) return issue.PullRequest } diff --git a/tests/integration/remote_test.go b/tests/integration/remote_test.go index d905f88a81..c59b4c7d32 100644 --- a/tests/integration/remote_test.go +++ b/tests/integration/remote_test.go @@ -18,6 +18,7 @@ import ( "github.com/markbates/goth" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRemote_MaybePromoteUserSuccess(t *testing.T) { @@ -66,15 +67,15 @@ func TestRemote_MaybePromoteUserSuccess(t *testing.T) { userAfterSignIn := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: userBeforeSignIn.ID}) // both are about the same user - assert.Equal(t, userAfterSignIn.ID, userBeforeSignIn.ID) + assert.Equal(t, userBeforeSignIn.ID, userAfterSignIn.ID) // the login time was updated, proof the login succeeded assert.Greater(t, userAfterSignIn.LastLoginUnix, userBeforeSignIn.LastLoginUnix) // the login type was promoted from Remote to OAuth2 - assert.Equal(t, userBeforeSignIn.LoginType, auth_model.Remote) - assert.Equal(t, userAfterSignIn.LoginType, auth_model.OAuth2) + assert.Equal(t, auth_model.Remote, userBeforeSignIn.LoginType) + assert.Equal(t, auth_model.OAuth2, userAfterSignIn.LoginType) // the OAuth2 email was used to set the missing user email - assert.Equal(t, userBeforeSignIn.Email, "") - assert.Equal(t, userAfterSignIn.Email, gitlabEmail) + assert.Equal(t, "", userBeforeSignIn.Email) + assert.Equal(t, gitlabEmail, userAfterSignIn.Email) } func TestRemote_MaybePromoteUserFail(t *testing.T) { @@ -94,7 +95,7 @@ func TestRemote_MaybePromoteUserFail(t *testing.T) { { promoted, reason, err := remote_service.MaybePromoteRemoteUser(ctx, &auth_model.Source{}, "", "") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, promoted) assert.Equal(t, remote_service.ReasonNotAuth2, reason) } @@ -102,7 +103,7 @@ func TestRemote_MaybePromoteUserFail(t *testing.T) { { remoteSource.Type = auth_model.OAuth2 promoted, reason, err := remote_service.MaybePromoteRemoteUser(ctx, remoteSource, "", "") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, promoted) assert.Equal(t, remote_service.ReasonBadAuth2, reason) remoteSource.Type = auth_model.Remote @@ -110,7 +111,7 @@ func TestRemote_MaybePromoteUserFail(t *testing.T) { { promoted, reason, err := remote_service.MaybePromoteRemoteUser(ctx, gitlabSource, "unknownloginname", "") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, promoted) assert.Equal(t, remote_service.ReasonLoginNameNotExists, reason) } @@ -127,7 +128,7 @@ func TestRemote_MaybePromoteUserFail(t *testing.T) { } defer createUser(context.Background(), t, remoteUser)() promoted, reason, err := remote_service.MaybePromoteRemoteUser(ctx, gitlabSource, remoteUserID, "") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, promoted) assert.Equal(t, remote_service.ReasonEmailIsSet, reason) } @@ -144,7 +145,7 @@ func TestRemote_MaybePromoteUserFail(t *testing.T) { } defer createUser(context.Background(), t, remoteUser)() promoted, reason, err := remote_service.MaybePromoteRemoteUser(ctx, gitlabSource, remoteUserID, "") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, promoted) assert.Equal(t, remote_service.ReasonNoSource, reason) } @@ -160,7 +161,7 @@ func TestRemote_MaybePromoteUserFail(t *testing.T) { } defer createUser(context.Background(), t, remoteUser)() promoted, reason, err := remote_service.MaybePromoteRemoteUser(ctx, gitlabSource, remoteUserID, "") - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, promoted) assert.Equal(t, remote_service.ReasonSourceWrongType, reason) } @@ -181,7 +182,7 @@ func TestRemote_MaybePromoteUserFail(t *testing.T) { } defer createUser(context.Background(), t, remoteUser)() promoted, reason, err := remote_service.MaybePromoteRemoteUser(ctx, unrelatedSource, remoteUserID, remoteEmail) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, promoted) assert.Equal(t, remote_service.ReasonNoMatch, reason) } @@ -198,7 +199,7 @@ func TestRemote_MaybePromoteUserFail(t *testing.T) { } defer createUser(context.Background(), t, remoteUser)() promoted, reason, err := remote_service.MaybePromoteRemoteUser(ctx, gitlabSource, remoteUserID, remoteEmail) - assert.NoError(t, err) + require.NoError(t, err) assert.True(t, promoted) assert.Equal(t, remote_service.ReasonPromoted, reason) } diff --git a/tests/integration/repo_activity_test.go b/tests/integration/repo_activity_test.go index 0b1e9939a1..824efddb52 100644 --- a/tests/integration/repo_activity_test.go +++ b/tests/integration/repo_activity_test.go @@ -20,6 +20,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepoActivity(t *testing.T) { @@ -83,13 +84,13 @@ func TestRepoActivityAllUnitsDisabled(t *testing.T) { Name: "empty-repo", AutoInit: false, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, repo) enabledUnits := make([]repo_model.RepoUnit, 0) disabledUnits := []unit_model.Type{unit_model.TypeCode, unit_model.TypeIssues, unit_model.TypePullRequests, unit_model.TypeReleases} err = repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, enabledUnits, disabledUnits) - assert.NoError(t, err) + require.NoError(t, err) req := NewRequest(t, "GET", fmt.Sprintf("%s/activity", repo.Link())) session.MakeRequest(t, req, http.StatusNotFound) @@ -113,14 +114,14 @@ func TestRepoActivityOnlyCodeUnitWithEmptyRepo(t *testing.T) { Name: "empty-repo", AutoInit: false, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, repo) enabledUnits := make([]repo_model.RepoUnit, 1) enabledUnits[0] = repo_model.RepoUnit{RepoID: repo.ID, Type: unit_model.TypeCode} disabledUnits := []unit_model.Type{unit_model.TypeIssues, unit_model.TypePullRequests, unit_model.TypeReleases} err = repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, enabledUnits, disabledUnits) - assert.NoError(t, err) + require.NoError(t, err) req := NewRequest(t, "GET", fmt.Sprintf("%s/activity", repo.Link())) session.MakeRequest(t, req, http.StatusOK) @@ -169,14 +170,14 @@ func TestRepoActivityOnlyIssuesUnit(t *testing.T) { Name: "empty-repo", AutoInit: false, }) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, repo) enabledUnits := make([]repo_model.RepoUnit, 1) enabledUnits[0] = repo_model.RepoUnit{RepoID: repo.ID, Type: unit_model.TypeIssues} disabledUnits := []unit_model.Type{unit_model.TypeCode, unit_model.TypePullRequests, unit_model.TypeReleases} err = repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, enabledUnits, disabledUnits) - assert.NoError(t, err) + require.NoError(t, err) req := NewRequest(t, "GET", fmt.Sprintf("%s/activity", repo.Link())) session.MakeRequest(t, req, http.StatusOK) diff --git a/tests/integration/repo_archive_test.go b/tests/integration/repo_archive_test.go index 664b04baf7..75fe78eeed 100644 --- a/tests/integration/repo_archive_test.go +++ b/tests/integration/repo_archive_test.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepoDownloadArchive(t *testing.T) { @@ -27,7 +28,7 @@ func TestRepoDownloadArchive(t *testing.T) { req.Header.Set("Accept-Encoding", "gzip") resp := MakeRequest(t, req, http.StatusOK) bs, err := io.ReadAll(resp.Body) - assert.NoError(t, err) + require.NoError(t, err) assert.Empty(t, resp.Header().Get("Content-Encoding")) - assert.Equal(t, 320, len(bs)) + assert.Len(t, bs, 320) } diff --git a/tests/integration/repo_badges_test.go b/tests/integration/repo_badges_test.go index 9c3006b18d..522ff94ff9 100644 --- a/tests/integration/repo_badges_test.go +++ b/tests/integration/repo_badges_test.go @@ -27,6 +27,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestBadges(t *testing.T) { @@ -130,7 +131,7 @@ func TestBadges(t *testing.T) { // Lets create a tag! owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) err := release.CreateNewTag(git.DefaultContext, owner, repo, "main", "v1", "message") - assert.NoError(t, err) + require.NoError(t, err) // Now the workflow is wating req = NewRequestf(t, "GET", "/user2/%s/actions/workflows/tag-test.yaml/badge.svg", repo.Name) @@ -239,7 +240,7 @@ func TestBadges(t *testing.T) { session := loginUser(t, repo.Owner.Name) token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository) err := release.CreateNewTag(git.DefaultContext, repo.Owner, repo, "main", "repo-name-2.0", "dash in the tag name") - assert.NoError(t, err) + require.NoError(t, err) createNewReleaseUsingAPI(t, token, repo.Owner, repo, "repo-name-2.0", "main", "dashed release", "dashed release") req := NewRequestf(t, "GET", "/user2/%s/badges/release.svg", repo.Name) diff --git a/tests/integration/repo_branch_test.go b/tests/integration/repo_branch_test.go index 7f18bc7ddf..2aa299479a 100644 --- a/tests/integration/repo_branch_test.go +++ b/tests/integration/repo_branch_test.go @@ -25,6 +25,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testCreateBranch(t testing.TB, session *TestSession, user, repo, oldRefSubURL, newBranchName string, expectedStatus int) string { @@ -177,13 +178,13 @@ func TestDatabaseMissingABranch(t *testing.T) { // Run the repo branch sync, to ensure the db and git agree. err2 := repo_service.AddAllRepoBranchesToSyncQueue(graceful.GetManager().ShutdownContext()) - assert.NoError(t, err2) + require.NoError(t, err2) // Delete one branch from git only, leaving it in the database repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) cmd := git.NewCommand(db.DefaultContext, "branch", "-D").AddDynamicArguments("will-be-missing") _, _, err := cmd.RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) - assert.NoError(t, err) + require.NoError(t, err) // Verify that loading the repo's branches page works still, and that it // reports at least three branches (master, will-be-present, and @@ -196,7 +197,7 @@ func TestDatabaseMissingABranch(t *testing.T) { // Run the repo branch sync again err2 = repo_service.AddAllRepoBranchesToSyncQueue(graceful.GetManager().ShutdownContext()) - assert.NoError(t, err2) + require.NoError(t, err2) // Verify that loading the repo's branches page works still, and that it // reports one branch less than the first time. diff --git a/tests/integration/repo_commits_test.go b/tests/integration/repo_commits_test.go index bb65d9e04a..e399898958 100644 --- a/tests/integration/repo_commits_test.go +++ b/tests/integration/repo_commits_test.go @@ -18,6 +18,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepoCommits(t *testing.T) { @@ -91,9 +92,9 @@ func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) { func testRepoCommitsWithStatus(t *testing.T, resp, respOne *httptest.ResponseRecorder, state string) { var statuses []*api.CommitStatus - assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), &statuses)) + require.NoError(t, json.Unmarshal(resp.Body.Bytes(), &statuses)) var status api.CombinedStatus - assert.NoError(t, json.Unmarshal(respOne.Body.Bytes(), &status)) + require.NoError(t, json.Unmarshal(respOne.Body.Bytes(), &status)) assert.NotNil(t, status) if assert.Len(t, statuses, 1) { diff --git a/tests/integration/repo_delete_test.go b/tests/integration/repo_delete_test.go index 10e99db444..44ef26f19a 100644 --- a/tests/integration/repo_delete_test.go +++ b/tests/integration/repo_delete_test.go @@ -15,10 +15,11 @@ import ( repo_service "code.gitea.io/gitea/services/repository" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTeam_HasRepository(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}) @@ -34,11 +35,11 @@ func TestTeam_HasRepository(t *testing.T) { } func TestTeam_RemoveRepository(t *testing.T) { - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) testSuccess := func(teamID, repoID int64) { team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) - assert.NoError(t, repo_service.RemoveRepositoryFromTeam(db.DefaultContext, team, repoID)) + require.NoError(t, repo_service.RemoveRepositoryFromTeam(db.DefaultContext, team, repoID)) unittest.AssertNotExistsBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repoID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &repo_model.Repository{ID: repoID}) } @@ -62,7 +63,7 @@ func TestDeleteOwnerRepositoriesDirectly(t *testing.T) { HookID: preservedHookID, }) - assert.NoError(t, repo_service.DeleteOwnerRepositoriesDirectly(db.DefaultContext, user)) + require.NoError(t, repo_service.DeleteOwnerRepositoriesDirectly(db.DefaultContext, user)) unittest.AssertNotExistsBean(t, &webhook_model.HookTask{ HookID: deletedHookID, diff --git a/tests/integration/repo_fork_test.go b/tests/integration/repo_fork_test.go index 7b92bcda4b..38cbc3af28 100644 --- a/tests/integration/repo_fork_test.go +++ b/tests/integration/repo_fork_test.go @@ -23,6 +23,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func testRepoFork(t *testing.T, session *TestSession, ownerName, repoName, forkOwnerName, forkRepoName string) *httptest.ResponseRecorder { @@ -150,7 +151,7 @@ func TestRepoFork(t *testing.T) { defer func() { repo_service.DeleteRepository(db.DefaultContext, user5, repo, false) }() - assert.NoError(t, err) + require.NoError(t, err) assert.NotEmpty(t, repo) // Load the repository home view diff --git a/tests/integration/repo_search_test.go b/tests/integration/repo_search_test.go index 3a68a14196..a2b4588890 100644 --- a/tests/integration/repo_search_test.go +++ b/tests/integration/repo_search_test.go @@ -17,6 +17,7 @@ import ( "github.com/PuerkitoBio/goquery" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func resultFilenames(t testing.TB, doc *HTMLDoc) []string { @@ -26,7 +27,7 @@ func resultFilenames(t testing.TB, doc *HTMLDoc) []string { result := make([]string, resultSelections.Length()) resultSelections.Each(func(i int, selection *goquery.Selection) { - assert.True(t, resultSelections.Find("div ol li").Length() > 0) + assert.Positive(t, resultSelections.Find("div ol li").Length(), 0) result[i] = selection. Find(".header"). Find("span.file a.file-link"). @@ -51,7 +52,7 @@ func testSearchRepo(t *testing.T, indexer bool) { defer test.MockVariableValue(&testWebRoutes, routers.NormalRoutes())() repo, err := repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "repo1") - assert.NoError(t, err) + require.NoError(t, err) if indexer { code_indexer.UpdateRepoIndexer(repo) @@ -70,7 +71,7 @@ func testSearchRepo(t *testing.T, indexer bool) { defer test.MockVariableValue(&setting.Indexer.ExcludePatterns, setting.IndexerGlobFromString("**/y/**"))() repo, err = repo_model.GetRepositoryByOwnerAndName(db.DefaultContext, "user2", "glob") - assert.NoError(t, err) + require.NoError(t, err) if indexer { code_indexer.UpdateRepoIndexer(repo) diff --git a/tests/integration/repo_settings_hook_test.go b/tests/integration/repo_settings_hook_test.go index 8b800c4d6b..0a3dd57160 100644 --- a/tests/integration/repo_settings_hook_test.go +++ b/tests/integration/repo_settings_hook_test.go @@ -11,6 +11,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepoSettingsHookHistory(t *testing.T) { @@ -26,7 +27,7 @@ func TestRepoSettingsHookHistory(t *testing.T) { t.Run("1/delivered", func(t *testing.T) { html, err := doc.doc.Find(".webhook div[data-tab='request-1']").Html() - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, html, "Request URL: /matrix-delivered\n") assert.Contains(t, html, "Request method: PUT") assert.Contains(t, html, "X-Head: 42") @@ -39,7 +40,7 @@ func TestRepoSettingsHookHistory(t *testing.T) { t.Run("2/undelivered", func(t *testing.T) { html, err := doc.doc.Find(".webhook div[data-tab='request-2']").Html() - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, "-", strings.TrimSpace(html)) val, ok := doc.doc.Find(".webhook div.item:has(div#info-2) svg").Attr("class") @@ -49,7 +50,7 @@ func TestRepoSettingsHookHistory(t *testing.T) { t.Run("3/success", func(t *testing.T) { html, err := doc.doc.Find(".webhook div[data-tab='request-3']").Html() - assert.NoError(t, err) + require.NoError(t, err) assert.Contains(t, html, "Request URL: /matrix-success\n") assert.Contains(t, html, "Request method: PUT") assert.Contains(t, html, "X-Head: 42") diff --git a/tests/integration/repo_settings_test.go b/tests/integration/repo_settings_test.go index 16ed444e47..6ea7ca6b3a 100644 --- a/tests/integration/repo_settings_test.go +++ b/tests/integration/repo_settings_test.go @@ -28,6 +28,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepoSettingsUnits(t *testing.T) { @@ -63,12 +64,12 @@ func TestRepoAddMoreUnitsHighlighting(t *testing.T) { setUserHints := func(t *testing.T, hints bool) func() { saved := user.EnableRepoUnitHints - assert.NoError(t, user_service.UpdateUser(db.DefaultContext, user, &user_service.UpdateOptions{ + require.NoError(t, user_service.UpdateUser(db.DefaultContext, user, &user_service.UpdateOptions{ EnableRepoUnitHints: optional.Some(hints), })) return func() { - assert.NoError(t, user_service.UpdateUser(db.DefaultContext, user, &user_service.UpdateOptions{ + require.NoError(t, user_service.UpdateUser(db.DefaultContext, user, &user_service.UpdateOptions{ EnableRepoUnitHints: optional.Some(saved), })) } @@ -178,7 +179,7 @@ func TestRepoAddMoreUnits(t *testing.T) { // Disable the Packages unit err := repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, nil, []unit_model.Type{unit_model.TypePackages}) - assert.NoError(t, err) + require.NoError(t, err) assertAddMore(t, true) }) @@ -200,7 +201,7 @@ func TestRepoAddMoreUnits(t *testing.T) { // Disable the Packages unit err := repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, nil, []unit_model.Type{unit_model.TypePackages}) - assert.NoError(t, err) + require.NoError(t, err) // The "Add more" link appears no more assertAddMore(t, false) @@ -223,7 +224,7 @@ func TestRepoAddMoreUnits(t *testing.T) { // Disable the Issues unit err := repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, nil, []unit_model.Type{unit_model.TypeIssues}) - assert.NoError(t, err) + require.NoError(t, err) // The "Add more" link appears no more assertAddMore(t, false) diff --git a/tests/integration/repo_signed_tag_test.go b/tests/integration/repo_signed_tag_test.go index a2904dc075..9b6188ef95 100644 --- a/tests/integration/repo_signed_tag_test.go +++ b/tests/integration/repo_signed_tag_test.go @@ -21,7 +21,7 @@ import ( api "code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/tests" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestRepoSSHSignedTags(t *testing.T) { @@ -35,13 +35,13 @@ func TestRepoSSHSignedTags(t *testing.T) { // Set up an SSH key for the tagger tmpDir := t.TempDir() err := os.Chmod(tmpDir, 0o700) - assert.NoError(t, err) + require.NoError(t, err) signingKey := fmt.Sprintf("%s/ssh_key", tmpDir) cmd := exec.Command("ssh-keygen", "-t", "ed25519", "-N", "", "-f", signingKey) err = cmd.Run() - assert.NoError(t, err) + require.NoError(t, err) // Set up git config for the tagger _ = git.NewCommand(git.DefaultContext, "config", "user.name").AddDynamicArguments(user.Name).Run(&git.RunOpts{Dir: repo.RepoPath()}) @@ -55,7 +55,7 @@ func TestRepoSSHSignedTags(t *testing.T) { // Create a signed tag err = git.NewCommand(git.DefaultContext, "tag", "-s", "-m", "this is a signed tag", "ssh-signed-tag").Run(&git.RunOpts{Dir: repo.RepoPath()}) - assert.NoError(t, err) + require.NoError(t, err) // Sync the tag to the DB repo_module.SyncRepoTags(graceful.GetManager().ShutdownContext(), repo.ID) @@ -83,7 +83,7 @@ func TestRepoSSHSignedTags(t *testing.T) { // Upload the signing key keyData, err := os.ReadFile(fmt.Sprintf("%s.pub", signingKey)) - assert.NoError(t, err) + require.NoError(t, err) key := string(keyData) session := loginUser(t, user.Name) diff --git a/tests/integration/repo_starwatch_test.go b/tests/integration/repo_starwatch_test.go index d1ba2dbf0a..ecab75847a 100644 --- a/tests/integration/repo_starwatch_test.go +++ b/tests/integration/repo_starwatch_test.go @@ -38,7 +38,7 @@ func testRepoStarringOrWatching(t *testing.T, action, listURI string) { // Verify that the star/watch button is now the opposite htmlDoc := NewHTMLParser(t, resp.Body) actionButton := htmlDoc.Find(fmt.Sprintf("form[action='/user2/repo1/action/%s']", oppositeAction)) - assert.True(t, actionButton.Length() == 1) + assert.Equal(t, 1, actionButton.Length()) text := strings.ToLower(actionButton.Find("button span.text").Text()) assert.Equal(t, oppositeAction, text) @@ -63,7 +63,7 @@ func testRepoStarringOrWatching(t *testing.T, action, listURI string) { // Verify that the star/watch button is now back to its default htmlDoc = NewHTMLParser(t, resp.Body) actionButton = htmlDoc.Find(fmt.Sprintf("form[action='/user2/repo1/action/%s']", action)) - assert.True(t, actionButton.Length() == 1) + assert.Equal(t, 1, actionButton.Length()) text = strings.ToLower(actionButton.Find("button span.text").Text()) assert.Equal(t, action, text) diff --git a/tests/integration/repo_tag_test.go b/tests/integration/repo_tag_test.go index 273d7f713c..05bf74b73b 100644 --- a/tests/integration/repo_tag_test.go +++ b/tests/integration/repo_tag_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestTagViewWithoutRelease(t *testing.T) { @@ -35,16 +36,16 @@ func TestTagViewWithoutRelease(t *testing.T) { TagNames: []string{"no-release"}, RepoID: repo.ID, }) - assert.NoError(t, err) + require.NoError(t, err) for _, release := range releases { _, err = db.DeleteByID[repo_model.Release](db.DefaultContext, release.ID) - assert.NoError(t, err) + require.NoError(t, err) } }() err := release.CreateNewTag(git.DefaultContext, owner, repo, "master", "no-release", "release-less tag") - assert.NoError(t, err) + require.NoError(t, err) // Test that the page loads req := NewRequestf(t, "GET", "/%s/releases/tag/no-release", repo.FullName()) @@ -77,14 +78,14 @@ func TestCreateNewTagProtected(t *testing.T) { defer tests.PrintCurrentTest(t)() err := release.CreateNewTag(git.DefaultContext, owner, repo, "master", "t-first", "first tag") - assert.NoError(t, err) + require.NoError(t, err) err = release.CreateNewTag(git.DefaultContext, owner, repo, "master", "v-2", "second tag") - assert.Error(t, err) + require.Error(t, err) assert.True(t, models.IsErrProtectedTagName(err)) err = release.CreateNewTag(git.DefaultContext, owner, repo, "master", "v-1.1", "third tag") - assert.NoError(t, err) + require.NoError(t, err) }) t.Run("Git", func(t *testing.T) { @@ -99,10 +100,10 @@ func TestCreateNewTagProtected(t *testing.T) { doGitClone(dstPath, u)(t) _, _, err := git.NewCommand(git.DefaultContext, "tag", "v-2").RunStdString(&git.RunOpts{Dir: dstPath}) - assert.NoError(t, err) + require.NoError(t, err) _, _, err = git.NewCommand(git.DefaultContext, "push", "--tags").RunStdString(&git.RunOpts{Dir: dstPath}) - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, err.Error(), "Tag v-2 is protected") }) }) @@ -113,18 +114,18 @@ func TestCreateNewTagProtected(t *testing.T) { TagNames: []string{"v-1", "v-1.1"}, RepoID: repo.ID, }) - assert.NoError(t, err) + require.NoError(t, err) for _, release := range releases { _, err = db.DeleteByID[repo_model.Release](db.DefaultContext, release.ID) - assert.NoError(t, err) + require.NoError(t, err) } protectedTags, err := git_model.GetProtectedTags(db.DefaultContext, repo.ID) - assert.NoError(t, err) + require.NoError(t, err) for _, protectedTag := range protectedTags { err = git_model.DeleteProtectedTag(db.DefaultContext, protectedTag) - assert.NoError(t, err) + require.NoError(t, err) } } diff --git a/tests/integration/repo_test.go b/tests/integration/repo_test.go index 224a8e67aa..c1d2f327b4 100644 --- a/tests/integration/repo_test.go +++ b/tests/integration/repo_test.go @@ -746,7 +746,7 @@ func TestRepoHomeViewRedirect(t *testing.T) { err := repo_service.UpdateRepositoryUnits(db.DefaultContext, repo, nil, []unit_model.Type{ unit_model.TypeCode, }) - assert.NoError(t, err) + require.NoError(t, err) // The repo home should redirect to the built-in issue tracker req := NewRequest(t, "GET", "/user2/repo1") @@ -775,7 +775,7 @@ func TestRepoHomeViewRedirect(t *testing.T) { unit_model.TypePackages, unit_model.TypeActions, }) - assert.NoError(t, err) + require.NoError(t, err) // The repo home should redirect to pull requests req := NewRequest(t, "GET", "/user2/repo1") @@ -808,7 +808,7 @@ func TestRepoHomeViewRedirect(t *testing.T) { unit_model.TypeReleases, unit_model.TypeWiki, }) - assert.NoError(t, err) + require.NoError(t, err) // The repo home ends up being 404 req := NewRequest(t, "GET", "/user2/repo1") diff --git a/tests/integration/repo_topic_test.go b/tests/integration/repo_topic_test.go index 2ca8fe64cd..f5778a2861 100644 --- a/tests/integration/repo_topic_test.go +++ b/tests/integration/repo_topic_test.go @@ -77,5 +77,5 @@ func TestTopicSearchPaging(t *testing.T) { res = MakeRequest(t, NewRequest(t, "GET", "/explore/topics/search?page=2"), http.StatusOK) DecodeJSON(t, res, &topics) - assert.Greater(t, len(topics.TopicNames), 0) + assert.NotEmpty(t, topics.TopicNames) } diff --git a/tests/integration/repofiles_change_test.go b/tests/integration/repofiles_change_test.go index 7633d6915f..7f5e17c2ce 100644 --- a/tests/integration/repofiles_change_test.go +++ b/tests/integration/repofiles_change_test.go @@ -20,6 +20,7 @@ import ( files_service "code.gitea.io/gitea/services/repository/files" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func getCreateRepoFilesOptions(repo *repo_model.Repository) *files_service.ChangeRepoFilesOptions { @@ -262,7 +263,7 @@ func TestChangeRepoFilesForCreate(t *testing.T) { filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) // asserts - assert.NoError(t, err) + require.NoError(t, err) gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo) defer gitRepo.Close() @@ -299,7 +300,7 @@ func TestChangeRepoFilesForUpdate(t *testing.T) { filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) // asserts - assert.NoError(t, err) + require.NoError(t, err) gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo) defer gitRepo.Close() @@ -335,7 +336,7 @@ func TestChangeRepoFilesForUpdateWithFileMove(t *testing.T) { filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) // asserts - assert.NoError(t, err) + require.NoError(t, err) gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo) defer gitRepo.Close() @@ -351,7 +352,7 @@ func TestChangeRepoFilesForUpdateWithFileMove(t *testing.T) { t.Fatalf("expected git.ErrNotExist, got:%v", err) } toEntry, err := commit.GetTreeEntryByPath(opts.Files[0].TreePath) - assert.NoError(t, err) + require.NoError(t, err) assert.Nil(t, fromEntry) // Should no longer exist here assert.NotNil(t, toEntry) // Should exist here // assert SHA has remained the same but paths use the new file name @@ -386,7 +387,7 @@ func TestChangeRepoFilesWithoutBranchNames(t *testing.T) { filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) // asserts - assert.NoError(t, err) + require.NoError(t, err) gitRepo, _ := gitrepo.OpenRepository(git.DefaultContext, repo) defer gitRepo.Close() @@ -417,7 +418,7 @@ func testDeleteRepoFiles(t *testing.T, u *url.URL) { t.Run("Delete README.md file", func(t *testing.T) { filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) - assert.NoError(t, err) + require.NoError(t, err) expectedFileResponse := getExpectedFileResponseForRepofilesDelete() assert.NotNil(t, filesResponse) assert.Nil(t, filesResponse.Files[0]) @@ -459,7 +460,7 @@ func testDeleteRepoFilesWithoutBranchNames(t *testing.T, u *url.URL) { t.Run("Delete README.md without Branch Name", func(t *testing.T) { filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) - assert.NoError(t, err) + require.NoError(t, err) expectedFileResponse := getExpectedFileResponseForRepofilesDelete() assert.NotNil(t, filesResponse) assert.Nil(t, filesResponse.Files[0]) @@ -488,7 +489,7 @@ func TestChangeRepoFilesErrors(t *testing.T) { opts := getUpdateRepoFilesOptions(repo) opts.OldBranch = "bad_branch" filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, filesResponse) expectedError := "branch does not exist [name: " + opts.OldBranch + "]" assert.EqualError(t, err, expectedError) @@ -500,7 +501,7 @@ func TestChangeRepoFilesErrors(t *testing.T) { opts.Files[0].SHA = "bad_sha" filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) assert.Nil(t, filesResponse) - assert.Error(t, err) + require.Error(t, err) expectedError := "sha does not match [given: " + opts.Files[0].SHA + ", expected: " + origSHA + "]" assert.EqualError(t, err, expectedError) }) @@ -510,7 +511,7 @@ func TestChangeRepoFilesErrors(t *testing.T) { opts.NewBranch = "develop" filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) assert.Nil(t, filesResponse) - assert.Error(t, err) + require.Error(t, err) expectedError := "branch already exists [name: " + opts.NewBranch + "]" assert.EqualError(t, err, expectedError) }) @@ -520,7 +521,7 @@ func TestChangeRepoFilesErrors(t *testing.T) { opts.Files[0].TreePath = "" filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) assert.Nil(t, filesResponse) - assert.Error(t, err) + require.Error(t, err) expectedError := "path contains a malformed path component [path: ]" assert.EqualError(t, err, expectedError) }) @@ -530,7 +531,7 @@ func TestChangeRepoFilesErrors(t *testing.T) { opts.Files[0].TreePath = ".git" filesResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) assert.Nil(t, filesResponse) - assert.Error(t, err) + require.Error(t, err) expectedError := "path contains a malformed path component [path: " + opts.Files[0].TreePath + "]" assert.EqualError(t, err, expectedError) }) @@ -540,7 +541,7 @@ func TestChangeRepoFilesErrors(t *testing.T) { opts.Files[0].TreePath = "README.md" // already exists fileResponse, err := files_service.ChangeRepoFiles(git.DefaultContext, repo, doer, opts) assert.Nil(t, fileResponse) - assert.Error(t, err) + require.Error(t, err) expectedError := "repository file already exists [path: " + opts.Files[0].TreePath + "]" assert.EqualError(t, err, expectedError) }) diff --git a/tests/integration/session_test.go b/tests/integration/session_test.go index d47148efa2..a5bcab269a 100644 --- a/tests/integration/session_test.go +++ b/tests/integration/session_test.go @@ -12,26 +12,27 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_RegenerateSession(t *testing.T) { defer tests.PrepareTestEnv(t)() - assert.NoError(t, unittest.PrepareTestDatabase()) + require.NoError(t, unittest.PrepareTestDatabase()) key := "new_key890123456" // it must be 16 characters long key2 := "new_key890123457" // it must be 16 characters exist, err := auth.ExistSession(db.DefaultContext, key) - assert.NoError(t, err) + require.NoError(t, err) assert.False(t, exist) sess, err := auth.RegenerateSession(db.DefaultContext, "", key) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, key, sess.Key) - assert.Len(t, sess.Data, 0) + assert.Empty(t, sess.Data, 0) sess, err = auth.ReadSession(db.DefaultContext, key2) - assert.NoError(t, err) + require.NoError(t, err) assert.EqualValues(t, key2, sess.Key) - assert.Len(t, sess.Data, 0) + assert.Empty(t, sess.Data, 0) } diff --git a/tests/integration/setting_test.go b/tests/integration/setting_test.go index a82a8afef1..29615b3ecf 100644 --- a/tests/integration/setting_test.go +++ b/tests/integration/setting_test.go @@ -15,6 +15,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestSettingShowUserEmailExplore(t *testing.T) { @@ -133,7 +134,7 @@ func TestSettingSecurityAuthSource(t *testing.T) { LoginSourceID: active.ID, } err := user_model.LinkExternalToUser(db.DefaultContext, user, activeExternalLoginUser) - assert.NoError(t, err) + require.NoError(t, err) inactive := addAuthSource(t, authSourcePayloadGitLabCustom("gitlab-inactive")) inactiveExternalLoginUser := &user_model.ExternalLoginUser{ @@ -142,12 +143,12 @@ func TestSettingSecurityAuthSource(t *testing.T) { LoginSourceID: inactive.ID, } err = user_model.LinkExternalToUser(db.DefaultContext, user, inactiveExternalLoginUser) - assert.NoError(t, err) + require.NoError(t, err) // mark the authSource as inactive inactive.IsActive = false err = auth_model.UpdateSource(db.DefaultContext, inactive) - assert.NoError(t, err) + require.NoError(t, err) session := loginUser(t, "user1") req := NewRequest(t, "GET", "user/settings/security") diff --git a/tests/integration/size_translations_test.go b/tests/integration/size_translations_test.go index 1ee5f7b36f..ee03f5faa8 100644 --- a/tests/integration/size_translations_test.go +++ b/tests/integration/size_translations_test.go @@ -63,7 +63,7 @@ func TestDataSizeTranslation(t *testing.T) { // Check if repo size is translated repos := NewHTMLParser(t, resp.Body).Find(".user-setting-content .list .item .content") - assert.True(t, repos.Length() > 0) + assert.Positive(t, repos.Length()) repos.Each(func(i int, repo *goquery.Selection) { repoName := repo.Find("a.name").Text() if repoName == path.Join(testUser, testRepo.Name) { diff --git a/tests/integration/ssh_key_test.go b/tests/integration/ssh_key_test.go index cf261dc39b..ebf0d26c2d 100644 --- a/tests/integration/ssh_key_test.go +++ b/tests/integration/ssh_key_test.go @@ -17,6 +17,7 @@ import ( api "code.gitea.io/gitea/modules/structs" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func doCheckRepositoryEmptyStatus(ctx APITestContext, isEmpty bool) func(*testing.T) { @@ -27,14 +28,14 @@ func doCheckRepositoryEmptyStatus(ctx APITestContext, isEmpty bool) func(*testin func doAddChangesToCheckout(dstPath, filename string) func(*testing.T) { return func(t *testing.T) { - assert.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0o644)) - assert.NoError(t, git.AddChanges(dstPath, true)) + require.NoError(t, os.WriteFile(filepath.Join(dstPath, filename), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s at time: %v", dstPath, time.Now())), 0o644)) + require.NoError(t, git.AddChanges(dstPath, true)) signature := git.Signature{ Email: "test@example.com", Name: "test", When: time.Now(), } - assert.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{ + require.NoError(t, git.CommitChanges(dstPath, git.CommitChangesOptions{ Committer: &signature, Author: &signature, Message: "Initial Commit", diff --git a/tests/integration/user_avatar_test.go b/tests/integration/user_avatar_test.go index ec5813df0d..a5805d0eda 100644 --- a/tests/integration/user_avatar_test.go +++ b/tests/integration/user_avatar_test.go @@ -19,6 +19,7 @@ import ( "code.gitea.io/gitea/modules/avatar" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestUserAvatar(t *testing.T) { @@ -32,7 +33,7 @@ func TestUserAvatar(t *testing.T) { img, err := avatar.RandomImage([]byte(seed)) if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } @@ -48,22 +49,22 @@ func TestUserAvatar(t *testing.T) { writer.WriteField("source", "local") part, err := writer.CreateFormFile("avatar", "avatar-for-testuseravatar.png") if err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } if err := png.Encode(imgData, img); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } if _, err := io.Copy(part, imgData); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } if err := writer.Close(); err != nil { - assert.NoError(t, err) + require.NoError(t, err) return } diff --git a/tests/integration/user_profile_activity_test.go b/tests/integration/user_profile_activity_test.go index 015eeaef7e..0592523076 100644 --- a/tests/integration/user_profile_activity_test.go +++ b/tests/integration/user_profile_activity_test.go @@ -96,8 +96,7 @@ func testUser2ActivityVisibility(t *testing.T, session *TestSession, hint string // Check that the current tab is displayed and is active regardless of it's actual availability // For example, on / it wouldn't be available to guest, but it should be still present on /?tab=activity - assert.True(t, page.Find("overflow-menu .active.item[href='/user2?tab=activity']").Length() > 0) - + assert.Positive(t, page.Find("overflow-menu .active.item[href='/user2?tab=activity']").Length()) if hintLinkExists { return hintLink } diff --git a/tests/integration/user_test.go b/tests/integration/user_test.go index baf8cee82f..e5e819dfe9 100644 --- a/tests/integration/user_test.go +++ b/tests/integration/user_test.go @@ -611,7 +611,7 @@ func TestUserPronouns(t *testing.T) { htmlDoc := NewHTMLParser(t, resp.Body) userName := strings.TrimSpace(htmlDoc.Find(".profile-avatar-name .username").Text()) - assert.EqualValues(t, userName, "user2") + assert.EqualValues(t, "user2", userName) }) } diff --git a/tests/integration/webfinger_test.go b/tests/integration/webfinger_test.go index 825cffed7a..18f509aca9 100644 --- a/tests/integration/webfinger_test.go +++ b/tests/integration/webfinger_test.go @@ -48,7 +48,7 @@ func TestWebfinger(t *testing.T) { req := NewRequest(t, "GET", fmt.Sprintf("/.well-known/webfinger?resource=acct:%s@%s", user.LowerName, appURL.Host)) resp := MakeRequest(t, req, http.StatusOK) - assert.Equal(t, resp.Header().Get("Content-Type"), "application/jrd+json") + assert.Equal(t, "application/jrd+json", resp.Header().Get("Content-Type")) var jrd webfingerJRD DecodeJSON(t, resp, &jrd) diff --git a/tests/integration/webhook_test.go b/tests/integration/webhook_test.go index 4c2b42f880..60d4d48d7c 100644 --- a/tests/integration/webhook_test.go +++ b/tests/integration/webhook_test.go @@ -21,6 +21,7 @@ import ( "code.gitea.io/gitea/tests" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestWebhookPayloadRef(t *testing.T) { @@ -29,8 +30,8 @@ func TestWebhookPayloadRef(t *testing.T) { w.HookEvent = &webhook_module.HookEvent{ SendEverything: true, } - assert.NoError(t, w.UpdateEvent()) - assert.NoError(t, webhook_model.UpdateWebhook(db.DefaultContext, w)) + require.NoError(t, w.UpdateEvent()) + require.NoError(t, webhook_model.UpdateWebhook(db.DefaultContext, w)) hookTasks := retrieveHookTasks(t, w.ID, true) hookTasksLenBefore := len(hookTasks) @@ -69,7 +70,7 @@ func TestWebhookPayloadRef(t *testing.T) { var payload struct { Ref string `json:"ref"` } - assert.NoError(t, json.Unmarshal([]byte(hookTask.PayloadContent), &payload)) + require.NoError(t, json.Unmarshal([]byte(hookTask.PayloadContent), &payload)) assert.Equal(t, "refs/heads/arbre", payload.Ref, "unexpected ref for %q event", hookTask.EventType) delete(expected, hookTask.EventType) } @@ -89,17 +90,17 @@ func TestWebhookReleaseEvents(t *testing.T) { w.HookEvent = &webhook_module.HookEvent{ SendEverything: true, } - assert.NoError(t, w.UpdateEvent()) - assert.NoError(t, webhook_model.UpdateWebhook(db.DefaultContext, w)) + require.NoError(t, w.UpdateEvent()) + require.NoError(t, webhook_model.UpdateWebhook(db.DefaultContext, w)) hookTasks := retrieveHookTasks(t, w.ID, true) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo) - assert.NoError(t, err) + require.NoError(t, err) defer gitRepo.Close() t.Run("CreateRelease", func(t *testing.T) { - assert.NoError(t, release.CreateRelease(gitRepo, &repo_model.Release{ + require.NoError(t, release.CreateRelease(gitRepo, &repo_model.Release{ RepoID: repo.ID, Repo: repo, PublisherID: user.ID, @@ -125,7 +126,7 @@ func TestWebhookReleaseEvents(t *testing.T) { t.Run("UpdateRelease", func(t *testing.T) { rel := unittest.AssertExistsAndLoadBean(t, &repo_model.Release{RepoID: repo.ID, TagName: "v1.1.1"}) - assert.NoError(t, release.UpdateRelease(db.DefaultContext, user, gitRepo, rel, false, nil)) + require.NoError(t, release.UpdateRelease(db.DefaultContext, user, gitRepo, rel, false, nil)) // check the newly created hooktasks hookTasksLenBefore := len(hookTasks) @@ -138,7 +139,7 @@ func TestWebhookReleaseEvents(t *testing.T) { }) t.Run("CreateNewTag", func(t *testing.T) { - assert.NoError(t, release.CreateNewTag(db.DefaultContext, + require.NoError(t, release.CreateNewTag(db.DefaultContext, user, repo, "master", @@ -157,7 +158,7 @@ func TestWebhookReleaseEvents(t *testing.T) { t.Run("UpdateRelease", func(t *testing.T) { rel := unittest.AssertExistsAndLoadBean(t, &repo_model.Release{RepoID: repo.ID, TagName: "v1.1.2"}) - assert.NoError(t, release.UpdateRelease(db.DefaultContext, user, gitRepo, rel, true, nil)) + require.NoError(t, release.UpdateRelease(db.DefaultContext, user, gitRepo, rel, true, nil)) // check the newly created hooktasks hookTasksLenBefore := len(hookTasks) @@ -180,7 +181,7 @@ func checkHookTasks(t *testing.T, expectedActions map[webhook_module.HookEventTy var payload struct { Action string `json:"action"` } - assert.NoError(t, json.Unmarshal([]byte(hookTask.PayloadContent), &payload)) + require.NoError(t, json.Unmarshal([]byte(hookTask.PayloadContent), &payload)) assert.Equal(t, expectedAction, payload.Action, "unexpected action for %q event", hookTask.EventType) delete(expectedActions, hookTask.EventType) } diff --git a/tests/integration/xss_test.go b/tests/integration/xss_test.go index 6fe394acda..70038cf560 100644 --- a/tests/integration/xss_test.go +++ b/tests/integration/xss_test.go @@ -55,9 +55,9 @@ func TestXSSWikiLastCommitInfo(t *testing.T) { dstPath := t.TempDir() r := fmt.Sprintf("%suser2/repo1.wiki.git", u.String()) u, err := url.Parse(r) - assert.NoError(t, err) + require.NoError(t, err) u.User = url.UserPassword("user2", userPassword) - assert.NoError(t, git.CloneWithArgs(context.Background(), git.AllowLFSFiltersArgs(), u.String(), dstPath, git.CloneRepoOptions{})) + require.NoError(t, git.CloneWithArgs(context.Background(), git.AllowLFSFiltersArgs(), u.String(), dstPath, git.CloneRepoOptions{})) // Use go-git here, because using git wouldn't work, it has code to remove // `<`, `>` and `\n` in user names. Even though this is permitted and diff --git a/tests/test_utils.go b/tests/test_utils.go index 082785b75c..3b8ff7d310 100644 --- a/tests/test_utils.go +++ b/tests/test_utils.go @@ -31,7 +31,7 @@ import ( "code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/routers" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func exitf(format string, args ...any) { @@ -173,13 +173,13 @@ func InitTest(requireGitea bool) { func PrepareAttachmentsStorage(t testing.TB) { // prepare attachments directory and files - assert.NoError(t, storage.Clean(storage.Attachments)) + require.NoError(t, storage.Clean(storage.Attachments)) s, err := storage.NewStorage(setting.LocalStorageType, &setting.Storage{ Path: filepath.Join(filepath.Dir(setting.AppPath), "tests", "testdata", "data", "attachments"), }) - assert.NoError(t, err) - assert.NoError(t, s.IterateObjects("", func(p string, obj storage.Object) error { + require.NoError(t, err) + require.NoError(t, s.IterateObjects("", func(p string, obj storage.Object) error { _, err = storage.Copy(storage.Attachments, p, s, p) return err })) @@ -229,14 +229,14 @@ func PrepareTestEnv(t testing.TB, skip ...int) func() { t.Cleanup(func() { cancelProcesses(t, 0) }) // cancel remaining processes in a non-blocking way // load database fixtures - assert.NoError(t, unittest.LoadFixtures()) + require.NoError(t, unittest.LoadFixtures()) // load git repo fixtures - assert.NoError(t, util.RemoveAll(setting.RepoRootPath)) - assert.NoError(t, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath)) + require.NoError(t, util.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() { @@ -244,7 +244,7 @@ func PrepareTestEnv(t testing.TB, skip ...int) func() { } 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) @@ -259,15 +259,15 @@ func PrepareTestEnv(t testing.TB, skip ...int) func() { lfsFixtures, err := storage.NewStorage(setting.LocalStorageType, &setting.Storage{ Path: filepath.Join(filepath.Dir(setting.AppPath), "tests/gitea-lfs-meta"), }) - assert.NoError(t, err) - assert.NoError(t, storage.Clean(storage.LFS)) - assert.NoError(t, lfsFixtures.IterateObjects("", func(path string, _ storage.Object) error { + require.NoError(t, err) + require.NoError(t, storage.Clean(storage.LFS)) + require.NoError(t, lfsFixtures.IterateObjects("", func(path string, _ storage.Object) error { _, err := storage.Copy(storage.LFS, path, lfsFixtures, path) return err })) // clear all package data - assert.NoError(t, db.TruncateBeans(db.DefaultContext, + require.NoError(t, db.TruncateBeans(db.DefaultContext, &packages_model.Package{}, &packages_model.PackageVersion{}, &packages_model.PackageFile{}, @@ -276,7 +276,7 @@ func PrepareTestEnv(t testing.TB, skip ...int) func() { &packages_model.PackageBlobUpload{}, &packages_model.PackageCleanupRule{}, )) - assert.NoError(t, storage.Clean(storage.Packages)) + require.NoError(t, storage.Clean(storage.Packages)) return deferFn }