Add testifylint to lint checks (#4535)

go-require lint is ignored for now

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/4535
Reviewed-by: Gusted <gusted@noreply.codeberg.org>
Co-authored-by: TheFox0x7 <thefox0x7@gmail.com>
Co-committed-by: TheFox0x7 <thefox0x7@gmail.com>
This commit is contained in:
TheFox0x7 2024-07-30 19:41:10 +00:00 committed by Earl Warren
parent 94933470cd
commit 4de909747b
504 changed files with 5028 additions and 4680 deletions

View file

@ -20,6 +20,7 @@ linters:
- staticcheck - staticcheck
- stylecheck - stylecheck
- tenv - tenv
- testifylint
- typecheck - typecheck
- unconvert - unconvert
- unused - unused
@ -28,10 +29,6 @@ linters:
run: run:
timeout: 10m timeout: 10m
skip-dirs:
- node_modules
- public
- web_src
output: output:
sort-results: true sort-results: true
@ -101,6 +98,9 @@ linters-settings:
desc: do not use the ini package, use gitea's config system instead desc: do not use the ini package, use gitea's config system instead
- pkg: github.com/minio/sha256-simd - pkg: github.com/minio/sha256-simd
desc: use crypto/sha256 instead, see https://codeberg.org/forgejo/forgejo/pulls/1528 desc: use crypto/sha256 instead, see https://codeberg.org/forgejo/forgejo/pulls/1528
testifylint:
disable:
- go-require
issues: issues:
max-issues-per-linter: 0 max-issues-per-linter: 0

View file

@ -7,6 +7,7 @@ import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestFormatImportsSimple(t *testing.T) { func TestFormatImportsSimple(t *testing.T) {
@ -29,7 +30,7 @@ import (
) )
` `
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, expected, string(formatted)) 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)) assert.Equal(t, expected, string(formatted))
} }
@ -120,5 +121,5 @@ import (
"image/gif" "image/gif"
) )
`)) `))
assert.ErrorIs(t, err, errInvalidCommentBetweenImports) require.ErrorIs(t, err, errInvalidCommentBetweenImports)
} }

View file

@ -11,6 +11,7 @@ import (
"code.gitea.io/gitea/services/auth/source/ldap" "code.gitea.io/gitea/services/auth/source/ldap"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
) )
@ -234,7 +235,7 @@ func TestAddLdapBindDn(t *testing.T) {
if c.errMsg != "" { if c.errMsg != "" {
assert.EqualError(t, err, c.errMsg, "case %d: error should match", n) assert.EqualError(t, err, c.errMsg, "case %d: error should match", n)
} else { } 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) assert.Equal(t, c.source, createdAuthSource, "case %d: wrong authSource", n)
} }
} }
@ -465,7 +466,7 @@ func TestAddLdapSimpleAuth(t *testing.T) {
if c.errMsg != "" { if c.errMsg != "" {
assert.EqualError(t, err, c.errMsg, "case %d: error should match", n) assert.EqualError(t, err, c.errMsg, "case %d: error should match", n)
} else { } 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) assert.Equal(t, c.authSource, createdAuthSource, "case %d: wrong authSource", n)
} }
} }
@ -928,7 +929,7 @@ func TestUpdateLdapBindDn(t *testing.T) {
if c.errMsg != "" { if c.errMsg != "" {
assert.EqualError(t, err, c.errMsg, "case %d: error should match", n) assert.EqualError(t, err, c.errMsg, "case %d: error should match", n)
} else { } 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) assert.Equal(t, c.authSource, updatedAuthSource, "case %d: wrong authSource", n)
} }
} }
@ -1318,7 +1319,7 @@ func TestUpdateLdapSimpleAuth(t *testing.T) {
if c.errMsg != "" { if c.errMsg != "" {
assert.EqualError(t, err, c.errMsg, "case %d: error should match", n) assert.EqualError(t, err, c.errMsg, "case %d: error should match", n)
} else { } 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) assert.Equal(t, c.authSource, updatedAuthSource, "case %d: wrong authSource", n)
} }
} }

View file

@ -10,7 +10,7 @@ import (
"code.gitea.io/gitea/modules/log" "code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/services/doctor" "code.gitea.io/gitea/services/doctor"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
"github.com/urfave/cli/v2" "github.com/urfave/cli/v2"
) )
@ -25,9 +25,9 @@ func TestDoctorRun(t *testing.T) {
app := cli.NewApp() app := cli.NewApp()
app.Commands = []*cli.Command{cmdDoctorCheck} app.Commands = []*cli.Command{cmdDoctorCheck}
err := app.Run([]string{"./gitea", "check", "--run", "test-check"}) 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"}) 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"}) 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"`)
} }

View file

@ -10,6 +10,7 @@ import (
"github.com/mholt/archiver/v3" "github.com/mholt/archiver/v3"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
type mockArchiver struct { type mockArchiver struct {
@ -35,20 +36,20 @@ func TestAddRecursiveExclude(t *testing.T) {
archiver := &mockArchiver{} archiver := &mockArchiver{}
err := addRecursiveExclude(archiver, "", dir, []string{}, false) err := addRecursiveExclude(archiver, "", dir, []string{}, false)
assert.NoError(t, err) require.NoError(t, err)
assert.Empty(t, archiver.addedFiles) assert.Empty(t, archiver.addedFiles)
}) })
t.Run("Single file", func(t *testing.T) { t.Run("Single file", func(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
err := os.WriteFile(dir+"/example", nil, 0o666) err := os.WriteFile(dir+"/example", nil, 0o666)
assert.NoError(t, err) require.NoError(t, err)
t.Run("No exclude", func(t *testing.T) { t.Run("No exclude", func(t *testing.T) {
archiver := &mockArchiver{} archiver := &mockArchiver{}
err = addRecursiveExclude(archiver, "", dir, nil, false) err = addRecursiveExclude(archiver, "", dir, nil, false)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, archiver.addedFiles, 1) assert.Len(t, archiver.addedFiles, 1)
assert.Contains(t, archiver.addedFiles, "example") assert.Contains(t, archiver.addedFiles, "example")
}) })
@ -57,7 +58,7 @@ func TestAddRecursiveExclude(t *testing.T) {
archiver := &mockArchiver{} archiver := &mockArchiver{}
err = addRecursiveExclude(archiver, "", dir, []string{dir + "/example"}, false) err = addRecursiveExclude(archiver, "", dir, []string{dir + "/example"}, false)
assert.NoError(t, err) require.NoError(t, err)
assert.Empty(t, archiver.addedFiles) assert.Empty(t, archiver.addedFiles)
}) })
}) })
@ -65,17 +66,17 @@ func TestAddRecursiveExclude(t *testing.T) {
t.Run("File inside directory", func(t *testing.T) { t.Run("File inside directory", func(t *testing.T) {
dir := t.TempDir() dir := t.TempDir()
err := os.MkdirAll(dir+"/deep/nested/folder", 0o750) 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) 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) 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) { t.Run("No exclude", func(t *testing.T) {
archiver := &mockArchiver{} archiver := &mockArchiver{}
err = addRecursiveExclude(archiver, "", dir, nil, false) err = addRecursiveExclude(archiver, "", dir, nil, false)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, archiver.addedFiles, 5) assert.Len(t, archiver.addedFiles, 5)
assert.Contains(t, archiver.addedFiles, "deep") assert.Contains(t, archiver.addedFiles, "deep")
assert.Contains(t, archiver.addedFiles, "deep/nested") assert.Contains(t, archiver.addedFiles, "deep/nested")
@ -88,7 +89,7 @@ func TestAddRecursiveExclude(t *testing.T) {
archiver := &mockArchiver{} archiver := &mockArchiver{}
err = addRecursiveExclude(archiver, "", dir, []string{dir + "/deep"}, false) err = addRecursiveExclude(archiver, "", dir, []string{dir + "/deep"}, false)
assert.NoError(t, err) require.NoError(t, err)
assert.Empty(t, archiver.addedFiles) assert.Empty(t, archiver.addedFiles)
}) })
@ -96,7 +97,7 @@ func TestAddRecursiveExclude(t *testing.T) {
archiver := &mockArchiver{} archiver := &mockArchiver{}
err = addRecursiveExclude(archiver, "", dir, []string{dir + "/deep/nested/folder"}, false) 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.Len(t, archiver.addedFiles, 2)
assert.Contains(t, archiver.addedFiles, "deep") assert.Contains(t, archiver.addedFiles, "deep")
assert.Contains(t, archiver.addedFiles, "deep/nested") assert.Contains(t, archiver.addedFiles, "deep/nested")
@ -106,7 +107,7 @@ func TestAddRecursiveExclude(t *testing.T) {
archiver := &mockArchiver{} archiver := &mockArchiver{}
err = addRecursiveExclude(archiver, "", dir, []string{dir + "/deep/nested/folder/example"}, false) 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.Len(t, archiver.addedFiles, 4)
assert.Contains(t, archiver.addedFiles, "deep") assert.Contains(t, archiver.addedFiles, "deep")
assert.Contains(t, archiver.addedFiles, "deep/nested") assert.Contains(t, archiver.addedFiles, "deep/nested")

View file

@ -79,9 +79,9 @@ func TestActions_getLabels(t *testing.T) {
assert.Nil(t, result.labels) assert.Nil(t, result.labels)
} }
if c.hasError { if c.hasError {
assert.NotNil(t, result.err) require.Error(t, result.err)
} else { } else {
assert.Nil(t, result.err) assert.NoError(t, result.err)
} }
}) })
} }

View file

@ -48,66 +48,66 @@ func TestPktLine(t *testing.T) {
s := strings.NewReader("0000") s := strings.NewReader("0000")
r := bufio.NewReader(s) r := bufio.NewReader(s)
result, err := readPktLine(ctx, r, pktLineTypeFlush) result, err := readPktLine(ctx, r, pktLineTypeFlush)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, pktLineTypeFlush, result.Type) assert.Equal(t, pktLineTypeFlush, result.Type)
s = strings.NewReader("0006a\n") s = strings.NewReader("0006a\n")
r = bufio.NewReader(s) r = bufio.NewReader(s)
result, err = readPktLine(ctx, r, pktLineTypeData) result, err = readPktLine(ctx, r, pktLineTypeData)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, pktLineTypeData, result.Type) assert.Equal(t, pktLineTypeData, result.Type)
assert.Equal(t, []byte("a\n"), result.Data) assert.Equal(t, []byte("a\n"), result.Data)
s = strings.NewReader("0004") s = strings.NewReader("0004")
r = bufio.NewReader(s) r = bufio.NewReader(s)
result, err = readPktLine(ctx, r, pktLineTypeData) result, err = readPktLine(ctx, r, pktLineTypeData)
assert.Error(t, err) require.Error(t, err)
assert.Nil(t, result) assert.Nil(t, result)
data := strings.Repeat("x", 65516) data := strings.Repeat("x", 65516)
r = bufio.NewReader(strings.NewReader("fff0" + data)) r = bufio.NewReader(strings.NewReader("fff0" + data))
result, err = readPktLine(ctx, r, pktLineTypeData) result, err = readPktLine(ctx, r, pktLineTypeData)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, pktLineTypeData, result.Type) assert.Equal(t, pktLineTypeData, result.Type)
assert.Equal(t, []byte(data), result.Data) assert.Equal(t, []byte(data), result.Data)
r = bufio.NewReader(strings.NewReader("fff1a")) r = bufio.NewReader(strings.NewReader("fff1a"))
result, err = readPktLine(ctx, r, pktLineTypeData) result, err = readPktLine(ctx, r, pktLineTypeData)
assert.Error(t, err) require.Error(t, err)
assert.Nil(t, result) assert.Nil(t, result)
}) })
t.Run("Write", func(t *testing.T) { t.Run("Write", func(t *testing.T) {
w := bytes.NewBuffer([]byte{}) w := bytes.NewBuffer([]byte{})
err := writeFlushPktLine(ctx, w) err := writeFlushPktLine(ctx, w)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, []byte("0000"), w.Bytes()) assert.Equal(t, []byte("0000"), w.Bytes())
w.Reset() w.Reset()
err = writeDataPktLine(ctx, w, []byte("a\nb")) err = writeDataPktLine(ctx, w, []byte("a\nb"))
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, []byte("0007a\nb"), w.Bytes()) assert.Equal(t, []byte("0007a\nb"), w.Bytes())
w.Reset() w.Reset()
data := bytes.Repeat([]byte{0x05}, 288) data := bytes.Repeat([]byte{0x05}, 288)
err = writeDataPktLine(ctx, w, data) err = writeDataPktLine(ctx, w, data)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, append([]byte("0124"), data...), w.Bytes()) assert.Equal(t, append([]byte("0124"), data...), w.Bytes())
w.Reset() w.Reset()
err = writeDataPktLine(ctx, w, nil) err = writeDataPktLine(ctx, w, nil)
assert.Error(t, err) require.Error(t, err)
assert.Empty(t, w.Bytes()) assert.Empty(t, w.Bytes())
w.Reset() w.Reset()
data = bytes.Repeat([]byte{0x64}, 65516) data = bytes.Repeat([]byte{0x64}, 65516)
err = writeDataPktLine(ctx, w, data) err = writeDataPktLine(ctx, w, data)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, append([]byte("fff0"), data...), w.Bytes()) assert.Equal(t, append([]byte("fff0"), data...), w.Bytes())
w.Reset() w.Reset()
err = writeDataPktLine(ctx, w, bytes.Repeat([]byte{0x64}, 65516+1)) err = writeDataPktLine(ctx, w, bytes.Repeat([]byte{0x64}, 65516+1))
assert.Error(t, err) require.Error(t, err)
assert.Empty(t, w.Bytes()) 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"}) err := app.Run([]string{"./forgejo", "update", "refs/pull/1/head", "0a51ae26bc73c47e2f754560c40904cf14ed51a9", "0000000000000000000000000000000000000000"})
out := finish() 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.") 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) { t.Run("Update of internal reference", func(t *testing.T) {
err := app.Run([]string{"./forgejo", "update", "refs/pull/1/head", "0a51ae26bc73c47e2f754560c40904cf14ed51a9", "0000000000000000000000000000000000000001"}) 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) { t.Run("Removal of branch", func(t *testing.T) {
err := app.Run([]string{"./forgejo", "update", "refs/head/main", "0a51ae26bc73c47e2f754560c40904cf14ed51a9", "0000000000000000000000000000000000000000"}) 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) { t.Run("Not enough arguments", func(t *testing.T) {
err := app.Run([]string{"./forgejo", "update"}) err := app.Run([]string{"./forgejo", "update"})
assert.NoError(t, err) require.NoError(t, err)
}) })
} }

View file

@ -16,6 +16,7 @@ import (
"code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/urfave/cli/v2" "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 args := strings.Split(c.cmd, " ") // for test only, "split" is good enough
r, err := runTestApp(app, args...) 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.NotEmpty(t, c.exp, c.cmd)
assert.Contains(t, r.Stdout, 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) { func TestCliCmdError(t *testing.T) {
app := newTestApp(func(ctx *cli.Context) error { return fmt.Errorf("normal error") }) app := newTestApp(func(ctx *cli.Context) error { return fmt.Errorf("normal error") })
r, err := runTestApp(app, "./gitea", "test-cmd") r, err := runTestApp(app, "./gitea", "test-cmd")
assert.Error(t, err) require.Error(t, err)
assert.Equal(t, 1, r.ExitCode) assert.Equal(t, 1, r.ExitCode)
assert.Equal(t, "", r.Stdout) assert.Equal(t, "", r.Stdout)
assert.Equal(t, "Command error: normal error\n", r.Stderr) assert.Equal(t, "Command error: normal error\n", r.Stderr)
app = newTestApp(func(ctx *cli.Context) error { return cli.Exit("exit error", 2) }) app = newTestApp(func(ctx *cli.Context) error { return cli.Exit("exit error", 2) })
r, err = runTestApp(app, "./gitea", "test-cmd") r, err = runTestApp(app, "./gitea", "test-cmd")
assert.Error(t, err) require.Error(t, err)
assert.Equal(t, 2, r.ExitCode) assert.Equal(t, 2, r.ExitCode)
assert.Equal(t, "", r.Stdout) assert.Equal(t, "", r.Stdout)
assert.Equal(t, "exit error\n", r.Stderr) assert.Equal(t, "exit error\n", r.Stderr)
app = newTestApp(func(ctx *cli.Context) error { return nil }) app = newTestApp(func(ctx *cli.Context) error { return nil })
r, err = runTestApp(app, "./gitea", "test-cmd", "--no-such") 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, 1, r.ExitCode)
assert.Equal(t, "Incorrect Usage: flag provided but not defined: -no-such\n\n", r.Stdout) 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 .... 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 }) app = newTestApp(func(ctx *cli.Context) error { return nil })
r, err = runTestApp(app, "./gitea", "test-cmd") 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, -1, r.ExitCode) // the cli.OsExiter is not called
assert.Equal(t, "", r.Stdout) assert.Equal(t, "", r.Stdout)
assert.Equal(t, "", r.Stderr) assert.Equal(t, "", r.Stderr)

View file

@ -41,13 +41,13 @@ func createLocalStorage(t *testing.T) (storage.ObjectStorage, string) {
} }
func TestMigratePackages(t *testing.T) { func TestMigratePackages(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
creator := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) creator := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
content := "package main\n\nfunc main() {\nfmt.Println(\"hi\")\n}\n" content := "package main\n\nfunc main() {\nfmt.Println(\"hi\")\n}\n"
buf, err := packages_module.CreateHashedBufferFromReaderWithSize(strings.NewReader(content), 1024) buf, err := packages_module.CreateHashedBufferFromReaderWithSize(strings.NewReader(content), 1024)
assert.NoError(t, err) require.NoError(t, err)
defer buf.Close() defer buf.Close()
v, f, err := packages_service.CreatePackageAndAddFile(db.DefaultContext, &packages_service.PackageCreationInfo{ v, f, err := packages_service.CreatePackageAndAddFile(db.DefaultContext, &packages_service.PackageCreationInfo{
@ -68,7 +68,7 @@ func TestMigratePackages(t *testing.T) {
Data: buf, Data: buf,
IsLead: true, IsLead: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, v) assert.NotNil(t, v)
assert.NotNil(t, f) assert.NotNil(t, f)
@ -77,17 +77,17 @@ func TestMigratePackages(t *testing.T) {
dstStorage, p := createLocalStorage(t) dstStorage, p := createLocalStorage(t)
err = migratePackages(ctx, dstStorage) err = migratePackages(ctx, dstStorage)
assert.NoError(t, err) require.NoError(t, err)
entries, err := os.ReadDir(p) entries, err := os.ReadDir(p)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, entries, 2) assert.Len(t, entries, 2)
assert.EqualValues(t, "01", entries[0].Name()) assert.EqualValues(t, "01", entries[0].Name())
assert.EqualValues(t, "tmp", entries[1].Name()) assert.EqualValues(t, "tmp", entries[1].Name())
} }
func TestMigrateActionsArtifacts(t *testing.T) { func TestMigrateActionsArtifacts(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
srcStorage, _ := createLocalStorage(t) srcStorage, _ := createLocalStorage(t)
defer test.MockVariableValue(&storage.ActionsArtifacts, srcStorage)() defer test.MockVariableValue(&storage.ActionsArtifacts, srcStorage)()
@ -118,17 +118,17 @@ func TestMigrateActionsArtifacts(t *testing.T) {
dstStorage, _ := createLocalStorage(t) dstStorage, _ := createLocalStorage(t)
assert.NoError(t, migrateActionsArtifacts(db.DefaultContext, dstStorage)) require.NoError(t, migrateActionsArtifacts(db.DefaultContext, dstStorage))
object, err := dstStorage.Open(exists) object, err := dstStorage.Open(exists)
assert.NoError(t, err) require.NoError(t, err)
buf, err := io.ReadAll(object) buf, err := io.ReadAll(object)
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, exists, string(buf)) assert.Equal(t, exists, string(buf))
_, err = dstStorage.Stat(expired) _, err = dstStorage.Stat(expired)
assert.Error(t, err) require.Error(t, err)
_, err = dstStorage.Stat(notFound) _, err = dstStorage.Stat(notFound)
assert.Error(t, err) require.Error(t, err)
} }

View file

@ -15,7 +15,7 @@ import (
) )
func TestActions_RegisterRunner_Token(t *testing.T) { func TestActions_RegisterRunner_Token(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
ownerID := int64(0) ownerID := int64(0)
repoID := int64(0) repoID := int64(0)
token := "0123456789012345678901234567890123456789" token := "0123456789012345678901234567890123456789"
@ -23,7 +23,7 @@ func TestActions_RegisterRunner_Token(t *testing.T) {
name := "runner" name := "runner"
version := "v1.2.3" version := "v1.2.3"
runner, err := RegisterRunner(db.DefaultContext, ownerID, repoID, token, &labels, name, version) 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, 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") 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 const recordID = 12345678
oldToken := "7e577e577e577e57feedfacefeedfacefeedface" oldToken := "7e577e577e577e57feedfacefeedfacefeedface"
newToken := "7e577e577e577e57deadbeefdeadbeefdeadbeef" newToken := "7e577e577e577e57deadbeefdeadbeefdeadbeef"
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
before := unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID}) before := unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID})
require.Equal(t, require.Equal(t,
before.TokenHash, auth_model.HashToken(oldToken, before.TokenSalt), 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) { func TestActions_RegisterRunner_CreateWithLabels(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
ownerID := int64(0) ownerID := int64(0)
repoID := int64(0) repoID := int64(0)
token := "0123456789012345678901234567890123456789" 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 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) 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 // Check that the returned record has been updated, except for the labels
assert.EqualValues(t, ownerID, runner.OwnerID) assert.EqualValues(t, ownerID, runner.OwnerID)
@ -89,7 +89,7 @@ func TestActions_RegisterRunner_CreateWithLabels(t *testing.T) {
} }
func TestActions_RegisterRunner_CreateWithoutLabels(t *testing.T) { func TestActions_RegisterRunner_CreateWithoutLabels(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
ownerID := int64(0) ownerID := int64(0)
repoID := int64(0) repoID := int64(0)
token := "0123456789012345678901234567890123456789" token := "0123456789012345678901234567890123456789"
@ -97,7 +97,7 @@ func TestActions_RegisterRunner_CreateWithoutLabels(t *testing.T) {
version := "v1.2.3" version := "v1.2.3"
runner, err := RegisterRunner(db.DefaultContext, ownerID, repoID, token, nil, name, version) 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 // Check that the returned record has been updated, except for the labels
assert.EqualValues(t, ownerID, runner.OwnerID) assert.EqualValues(t, ownerID, runner.OwnerID)
@ -118,7 +118,7 @@ func TestActions_RegisterRunner_CreateWithoutLabels(t *testing.T) {
func TestActions_RegisterRunner_UpdateWithLabels(t *testing.T) { func TestActions_RegisterRunner_UpdateWithLabels(t *testing.T) {
const recordID = 12345678 const recordID = 12345678
token := "7e577e577e577e57feedfacefeedfacefeedface" token := "7e577e577e577e57feedfacefeedfacefeedface"
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID}) unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID})
newOwnerID := int64(1) 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 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) 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 // Check that the returned record has been updated
assert.EqualValues(t, newOwnerID, runner.OwnerID) assert.EqualValues(t, newOwnerID, runner.OwnerID)
@ -150,7 +150,7 @@ func TestActions_RegisterRunner_UpdateWithLabels(t *testing.T) {
func TestActions_RegisterRunner_UpdateWithoutLabels(t *testing.T) { func TestActions_RegisterRunner_UpdateWithoutLabels(t *testing.T) {
const recordID = 12345678 const recordID = 12345678
token := "7e577e577e577e57feedfacefeedfacefeedface" token := "7e577e577e577e57feedfacefeedfacefeedface"
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
before := unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID}) before := unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID})
newOwnerID := int64(1) newOwnerID := int64(1)
@ -159,7 +159,7 @@ func TestActions_RegisterRunner_UpdateWithoutLabels(t *testing.T) {
newVersion := "v4.5.6" newVersion := "v4.5.6"
runner, err := RegisterRunner(db.DefaultContext, newOwnerID, newRepoID, token, nil, newName, newVersion) 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 // Check that the returned record has been updated, except for the labels
assert.EqualValues(t, newOwnerID, runner.OwnerID) assert.EqualValues(t, newOwnerID, runner.OwnerID)

View file

@ -31,15 +31,15 @@ func TestUpdateSecret(t *testing.T) {
func TestDeleteRunner(t *testing.T) { func TestDeleteRunner(t *testing.T) {
const recordID = 12345678 const recordID = 12345678
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
before := unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID}) before := unittest.AssertExistsAndLoadBean(t, &ActionRunner{ID: recordID})
err := DeleteRunner(db.DefaultContext, recordID) err := DeleteRunner(db.DefaultContext, recordID)
assert.NoError(t, err) require.NoError(t, err)
var after ActionRunner var after ActionRunner
found, err := db.GetEngine(db.DefaultContext).ID(recordID).Unscoped().Get(&after) found, err := db.GetEngine(db.DefaultContext).ID(recordID).Unscoped().Get(&after)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, found) assert.True(t, found)
// Most fields (namely Name, Version, OwnerID, RepoID, Description, Base, RepoRange, // Most fields (namely Name, Version, OwnerID, RepoID, Description, Base, RepoRange,

View file

@ -10,31 +10,32 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGetLatestRunnerToken(t *testing.T) { func TestGetLatestRunnerToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
token := unittest.AssertExistsAndLoadBean(t, &ActionRunnerToken{ID: 3}) token := unittest.AssertExistsAndLoadBean(t, &ActionRunnerToken{ID: 3})
expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0) expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, token, expectedToken) assert.EqualValues(t, expectedToken, token)
} }
func TestNewRunnerToken(t *testing.T) { func TestNewRunnerToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
token, err := NewRunnerToken(db.DefaultContext, 1, 0) token, err := NewRunnerToken(db.DefaultContext, 1, 0)
assert.NoError(t, err) require.NoError(t, err)
expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0) expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, token, expectedToken) assert.EqualValues(t, expectedToken, token)
} }
func TestUpdateRunnerToken(t *testing.T) { func TestUpdateRunnerToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
token := unittest.AssertExistsAndLoadBean(t, &ActionRunnerToken{ID: 3}) token := unittest.AssertExistsAndLoadBean(t, &ActionRunnerToken{ID: 3})
token.IsActive = true token.IsActive = true
assert.NoError(t, UpdateRunnerToken(db.DefaultContext, token)) require.NoError(t, UpdateRunnerToken(db.DefaultContext, token))
expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0) expectedToken, err := GetLatestRunnerToken(db.DefaultContext, 1, 0)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, token, expectedToken) assert.EqualValues(t, expectedToken, token)
} }

View file

@ -17,10 +17,11 @@ import (
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestAction_GetRepoPath(t *testing.T) { 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}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
action := &activities_model.Action{RepoID: repo.ID} action := &activities_model.Action{RepoID: repo.ID}
@ -28,7 +29,7 @@ func TestAction_GetRepoPath(t *testing.T) {
} }
func TestAction_GetRepoLink(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}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
comment := unittest.AssertExistsAndLoadBean(t, &issue_model.Comment{ID: 2}) comment := unittest.AssertExistsAndLoadBean(t, &issue_model.Comment{ID: 2})
@ -42,7 +43,7 @@ func TestAction_GetRepoLink(t *testing.T) {
func TestGetFeeds(t *testing.T) { func TestGetFeeds(t *testing.T) {
// test with an individual user // test with an individual user
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{ actions, count, err := activities_model.GetFeeds(db.DefaultContext, activities_model.GetFeedsOptions{
@ -52,7 +53,7 @@ func TestGetFeeds(t *testing.T) {
OnlyPerformedBy: false, OnlyPerformedBy: false,
IncludeDeleted: true, IncludeDeleted: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, actions, 1) { if assert.Len(t, actions, 1) {
assert.EqualValues(t, 1, actions[0].ID) assert.EqualValues(t, 1, actions[0].ID)
assert.EqualValues(t, user.ID, actions[0].UserID) assert.EqualValues(t, user.ID, actions[0].UserID)
@ -65,13 +66,13 @@ func TestGetFeeds(t *testing.T) {
IncludePrivate: false, IncludePrivate: false,
OnlyPerformedBy: false, OnlyPerformedBy: false,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, actions, 0) assert.Empty(t, actions)
assert.Equal(t, int64(0), count) assert.Equal(t, int64(0), count)
} }
func TestGetFeedsForRepos(t *testing.T) { func TestGetFeedsForRepos(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
privRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) privRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
pubRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 8}) pubRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 8})
@ -81,8 +82,8 @@ func TestGetFeedsForRepos(t *testing.T) {
RequestedRepo: privRepo, RequestedRepo: privRepo,
IncludePrivate: true, IncludePrivate: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, actions, 0) assert.Empty(t, actions)
assert.Equal(t, int64(0), count) assert.Equal(t, int64(0), count)
// public repo & no login // public repo & no login
@ -90,7 +91,7 @@ func TestGetFeedsForRepos(t *testing.T) {
RequestedRepo: pubRepo, RequestedRepo: pubRepo,
IncludePrivate: true, IncludePrivate: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, actions, 1) assert.Len(t, actions, 1)
assert.Equal(t, int64(1), count) assert.Equal(t, int64(1), count)
@ -100,7 +101,7 @@ func TestGetFeedsForRepos(t *testing.T) {
IncludePrivate: true, IncludePrivate: true,
Actor: user, Actor: user,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, actions, 1) assert.Len(t, actions, 1)
assert.Equal(t, int64(1), count) assert.Equal(t, int64(1), count)
@ -110,14 +111,14 @@ func TestGetFeedsForRepos(t *testing.T) {
IncludePrivate: true, IncludePrivate: true,
Actor: user, Actor: user,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, actions, 1) assert.Len(t, actions, 1)
assert.Equal(t, int64(1), count) assert.Equal(t, int64(1), count)
} }
func TestGetFeeds2(t *testing.T) { func TestGetFeeds2(t *testing.T) {
// test with an organization user // test with an organization user
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
@ -128,7 +129,7 @@ func TestGetFeeds2(t *testing.T) {
OnlyPerformedBy: false, OnlyPerformedBy: false,
IncludeDeleted: true, IncludeDeleted: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, actions, 1) assert.Len(t, actions, 1)
if assert.Len(t, actions, 1) { if assert.Len(t, actions, 1) {
assert.EqualValues(t, 2, actions[0].ID) assert.EqualValues(t, 2, actions[0].ID)
@ -143,8 +144,8 @@ func TestGetFeeds2(t *testing.T) {
OnlyPerformedBy: false, OnlyPerformedBy: false,
IncludeDeleted: true, IncludeDeleted: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, actions, 0) assert.Empty(t, actions)
assert.Equal(t, int64(0), count) assert.Equal(t, int64(0), count)
} }
@ -189,14 +190,14 @@ func TestActivityReadable(t *testing.T) {
} }
func TestNotifyWatchers(t *testing.T) { func TestNotifyWatchers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
action := &activities_model.Action{ action := &activities_model.Action{
ActUserID: 8, ActUserID: 8,
RepoID: 1, RepoID: 1,
OpType: activities_model.ActionStarRepo, 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 // One watchers are inactive, thus action is only created for user 8, 1, 4, 11
unittest.AssertExistsAndLoadBean(t, &activities_model.Action{ unittest.AssertExistsAndLoadBean(t, &activities_model.Action{
@ -226,7 +227,7 @@ func TestNotifyWatchers(t *testing.T) {
} }
func TestGetFeedsCorrupted(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}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
unittest.AssertExistsAndLoadBean(t, &activities_model.Action{ unittest.AssertExistsAndLoadBean(t, &activities_model.Action{
ID: 8, ID: 8,
@ -238,8 +239,8 @@ func TestGetFeedsCorrupted(t *testing.T) {
Actor: user, Actor: user,
IncludePrivate: true, IncludePrivate: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, actions, 0) assert.Empty(t, actions)
assert.Equal(t, int64(0), count) assert.Equal(t, int64(0), count)
} }
@ -247,47 +248,46 @@ func TestConsistencyUpdateAction(t *testing.T) {
if !setting.Database.Type.IsSQLite3() { if !setting.Database.Type.IsSQLite3() {
t.Skip("Test is only for SQLite database.") t.Skip("Test is only for SQLite database.")
} }
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
id := 8 id := 8
unittest.AssertExistsAndLoadBean(t, &activities_model.Action{ unittest.AssertExistsAndLoadBean(t, &activities_model.Action{
ID: int64(id), ID: int64(id),
}) })
_, err := db.GetEngine(db.DefaultContext).Exec(`UPDATE action SET created_unix = "" WHERE id = ?`, 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) actions := make([]*activities_model.Action, 0, 1)
// //
// XORM returns an error when created_unix is a string // XORM returns an error when created_unix is a string
// //
err = db.GetEngine(db.DefaultContext).Where("id = ?", id).Find(&actions) err = db.GetEngine(db.DefaultContext).Where("id = ?", id).Find(&actions)
if assert.Error(t, err) { require.ErrorContains(t, err, "type string to a int64: invalid syntax")
assert.Contains(t, err.Error(), "type string to a int64: invalid syntax")
}
// //
// Get rid of incorrectly set created_unix // Get rid of incorrectly set created_unix
// //
count, err := activities_model.CountActionCreatedUnixString(db.DefaultContext) count, err := activities_model.CountActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, count) assert.EqualValues(t, 1, count)
count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext) count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, count) assert.EqualValues(t, 1, count)
count, err = activities_model.CountActionCreatedUnixString(db.DefaultContext) count, err = activities_model.CountActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 0, count) assert.EqualValues(t, 0, count)
count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext) count, err = activities_model.FixActionCreatedUnixString(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 0, count) assert.EqualValues(t, 0, count)
// //
// XORM must be happy now // 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{}) unittest.CheckConsistencyFor(t, &activities_model.Action{})
} }
func TestDeleteIssueActions(t *testing.T) { func TestDeleteIssueActions(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
// load an issue // load an issue
issue := unittest.AssertExistsAndLoadBean(t, &issue_model.Issue{ID: 4}) issue := unittest.AssertExistsAndLoadBean(t, &issue_model.Issue{ID: 4})
@ -295,26 +295,26 @@ func TestDeleteIssueActions(t *testing.T) {
// insert a comment // insert a comment
err := db.Insert(db.DefaultContext, &issue_model.Comment{Type: issue_model.CommentTypeComment, IssueID: issue.ID}) 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}) comment := unittest.AssertExistsAndLoadBean(t, &issue_model.Comment{Type: issue_model.CommentTypeComment, IssueID: issue.ID})
// truncate action table and insert some actions // truncate action table and insert some actions
err = db.TruncateBeans(db.DefaultContext, &activities_model.Action{}) err = db.TruncateBeans(db.DefaultContext, &activities_model.Action{})
assert.NoError(t, err) require.NoError(t, err)
err = db.Insert(db.DefaultContext, &activities_model.Action{ err = db.Insert(db.DefaultContext, &activities_model.Action{
OpType: activities_model.ActionCommentIssue, OpType: activities_model.ActionCommentIssue,
CommentID: comment.ID, CommentID: comment.ID,
}) })
assert.NoError(t, err) require.NoError(t, err)
err = db.Insert(db.DefaultContext, &activities_model.Action{ err = db.Insert(db.DefaultContext, &activities_model.Action{
OpType: activities_model.ActionCreateIssue, OpType: activities_model.ActionCreateIssue,
RepoID: issue.RepoID, RepoID: issue.RepoID,
Content: fmt.Sprintf("%d|content...", issue.Index), Content: fmt.Sprintf("%d|content...", issue.Index),
}) })
assert.NoError(t, err) require.NoError(t, err)
// assert that the actions exist, then delete them // assert that the actions exist, then delete them
unittest.AssertCount(t, &activities_model.Action{}, 2) 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) unittest.AssertCount(t, &activities_model.Action{}, 0)
} }

View file

@ -14,13 +14,14 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestCreateOrUpdateIssueNotifications(t *testing.T) { func TestCreateOrUpdateIssueNotifications(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) 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 // 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}) 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) { func TestNotificationsForUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
notfs, err := db.Find[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{ notfs, err := db.Find[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{
UserID: user.ID, UserID: user.ID,
@ -41,7 +42,7 @@ func TestNotificationsForUser(t *testing.T) {
activities_model.NotificationStatusUnread, activities_model.NotificationStatusUnread,
}, },
}) })
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, notfs, 3) { if assert.Len(t, notfs, 3) {
assert.EqualValues(t, 5, notfs[0].ID) assert.EqualValues(t, 5, notfs[0].ID)
assert.EqualValues(t, user.ID, notfs[0].UserID) assert.EqualValues(t, user.ID, notfs[0].UserID)
@ -53,25 +54,25 @@ func TestNotificationsForUser(t *testing.T) {
} }
func TestNotification_GetRepo(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}) notf := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{RepoID: 1})
repo, err := notf.GetRepo(db.DefaultContext) repo, err := notf.GetRepo(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, repo, notf.Repository) assert.Equal(t, repo, notf.Repository)
assert.EqualValues(t, notf.RepoID, repo.ID) assert.EqualValues(t, notf.RepoID, repo.ID)
} }
func TestNotification_GetIssue(t *testing.T) { 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}) notf := unittest.AssertExistsAndLoadBean(t, &activities_model.Notification{RepoID: 1})
issue, err := notf.GetIssue(db.DefaultContext) issue, err := notf.GetIssue(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, issue, notf.Issue) assert.Equal(t, issue, notf.Issue)
assert.EqualValues(t, notf.IssueID, issue.ID) assert.EqualValues(t, notf.IssueID, issue.ID)
} }
func TestGetNotificationCount(t *testing.T) { func TestGetNotificationCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
cnt, err := db.Count[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{ cnt, err := db.Count[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{
UserID: user.ID, UserID: user.ID,
@ -79,7 +80,7 @@ func TestGetNotificationCount(t *testing.T) {
activities_model.NotificationStatusRead, activities_model.NotificationStatusRead,
}, },
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 0, cnt) assert.EqualValues(t, 0, cnt)
cnt, err = db.Count[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{ cnt, err = db.Count[activities_model.Notification](db.DefaultContext, activities_model.FindNotificationOptions{
@ -88,28 +89,28 @@ func TestGetNotificationCount(t *testing.T) {
activities_model.NotificationStatusUnread, activities_model.NotificationStatusUnread,
}, },
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, cnt) assert.EqualValues(t, 1, cnt)
} }
func TestSetNotificationStatus(t *testing.T) { func TestSetNotificationStatus(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
notf := unittest.AssertExistsAndLoadBean(t, notf := unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead}) &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead})
_, err := activities_model.SetNotificationStatus(db.DefaultContext, notf.ID, user, activities_model.NotificationStatusPinned) _, err := activities_model.SetNotificationStatus(db.DefaultContext, notf.ID, user, activities_model.NotificationStatusPinned)
assert.NoError(t, err) require.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{ID: notf.ID, Status: activities_model.NotificationStatusPinned}) &activities_model.Notification{ID: notf.ID, Status: activities_model.NotificationStatusPinned})
_, err = activities_model.SetNotificationStatus(db.DefaultContext, 1, user, activities_model.NotificationStatusRead) _, err = activities_model.SetNotificationStatus(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) _, 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) { func TestUpdateNotificationStatuses(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
notfUnread := unittest.AssertExistsAndLoadBean(t, notfUnread := unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusUnread}) &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}) &activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusRead})
notfPinned := unittest.AssertExistsAndLoadBean(t, notfPinned := unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{UserID: user.ID, Status: activities_model.NotificationStatusPinned}) &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, unittest.AssertExistsAndLoadBean(t,
&activities_model.Notification{ID: notfUnread.ID, Status: activities_model.NotificationStatusRead}) &activities_model.Notification{ID: notfUnread.ID, Status: activities_model.NotificationStatusRead})
unittest.AssertExistsAndLoadBean(t, unittest.AssertExistsAndLoadBean(t,
@ -127,14 +128,14 @@ func TestUpdateNotificationStatuses(t *testing.T) {
} }
func TestSetIssueReadBy(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}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{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) return activities_model.SetIssueReadBy(ctx, issue.ID, user.ID)
})) }))
nt, err := activities_model.GetIssueNotification(db.DefaultContext, user.ID, issue.ID) nt, err := activities_model.GetIssueNotification(db.DefaultContext, user.ID, issue.ID)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, activities_model.NotificationStatusRead, nt.Status) assert.EqualValues(t, activities_model.NotificationStatusRead, nt.Status)
} }

View file

@ -16,6 +16,7 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGetUserHeatmapDataByUser(t *testing.T) { func TestGetUserHeatmapDataByUser(t *testing.T) {
@ -56,7 +57,7 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
}, },
} }
// Prepare // Prepare
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
// Mock time // Mock time
timeutil.MockSet(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)) 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} doer := &user_model.User{ID: tc.doerID}
_, err := unittest.LoadBeanIfExists(doer) _, err := unittest.LoadBeanIfExists(doer)
assert.NoError(t, err) require.NoError(t, err)
if tc.doerID == 0 { if tc.doerID == 0 {
doer = nil doer = nil
} }
@ -80,7 +81,7 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
OnlyPerformedBy: true, OnlyPerformedBy: true,
IncludeDeleted: true, IncludeDeleted: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
// Get the heatmap and compare // Get the heatmap and compare
heatmap, err := activities_model.GetUserHeatmapDataByUser(db.DefaultContext, user, doer) heatmap, err := activities_model.GetUserHeatmapDataByUser(db.DefaultContext, user, doer)
@ -88,14 +89,14 @@ func TestGetUserHeatmapDataByUser(t *testing.T) {
for _, hm := range heatmap { for _, hm := range heatmap {
contributions += int(hm.Contributions) 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.Len(t, actions, contributions, "invalid action count: did the test data became too old?")
assert.Equal(t, count, int64(contributions)) assert.Equal(t, count, int64(contributions))
assert.Equal(t, tc.CountResult, contributions, fmt.Sprintf("testcase '%s'", tc.desc)) assert.Equal(t, tc.CountResult, contributions, fmt.Sprintf("testcase '%s'", tc.desc))
// Test JSON rendering // Test JSON rendering
jsonData, err := json.Marshal(heatmap) jsonData, err := json.Marshal(heatmap)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, tc.JSONResult, string(jsonData)) assert.Equal(t, tc.JSONResult, string(jsonData))
} }
} }

View file

@ -15,6 +15,7 @@ import (
"github.com/ProtonMail/go-crypto/openpgp/packet" "github.com/ProtonMail/go-crypto/openpgp/packet"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestCheckArmoredGPGKeyString(t *testing.T) { func TestCheckArmoredGPGKeyString(t *testing.T) {
@ -50,7 +51,7 @@ MkM/fdpyc2hY7Dl/+qFmN5MG5yGmMpQcX+RNNR222ibNC1D3wg==
-----END PGP PUBLIC KEY BLOCK-----` -----END PGP PUBLIC KEY BLOCK-----`
key, err := checkArmoredGPGKeyString(testGPGArmor) 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 // TODO verify value of key
} }
@ -71,7 +72,7 @@ OyjLLnFQiVmq7kEA/0z0CQe3ZQiQIq5zrs7Nh1XRkFAo8GlU/SGC9XFFi722
-----END PGP PUBLIC KEY BLOCK-----` -----END PGP PUBLIC KEY BLOCK-----`
key, err := checkArmoredGPGKeyString(testGPGArmor) 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 // TODO verify value of key
} }
@ -111,11 +112,11 @@ MkM/fdpyc2hY7Dl/+qFmN5MG5yGmMpQcX+RNNR222ibNC1D3wg==
return return
} }
ekey := keys[0] 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 pubkey := ekey.PrimaryKey
content, err := base64EncPubKey(pubkey) 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{ key := &GPGKey{
KeyID: pubkey.KeyIdString(), KeyID: pubkey.KeyIdString(),
@ -176,27 +177,27 @@ Unknown GPG key with good email
` `
// Reading Sign // Reading Sign
goodSig, err := extractSignature(testGoodSigArmor) 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) 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 // Generating hash of commit
goodHash, err := populateHash(goodSig.Hash, []byte(testGoodPayload)) 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)) 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 // Verify
err = verifySign(goodSig, goodHash, key) 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) 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) 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) { func TestCheckGPGUserEmail(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: 1})
@ -232,7 +233,7 @@ Q0KHb+QcycSgbDx0ZAvdIacuKvBBcbxrsmFUI4LR+oIup0G9gUc0roPvr014jYQL
-----END PGP PUBLIC KEY BLOCK-----` -----END PGP PUBLIC KEY BLOCK-----`
keys, err := AddGPGKey(db.DefaultContext, 1, testEmailWithUpperCaseLetters, "", "") keys, err := AddGPGKey(db.DefaultContext, 1, testEmailWithUpperCaseLetters, "", "")
assert.NoError(t, err) require.NoError(t, err)
if assert.NotEmpty(t, keys) { if assert.NotEmpty(t, keys) {
key := keys[0] key := keys[0]
if assert.Len(t, key.Emails, 1) { if assert.Len(t, key.Emails, 1) {
@ -242,10 +243,10 @@ Q0KHb+QcycSgbDx0ZAvdIacuKvBBcbxrsmFUI4LR+oIup0G9gUc0roPvr014jYQL
} }
func TestCheckGPGRevokedIdentity(t *testing.T) { 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})) require.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: "revoked@golang.com", IsActivated: true}))
_ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) _ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
revokedUserKey := `-----BEGIN PGP PUBLIC KEY BLOCK----- revokedUserKey := `-----BEGIN PGP PUBLIC KEY BLOCK-----
@ -289,7 +290,7 @@ heiQvzkApQup5c+BhH5zFDFdKJ2CBByxw9+7QjMFI/wgLixKuE0Ob2kAokXf7RlB
` `
keys, err := AddGPGKey(db.DefaultContext, 1, revokedUserKey, "", "") keys, err := AddGPGKey(db.DefaultContext, 1, revokedUserKey, "", "")
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, keys, 1) assert.Len(t, keys, 1)
assert.Len(t, keys[0].Emails, 1) assert.Len(t, keys[0].Emails, 1)
assert.EqualValues(t, "no-reply@golang.com", keys[0].Emails[0].Email) assert.EqualValues(t, "no-reply@golang.com", keys[0].Emails[0].Email)
@ -446,7 +447,7 @@ epiDVQ==
-----END PGP PUBLIC KEY BLOCK----- -----END PGP PUBLIC KEY BLOCK-----
` `
keys, err := checkArmoredGPGKeyString(testIssue6599) keys, err := checkArmoredGPGKeyString(testIssue6599)
assert.NoError(t, err) require.NoError(t, err)
if assert.NotEmpty(t, keys) { if assert.NotEmpty(t, keys) {
ekey := keys[0] ekey := keys[0]
expire := getExpiryTime(ekey) expire := getExpiryTime(ekey)

View file

@ -14,10 +14,11 @@ import (
"code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestParseCommitWithSSHSignature(t *testing.T) { func TestParseCommitWithSSHSignature(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
sshKey := unittest.AssertExistsAndLoadBean(t, &PublicKey{ID: 1000, OwnerID: 2}) sshKey := unittest.AssertExistsAndLoadBean(t, &PublicKey{ID: 1000, OwnerID: 2})

View file

@ -16,6 +16,7 @@ import (
"github.com/42wim/sshsig" "github.com/42wim/sshsig"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_SSHParsePublicKey(t *testing.T) { 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(tc.name, func(t *testing.T) {
t.Run("Native", func(t *testing.T) { t.Run("Native", func(t *testing.T) {
keyTypeN, lengthN, err := SSHNativeParsePublicKey(tc.content) keyTypeN, lengthN, err := SSHNativeParsePublicKey(tc.content)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, tc.keyType, keyTypeN) assert.Equal(t, tc.keyType, keyTypeN)
assert.EqualValues(t, tc.length, lengthN) assert.EqualValues(t, tc.length, lengthN)
}) })
@ -146,7 +147,7 @@ AAAAC3NzaC1lZDI1NTE5AAAAICV0MGX/W9IvLA4FXpIuUcdDcbj5KX4syHgsTy7soVgf
`}, `},
} { } {
_, err := CheckPublicKeyString(test.content) _, err := CheckPublicKeyString(test.content)
assert.NoError(t, err) require.NoError(t, err)
} }
setting.SSH.MinimumKeySizeCheck = oldValue setting.SSH.MinimumKeySizeCheck = oldValue
for _, invalidKeys := range []struct { for _, invalidKeys := range []struct {
@ -159,7 +160,7 @@ AAAAC3NzaC1lZDI1NTE5AAAAICV0MGX/W9IvLA4FXpIuUcdDcbj5KX4syHgsTy7soVgf
{"\r\ntest \r\ngitea\r\n\r\n"}, {"\r\ntest \r\ngitea\r\n\r\n"},
} { } {
_, err := CheckPublicKeyString(invalidKeys.content) _, 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(tc.name, func(t *testing.T) {
t.Run("Native", func(t *testing.T) { t.Run("Native", func(t *testing.T) {
fpN, err := calcFingerprintNative(tc.content) fpN, err := calcFingerprintNative(tc.content)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, tc.fp, fpN) assert.Equal(t, tc.fp, fpN)
}) })
if tc.skipSSHKeygen { if tc.skipSSHKeygen {
@ -191,7 +192,7 @@ func Test_calcFingerprint(t *testing.T) {
} }
t.Run("SSHKeygen", func(t *testing.T) { t.Run("SSHKeygen", func(t *testing.T) {
fpK, err := calcFingerprintSSHKeygen(tc.content) fpK, err := calcFingerprintSSHKeygen(tc.content)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, tc.fp, fpK) assert.Equal(t, tc.fp, fpK)
}) })
}) })

View file

@ -11,15 +11,16 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestNewAccessToken(t *testing.T) { func TestNewAccessToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
token := &auth_model.AccessToken{ token := &auth_model.AccessToken{
UID: 3, UID: 3,
Name: "Token C", 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) unittest.AssertExistsAndLoadBean(t, token)
invalidToken := &auth_model.AccessToken{ invalidToken := &auth_model.AccessToken{
@ -27,13 +28,13 @@ func TestNewAccessToken(t *testing.T) {
UID: 2, UID: 2,
Name: "Token F", 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) { func TestAccessTokenByNameExists(t *testing.T) {
name := "Token Gitea" name := "Token Gitea"
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
token := &auth_model.AccessToken{ token := &auth_model.AccessToken{
UID: 3, UID: 3,
Name: name, Name: name,
@ -41,16 +42,16 @@ func TestAccessTokenByNameExists(t *testing.T) {
// Check to make sure it doesn't exists already // Check to make sure it doesn't exists already
exist, err := auth_model.AccessTokenByNameExists(db.DefaultContext, token) exist, err := auth_model.AccessTokenByNameExists(db.DefaultContext, token)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, exist) assert.False(t, exist)
// Save it to the database // 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) unittest.AssertExistsAndLoadBean(t, token)
// This token must be found by name in the DB now // This token must be found by name in the DB now
exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, token) exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, token)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, exist) assert.True(t, exist)
user4Token := &auth_model.AccessToken{ 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 // Name matches but different user ID, this shouldn't exists in the
// database // database
exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, user4Token) exist, err = auth_model.AccessTokenByNameExists(db.DefaultContext, user4Token)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, exist) assert.False(t, exist)
} }
func TestGetAccessTokenBySHA(t *testing.T) { func TestGetAccessTokenBySHA(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "d2c6c1ba3890b309189a8e618c72a162e4efbf36") 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, int64(1), token.UID)
assert.Equal(t, "Token A", token.Name) assert.Equal(t, "Token A", token.Name)
assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash) assert.Equal(t, "2b3668e11cb82d3af8c6e4524fc7841297668f5008d1626f0ad3417e9fa39af84c268248b78c481daa7e5dc437784003494f", token.TokenHash)
assert.Equal(t, "e4efbf36", token.TokenLastEight) assert.Equal(t, "e4efbf36", token.TokenLastEight)
_, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "notahash") _, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "notahash")
assert.Error(t, err) require.Error(t, err)
assert.True(t, auth_model.IsErrAccessTokenNotExist(err)) assert.True(t, auth_model.IsErrAccessTokenNotExist(err))
_, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "") _, err = auth_model.GetAccessTokenBySHA(db.DefaultContext, "")
assert.Error(t, err) require.Error(t, err)
assert.True(t, auth_model.IsErrAccessTokenEmpty(err)) assert.True(t, auth_model.IsErrAccessTokenEmpty(err))
} }
func TestListAccessTokens(t *testing.T) { 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}) 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) { if assert.Len(t, tokens, 2) {
assert.Equal(t, int64(1), tokens[0].UID) assert.Equal(t, int64(1), tokens[0].UID)
assert.Equal(t, int64(1), tokens[1].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}) 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) { if assert.Len(t, tokens, 1) {
assert.Equal(t, int64(2), tokens[0].UID) assert.Equal(t, int64(2), tokens[0].UID)
assert.Equal(t, "Token A", tokens[0].Name) assert.Equal(t, "Token A", tokens[0].Name)
} }
tokens, err = db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 100}) tokens, err = db.Find[auth_model.AccessToken](db.DefaultContext, auth_model.ListAccessTokensOptions{UserID: 100})
assert.NoError(t, err) require.NoError(t, err)
assert.Empty(t, tokens) assert.Empty(t, tokens)
} }
func TestUpdateAccessToken(t *testing.T) { func TestUpdateAccessToken(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c") token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c")
assert.NoError(t, err) require.NoError(t, err)
token.Name = "Token Z" 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) unittest.AssertExistsAndLoadBean(t, token)
} }
func TestDeleteAccessTokenByID(t *testing.T) { func TestDeleteAccessTokenByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c") token, err := auth_model.GetAccessTokenBySHA(db.DefaultContext, "4c6f36e6cf498e2a448662f915d932c09c5a146c")
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(1), token.UID) 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) unittest.AssertNotExistsBean(t, token)
err = auth_model.DeleteAccessTokenByID(db.DefaultContext, 100, 100) err = auth_model.DeleteAccessTokenByID(db.DefaultContext, 100, 100)
assert.Error(t, err) require.Error(t, err)
assert.True(t, auth_model.IsErrAccessTokenNotExist(err)) assert.True(t, auth_model.IsErrAccessTokenNotExist(err))
} }

View file

@ -14,19 +14,20 @@ import (
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestOAuth2Application_GenerateClientSecret(t *testing.T) { 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}) app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
secret, err := app.GenerateClientSecret(db.DefaultContext) secret, err := app.GenerateClientSecret(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, len(secret) > 0) assert.Positive(t, len(secret))
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1, ClientSecret: app.ClientSecret}) unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1, ClientSecret: app.ClientSecret})
} }
func BenchmarkOAuth2Application_GenerateClientSecret(b *testing.B) { 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}) app := unittest.AssertExistsAndLoadBean(b, &auth_model.OAuth2Application{ID: 1})
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
_, _ = app.GenerateClientSecret(db.DefaultContext) _, _ = app.GenerateClientSecret(db.DefaultContext)
@ -77,29 +78,29 @@ func TestOAuth2Application_ContainsRedirect_Slash(t *testing.T) {
} }
func TestOAuth2Application_ValidateClientSecret(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}) app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
secret, err := app.GenerateClientSecret(db.DefaultContext) secret, err := app.GenerateClientSecret(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, app.ValidateClientSecret([]byte(secret))) assert.True(t, app.ValidateClientSecret([]byte(secret)))
assert.False(t, app.ValidateClientSecret([]byte("fewijfowejgfiowjeoifew"))) assert.False(t, app.ValidateClientSecret([]byte("fewijfowejgfiowjeoifew")))
} }
func TestGetOAuth2ApplicationByClientID(t *testing.T) { 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") 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) assert.Equal(t, "da7da3ba-9a13-4167-856f-3899de0b0138", app.ClientID)
app, err = auth_model.GetOAuth2ApplicationByClientID(db.DefaultContext, "invalid client id") app, err = auth_model.GetOAuth2ApplicationByClientID(db.DefaultContext, "invalid client id")
assert.Error(t, err) require.Error(t, err)
assert.Nil(t, app) assert.Nil(t, app)
} }
func TestCreateOAuth2Application(t *testing.T) { 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}) 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.Equal(t, "newapp", app.Name)
assert.Len(t, app.ClientID, 36) assert.Len(t, app.ClientID, 36)
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{Name: "newapp"}) unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{Name: "newapp"})
@ -110,22 +111,22 @@ func TestOAuth2Application_TableName(t *testing.T) {
} }
func TestOAuth2Application_GetGrantByUserID(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}) app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
grant, err := app.GetGrantByUserID(db.DefaultContext, 1) grant, err := app.GetGrantByUserID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(1), grant.UserID) assert.Equal(t, int64(1), grant.UserID)
grant, err = app.GetGrantByUserID(db.DefaultContext, 34923458) grant, err = app.GetGrantByUserID(db.DefaultContext, 34923458)
assert.NoError(t, err) require.NoError(t, err)
assert.Nil(t, grant) assert.Nil(t, grant)
} }
func TestOAuth2Application_CreateGrant(t *testing.T) { 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}) app := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Application{ID: 1})
grant, err := app.CreateGrant(db.DefaultContext, 2, "") grant, err := app.CreateGrant(db.DefaultContext, 2, "")
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, grant) assert.NotNil(t, grant)
assert.Equal(t, int64(2), grant.UserID) assert.Equal(t, int64(2), grant.UserID)
assert.Equal(t, int64(1), grant.ApplicationID) assert.Equal(t, int64(1), grant.ApplicationID)
@ -135,26 +136,26 @@ func TestOAuth2Application_CreateGrant(t *testing.T) {
//////////////////// Grant //////////////////// Grant
func TestGetOAuth2GrantByID(t *testing.T) { func TestGetOAuth2GrantByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
grant, err := auth_model.GetOAuth2GrantByID(db.DefaultContext, 1) grant, err := auth_model.GetOAuth2GrantByID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(1), grant.ID) assert.Equal(t, int64(1), grant.ID)
grant, err = auth_model.GetOAuth2GrantByID(db.DefaultContext, 34923458) grant, err = auth_model.GetOAuth2GrantByID(db.DefaultContext, 34923458)
assert.NoError(t, err) require.NoError(t, err)
assert.Nil(t, grant) assert.Nil(t, grant)
} }
func TestOAuth2Grant_IncreaseCounter(t *testing.T) { 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}) 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) assert.Equal(t, int64(2), grant.Counter)
unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 2}) unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Counter: 2})
} }
func TestOAuth2Grant_ScopeContains(t *testing.T) { 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"}) grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1, Scope: "openid profile"})
assert.True(t, grant.ScopeContains("openid")) assert.True(t, grant.ScopeContains("openid"))
assert.True(t, grant.ScopeContains("profile")) assert.True(t, grant.ScopeContains("profile"))
@ -163,12 +164,12 @@ func TestOAuth2Grant_ScopeContains(t *testing.T) {
} }
func TestOAuth2Grant_GenerateNewAuthorizationCode(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}) grant := unittest.AssertExistsAndLoadBean(t, &auth_model.OAuth2Grant{ID: 1})
code, err := grant.GenerateNewAuthorizationCode(db.DefaultContext, "https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256") code, err := grant.GenerateNewAuthorizationCode(db.DefaultContext, "https://example2.com/callback", "CjvyTLSdR47G5zYenDA-eDWW4lRrO8yvjcWwbD_deOg", "S256")
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, code) 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) { func TestOAuth2Grant_TableName(t *testing.T) {
@ -176,36 +177,36 @@ func TestOAuth2Grant_TableName(t *testing.T) {
} }
func TestGetOAuth2GrantsByUserID(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) result, err := auth_model.GetOAuth2GrantsByUserID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, result, 1) assert.Len(t, result, 1)
assert.Equal(t, int64(1), result[0].ID) assert.Equal(t, int64(1), result[0].ID)
assert.Equal(t, result[0].ApplicationID, result[0].Application.ID) assert.Equal(t, result[0].ApplicationID, result[0].Application.ID)
result, err = auth_model.GetOAuth2GrantsByUserID(db.DefaultContext, 34134) result, err = auth_model.GetOAuth2GrantsByUserID(db.DefaultContext, 34134)
assert.NoError(t, err) require.NoError(t, err)
assert.Empty(t, result) assert.Empty(t, result)
} }
func TestRevokeOAuth2Grant(t *testing.T) { func TestRevokeOAuth2Grant(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, auth_model.RevokeOAuth2Grant(db.DefaultContext, 1, 1)) require.NoError(t, auth_model.RevokeOAuth2Grant(db.DefaultContext, 1, 1))
unittest.AssertNotExistsBean(t, &auth_model.OAuth2Grant{ID: 1, UserID: 1}) unittest.AssertNotExistsBean(t, &auth_model.OAuth2Grant{ID: 1, UserID: 1})
} }
//////////////////// Authorization Code //////////////////// Authorization Code
func TestGetOAuth2AuthorizationByCode(t *testing.T) { func TestGetOAuth2AuthorizationByCode(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
code, err := auth_model.GetOAuth2AuthorizationByCode(db.DefaultContext, "authcode") code, err := auth_model.GetOAuth2AuthorizationByCode(db.DefaultContext, "authcode")
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, code) assert.NotNil(t, code)
assert.Equal(t, "authcode", code.Code) assert.Equal(t, "authcode", code.Code)
assert.Equal(t, int64(1), code.ID) assert.Equal(t, int64(1), code.ID)
code, err = auth_model.GetOAuth2AuthorizationByCode(db.DefaultContext, "does not exist") code, err = auth_model.GetOAuth2AuthorizationByCode(db.DefaultContext, "does not exist")
assert.NoError(t, err) require.NoError(t, err)
assert.Nil(t, code) assert.Nil(t, code)
} }
@ -248,18 +249,18 @@ func TestOAuth2AuthorizationCode_GenerateRedirectURI(t *testing.T) {
} }
redirect, err := code.GenerateRedirectURI("thestate") 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()) assert.Equal(t, "https://example.com/callback?code=thecode&state=thestate", redirect.String())
redirect, err = code.GenerateRedirectURI("") redirect, err = code.GenerateRedirectURI("")
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "https://example.com/callback?code=thecode", redirect.String()) assert.Equal(t, "https://example.com/callback?code=thecode", redirect.String())
} }
func TestOAuth2AuthorizationCode_Invalidate(t *testing.T) { 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"}) 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"}) unittest.AssertNotExistsBean(t, &auth_model.OAuth2AuthorizationCode{Code: "authcode"})
} }
@ -281,18 +282,18 @@ func TestOrphanedOAuth2Applications(t *testing.T) {
Dirs: []string{"models/auth/TestOrphanedOAuth2Applications/"}, Dirs: []string{"models/auth/TestOrphanedOAuth2Applications/"},
}, },
)() )()
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
count, err := auth_model.CountOrphanedOAuth2Applications(db.DefaultContext) count, err := auth_model.CountOrphanedOAuth2Applications(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, count) assert.EqualValues(t, 1, count)
unittest.AssertExistsIf(t, true, &auth_model.OAuth2Application{ID: 1002}) unittest.AssertExistsIf(t, true, &auth_model.OAuth2Application{ID: 1002})
_, err = auth_model.DeleteOrphanedOAuth2Applications(db.DefaultContext) _, err = auth_model.DeleteOrphanedOAuth2Applications(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
count, err = auth_model.CountOrphanedOAuth2Applications(db.DefaultContext) count, err = auth_model.CountOrphanedOAuth2Applications(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 0, count) assert.EqualValues(t, 0, count)
unittest.AssertExistsIf(t, false, &auth_model.OAuth2Application{ID: 1002}) unittest.AssertExistsIf(t, false, &auth_model.OAuth2Application{ID: 1002})
} }

View file

@ -13,10 +13,11 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestAuthSession(t *testing.T) { func TestAuthSession(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
defer timeutil.MockUnset() defer timeutil.MockUnset()
key := "I-Like-Free-Software" key := "I-Like-Free-Software"
@ -24,30 +25,30 @@ func TestAuthSession(t *testing.T) {
t.Run("Create Session", func(t *testing.T) { t.Run("Create Session", func(t *testing.T) {
// Ensure it doesn't exist. // Ensure it doesn't exist.
ok, err := auth.ExistSession(db.DefaultContext, key) ok, err := auth.ExistSession(db.DefaultContext, key)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, ok) assert.False(t, ok)
preCount, err := auth.CountSessions(db.DefaultContext) 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) now := time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)
timeutil.MockSet(now) timeutil.MockSet(now)
// New session is created. // New session is created.
sess, err := auth.ReadSession(db.DefaultContext, key) sess, err := auth.ReadSession(db.DefaultContext, key)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, key, sess.Key) assert.EqualValues(t, key, sess.Key)
assert.Empty(t, sess.Data) assert.Empty(t, sess.Data)
assert.EqualValues(t, now.Unix(), sess.Expiry) assert.EqualValues(t, now.Unix(), sess.Expiry)
// Ensure it exists. // Ensure it exists.
ok, err = auth.ExistSession(db.DefaultContext, key) ok, err = auth.ExistSession(db.DefaultContext, key)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, ok) assert.True(t, ok)
// Ensure the session is taken into account for count.. // Ensure the session is taken into account for count..
postCount, err := auth.CountSessions(db.DefaultContext) postCount, err := auth.CountSessions(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Greater(t, postCount, preCount) assert.Greater(t, postCount, preCount)
}) })
@ -58,14 +59,14 @@ func TestAuthSession(t *testing.T) {
// Update session. // Update session.
err := auth.UpdateSession(db.DefaultContext, key, data) 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)) timeutil.MockSet(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC))
// Read updated session. // Read updated session.
// Ensure data is updated and expiry is set from the update session call. // Ensure data is updated and expiry is set from the update session call.
sess, err := auth.ReadSession(db.DefaultContext, key) sess, err := auth.ReadSession(db.DefaultContext, key)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, key, sess.Key) assert.EqualValues(t, key, sess.Key)
assert.EqualValues(t, data, sess.Data) assert.EqualValues(t, data, sess.Data)
assert.EqualValues(t, now.Unix(), sess.Expiry) assert.EqualValues(t, now.Unix(), sess.Expiry)
@ -76,23 +77,23 @@ func TestAuthSession(t *testing.T) {
t.Run("Delete session", func(t *testing.T) { t.Run("Delete session", func(t *testing.T) {
// Ensure it't exist. // Ensure it't exist.
ok, err := auth.ExistSession(db.DefaultContext, key) ok, err := auth.ExistSession(db.DefaultContext, key)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, ok) assert.True(t, ok)
preCount, err := auth.CountSessions(db.DefaultContext) preCount, err := auth.CountSessions(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
err = auth.DestroySession(db.DefaultContext, key) err = auth.DestroySession(db.DefaultContext, key)
assert.NoError(t, err) require.NoError(t, err)
// Ensure it doesn't exists. // Ensure it doesn't exists.
ok, err = auth.ExistSession(db.DefaultContext, key) ok, err = auth.ExistSession(db.DefaultContext, key)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, ok) assert.False(t, ok)
// Ensure the session is taken into account for count.. // Ensure the session is taken into account for count..
postCount, err := auth.CountSessions(db.DefaultContext) postCount, err := auth.CountSessions(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Less(t, postCount, preCount) 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)) timeutil.MockSet(time.Date(2023, 1, 1, 0, 0, 0, 0, time.UTC))
_, err := auth.ReadSession(db.DefaultContext, "sess-1") _, err := auth.ReadSession(db.DefaultContext, "sess-1")
assert.NoError(t, err) require.NoError(t, err)
// One minute later. // One minute later.
timeutil.MockSet(time.Date(2023, 1, 1, 0, 1, 0, 0, time.UTC)) timeutil.MockSet(time.Date(2023, 1, 1, 0, 1, 0, 0, time.UTC))
_, err = auth.ReadSession(db.DefaultContext, "sess-2") _, err = auth.ReadSession(db.DefaultContext, "sess-2")
assert.NoError(t, err) require.NoError(t, err)
// 5 minutes, shouldn't clean up anything. // 5 minutes, shouldn't clean up anything.
err = auth.CleanupSessions(db.DefaultContext, 5*60) err = auth.CleanupSessions(db.DefaultContext, 5*60)
assert.NoError(t, err) require.NoError(t, err)
ok, err := auth.ExistSession(db.DefaultContext, "sess-1") ok, err := auth.ExistSession(db.DefaultContext, "sess-1")
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, ok) assert.True(t, ok)
ok, err = auth.ExistSession(db.DefaultContext, "sess-2") ok, err = auth.ExistSession(db.DefaultContext, "sess-2")
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, ok) assert.True(t, ok)
// 1 minute, should clean up sess-1. // 1 minute, should clean up sess-1.
err = auth.CleanupSessions(db.DefaultContext, 60) err = auth.CleanupSessions(db.DefaultContext, 60)
assert.NoError(t, err) require.NoError(t, err)
ok, err = auth.ExistSession(db.DefaultContext, "sess-1") ok, err = auth.ExistSession(db.DefaultContext, "sess-1")
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, ok) assert.False(t, ok)
ok, err = auth.ExistSession(db.DefaultContext, "sess-2") ok, err = auth.ExistSession(db.DefaultContext, "sess-2")
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, ok) assert.True(t, ok)
// Now, should clean up sess-2. // Now, should clean up sess-2.
err = auth.CleanupSessions(db.DefaultContext, 0) err = auth.CleanupSessions(db.DefaultContext, 0)
assert.NoError(t, err) require.NoError(t, err)
ok, err = auth.ExistSession(db.DefaultContext, "sess-2") ok, err = auth.ExistSession(db.DefaultContext, "sess-2")
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, ok) assert.False(t, ok)
}) })
} }

View file

@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/xorm/schemas" "xorm.io/xorm/schemas"
) )
@ -35,10 +36,10 @@ func (source *TestSource) ToDB() ([]byte, error) {
} }
func TestDumpAuthSource(t *testing.T) { func TestDumpAuthSource(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
authSourceSchema, err := db.TableInfo(new(auth_model.Source)) authSourceSchema, err := db.TableInfo(new(auth_model.Source))
assert.NoError(t, err) require.NoError(t, err)
auth_model.RegisterTypeConfig(auth_model.OAuth2, new(TestSource)) auth_model.RegisterTypeConfig(auth_model.OAuth2, new(TestSource))

View file

@ -12,25 +12,26 @@ import (
"github.com/go-webauthn/webauthn/webauthn" "github.com/go-webauthn/webauthn/webauthn"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGetWebAuthnCredentialByID(t *testing.T) { func TestGetWebAuthnCredentialByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
res, err := auth_model.GetWebAuthnCredentialByID(db.DefaultContext, 1) res, err := auth_model.GetWebAuthnCredentialByID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "WebAuthn credential", res.Name) assert.Equal(t, "WebAuthn credential", res.Name)
_, err = auth_model.GetWebAuthnCredentialByID(db.DefaultContext, 342432) _, err = auth_model.GetWebAuthnCredentialByID(db.DefaultContext, 342432)
assert.Error(t, err) require.Error(t, err)
assert.True(t, auth_model.IsErrWebAuthnCredentialNotExist(err)) assert.True(t, auth_model.IsErrWebAuthnCredentialNotExist(err))
} }
func TestGetWebAuthnCredentialsByUID(t *testing.T) { func TestGetWebAuthnCredentialsByUID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
res, err := auth_model.GetWebAuthnCredentialsByUID(db.DefaultContext, 32) res, err := auth_model.GetWebAuthnCredentialsByUID(db.DefaultContext, 32)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, res, 1) assert.Len(t, res, 1)
assert.Equal(t, "WebAuthn credential", res[0].Name) assert.Equal(t, "WebAuthn credential", res[0].Name)
} }
@ -40,26 +41,26 @@ func TestWebAuthnCredential_TableName(t *testing.T) {
} }
func TestWebAuthnCredential_UpdateSignCount(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 := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1})
cred.SignCount = 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}) unittest.AssertExistsIf(t, true, &auth_model.WebAuthnCredential{ID: 1, SignCount: 1})
} }
func TestWebAuthnCredential_UpdateLargeCounter(t *testing.T) { 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 := unittest.AssertExistsAndLoadBean(t, &auth_model.WebAuthnCredential{ID: 1})
cred.SignCount = 0xffffffff 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}) unittest.AssertExistsIf(t, true, &auth_model.WebAuthnCredential{ID: 1, SignCount: 0xffffffff})
} }
func TestCreateCredential(t *testing.T) { 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")}) 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, "WebAuthn Created Credential", res.Name)
assert.Equal(t, []byte("Test"), res.CredentialID) assert.Equal(t, []byte("Test"), res.CredentialID)

View file

@ -13,20 +13,21 @@ import (
"code.gitea.io/gitea/modules/setting/config" "code.gitea.io/gitea/modules/setting/config"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
const gravatarSource = "https://secure.gravatar.com/avatar/" const gravatarSource = "https://secure.gravatar.com/avatar/"
func disableGravatar(t *testing.T) { func disableGravatar(t *testing.T) {
err := system_model.SetSettings(db.DefaultContext, map[string]string{setting.Config().Picture.EnableFederatedAvatar.DynKey(): "false"}) 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"}) 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) { func enableGravatar(t *testing.T) {
err := system_model.SetSettings(db.DefaultContext, map[string]string{setting.Config().Picture.DisableGravatar.DynKey(): "false"}) 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 setting.GravatarSource = gravatarSource
} }

View file

@ -11,74 +11,75 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestInTransaction(t *testing.T) { func TestInTransaction(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
assert.False(t, db.InTransaction(db.DefaultContext)) 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)) assert.True(t, db.InTransaction(ctx))
return nil return nil
})) }))
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
defer committer.Close() defer committer.Close()
assert.True(t, db.InTransaction(ctx)) 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)) assert.True(t, db.InTransaction(ctx))
return nil return nil
})) }))
} }
func TestTxContext(t *testing.T) { func TestTxContext(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
{ // create new transaction { // create new transaction
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, db.InTransaction(ctx)) 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 { // reuse the transaction created by TxContext and commit it
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(db.DefaultContext)
engine := db.GetEngine(ctx) engine := db.GetEngine(ctx)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, db.InTransaction(ctx)) assert.True(t, db.InTransaction(ctx))
{ {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(ctx)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, db.InTransaction(ctx)) assert.True(t, db.InTransaction(ctx))
assert.Equal(t, engine, db.GetEngine(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 { // reuse the transaction created by TxContext and close it
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(db.DefaultContext)
engine := db.GetEngine(ctx) engine := db.GetEngine(ctx)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, db.InTransaction(ctx)) assert.True(t, db.InTransaction(ctx))
{ {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(ctx)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, db.InTransaction(ctx)) assert.True(t, db.InTransaction(ctx))
assert.Equal(t, engine, db.GetEngine(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 { // 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)) assert.True(t, db.InTransaction(ctx))
{ {
ctx, committer, err := db.TxContext(ctx) ctx, committer, err := db.TxContext(ctx)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, db.InTransaction(ctx)) assert.True(t, db.InTransaction(ctx))
assert.NoError(t, committer.Commit()) require.NoError(t, committer.Commit())
} }
return nil return nil
})) }))

View file

@ -18,11 +18,12 @@ import (
_ "code.gitea.io/gitea/cmd" // for TestPrimaryKeys _ "code.gitea.io/gitea/cmd" // for TestPrimaryKeys
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/xorm" "xorm.io/xorm"
) )
func TestDumpDatabase(t *testing.T) { func TestDumpDatabase(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
dir := t.TempDir() dir := t.TempDir()
@ -30,31 +31,31 @@ func TestDumpDatabase(t *testing.T) {
ID int64 `xorm:"pk autoincr"` ID int64 `xorm:"pk autoincr"`
Version int64 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 { 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) { 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{}) 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}) _, 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") 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) assert.EqualValues(t, 3, orphaned)
err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id") 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{}) countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{})
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, countBefore, countAfter) assert.EqualValues(t, countBefore, countAfter)
} }

View file

@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
type TestIndex db.ResourceIndex type TestIndex db.ResourceIndex
@ -31,96 +32,96 @@ func getCurrentResourceIndex(ctx context.Context, tableName string, groupID int6
} }
func TestSyncMaxResourceIndex(t *testing.T) { func TestSyncMaxResourceIndex(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
xe := unittest.GetXORMEngine() xe := unittest.GetXORMEngine()
assert.NoError(t, xe.Sync(&TestIndex{})) require.NoError(t, xe.Sync(&TestIndex{}))
err := db.SyncMaxResourceIndex(db.DefaultContext, "test_index", 10, 51) err := db.SyncMaxResourceIndex(db.DefaultContext, "test_index", 10, 51)
assert.NoError(t, err) require.NoError(t, err)
// sync new max index // sync new max index
maxIndex, err := getCurrentResourceIndex(db.DefaultContext, "test_index", 10) maxIndex, err := getCurrentResourceIndex(db.DefaultContext, "test_index", 10)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 51, maxIndex) assert.EqualValues(t, 51, maxIndex)
// smaller index doesn't change // smaller index doesn't change
err = db.SyncMaxResourceIndex(db.DefaultContext, "test_index", 10, 30) 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) maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 51, maxIndex) assert.EqualValues(t, 51, maxIndex)
// larger index changes // larger index changes
err = db.SyncMaxResourceIndex(db.DefaultContext, "test_index", 10, 62) 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) maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 62, maxIndex) assert.EqualValues(t, 62, maxIndex)
// commit transaction // commit transaction
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { err = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
err = db.SyncMaxResourceIndex(ctx, "test_index", 10, 73) err = db.SyncMaxResourceIndex(ctx, "test_index", 10, 73)
assert.NoError(t, err) require.NoError(t, err)
maxIndex, err = getCurrentResourceIndex(ctx, "test_index", 10) maxIndex, err = getCurrentResourceIndex(ctx, "test_index", 10)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 73, maxIndex) assert.EqualValues(t, 73, maxIndex)
return nil return nil
}) })
assert.NoError(t, err) require.NoError(t, err)
maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10) maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 73, maxIndex) assert.EqualValues(t, 73, maxIndex)
// rollback transaction // rollback transaction
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { err = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
err = db.SyncMaxResourceIndex(ctx, "test_index", 10, 84) err = db.SyncMaxResourceIndex(ctx, "test_index", 10, 84)
maxIndex, err = getCurrentResourceIndex(ctx, "test_index", 10) maxIndex, err = getCurrentResourceIndex(ctx, "test_index", 10)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 84, maxIndex) assert.EqualValues(t, 84, maxIndex)
return errors.New("test rollback") return errors.New("test rollback")
}) })
assert.Error(t, err) require.Error(t, err)
maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 10) 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 assert.EqualValues(t, 73, maxIndex) // the max index doesn't change because the transaction was rolled back
} }
func TestGetNextResourceIndex(t *testing.T) { func TestGetNextResourceIndex(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
xe := unittest.GetXORMEngine() xe := unittest.GetXORMEngine()
assert.NoError(t, xe.Sync(&TestIndex{})) require.NoError(t, xe.Sync(&TestIndex{}))
// create a new record // create a new record
maxIndex, err := db.GetNextResourceIndex(db.DefaultContext, "test_index", 20) maxIndex, err := db.GetNextResourceIndex(db.DefaultContext, "test_index", 20)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, maxIndex) assert.EqualValues(t, 1, maxIndex)
// increase the existing record // increase the existing record
maxIndex, err = db.GetNextResourceIndex(db.DefaultContext, "test_index", 20) maxIndex, err = db.GetNextResourceIndex(db.DefaultContext, "test_index", 20)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 2, maxIndex) assert.EqualValues(t, 2, maxIndex)
// commit transaction // commit transaction
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { err = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
maxIndex, err = db.GetNextResourceIndex(ctx, "test_index", 20) maxIndex, err = db.GetNextResourceIndex(ctx, "test_index", 20)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 3, maxIndex) assert.EqualValues(t, 3, maxIndex)
return nil return nil
}) })
assert.NoError(t, err) require.NoError(t, err)
maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 20) maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 20)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 3, maxIndex) assert.EqualValues(t, 3, maxIndex)
// rollback transaction // rollback transaction
err = db.WithTx(db.DefaultContext, func(ctx context.Context) error { err = db.WithTx(db.DefaultContext, func(ctx context.Context) error {
maxIndex, err = db.GetNextResourceIndex(ctx, "test_index", 20) maxIndex, err = db.GetNextResourceIndex(ctx, "test_index", 20)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 4, maxIndex) assert.EqualValues(t, 4, maxIndex)
return errors.New("test rollback") return errors.New("test rollback")
}) })
assert.Error(t, err) require.Error(t, err)
maxIndex, err = getCurrentResourceIndex(db.DefaultContext, "test_index", 20) 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 assert.EqualValues(t, 3, maxIndex) // the max index doesn't change because the transaction was rolled back
} }

View file

@ -12,22 +12,23 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestIterate(t *testing.T) { func TestIterate(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
xe := unittest.GetXORMEngine() 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{}) cnt, err := db.GetEngine(db.DefaultContext).Count(&repo_model.RepoUnit{})
assert.NoError(t, err) require.NoError(t, err)
var repoUnitCnt int var repoUnitCnt int
err = db.Iterate(db.DefaultContext, nil, func(ctx context.Context, repo *repo_model.RepoUnit) error { err = db.Iterate(db.DefaultContext, nil, func(ctx context.Context, repo *repo_model.RepoUnit) error {
repoUnitCnt++ repoUnitCnt++
return nil return nil
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, cnt, repoUnitCnt) assert.EqualValues(t, cnt, repoUnitCnt)
err = db.Iterate(db.DefaultContext, nil, func(ctx context.Context, repoUnit *repo_model.RepoUnit) error { 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 { if !has {
return db.ErrNotExist{Resource: "repo_unit", ID: repoUnit.ID} 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 return nil
}) })
assert.NoError(t, err) require.NoError(t, err)
} }

View file

@ -11,6 +11,7 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/builder" "xorm.io/builder"
) )
@ -27,26 +28,26 @@ func (opts mockListOptions) ToConds() builder.Cond {
} }
func TestFind(t *testing.T) { func TestFind(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
xe := unittest.GetXORMEngine() xe := unittest.GetXORMEngine()
assert.NoError(t, xe.Sync(&repo_model.RepoUnit{})) require.NoError(t, xe.Sync(&repo_model.RepoUnit{}))
var repoUnitCount int var repoUnitCount int
_, err := db.GetEngine(db.DefaultContext).SQL("SELECT COUNT(*) FROM repo_unit").Get(&repoUnitCount) _, 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) assert.NotEmpty(t, repoUnitCount)
opts := mockListOptions{} opts := mockListOptions{}
repoUnits, err := db.Find[repo_model.RepoUnit](db.DefaultContext, opts) repoUnits, err := db.Find[repo_model.RepoUnit](db.DefaultContext, opts)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, repoUnits, repoUnitCount) assert.Len(t, repoUnits, repoUnitCount)
cnt, err := db.Count[repo_model.RepoUnit](db.DefaultContext, opts) cnt, err := db.Count[repo_model.RepoUnit](db.DefaultContext, opts)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, repoUnitCount, cnt) assert.EqualValues(t, repoUnitCount, cnt)
repoUnits, newCnt, err := db.FindAndCount[repo_model.RepoUnit](db.DefaultContext, opts) 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.EqualValues(t, cnt, newCnt)
assert.Len(t, repoUnits, repoUnitCount) assert.Len(t, repoUnits, repoUnitCount)
} }

View file

@ -12,6 +12,7 @@ import (
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func changeDefaultFileBlockSize(n int64) (restore func()) { func changeDefaultFileBlockSize(n int64) (restore func()) {
@ -27,102 +28,102 @@ func TestDbfsBasic(t *testing.T) {
// test basic write/read // test basic write/read
f, err := OpenFile(db.DefaultContext, "test.txt", os.O_RDWR|os.O_CREATE) 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 n, err := f.Write([]byte("0123456789")) // blocks: 0123 4567 89
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 10, n) assert.EqualValues(t, 10, n)
_, err = f.Seek(0, io.SeekStart) _, err = f.Seek(0, io.SeekStart)
assert.NoError(t, err) require.NoError(t, err)
buf, err := io.ReadAll(f) buf, err := io.ReadAll(f)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 10, n) assert.EqualValues(t, 10, n)
assert.EqualValues(t, "0123456789", string(buf)) assert.EqualValues(t, "0123456789", string(buf))
// write some new data // write some new data
_, err = f.Seek(1, io.SeekStart) _, err = f.Seek(1, io.SeekStart)
assert.NoError(t, err) require.NoError(t, err)
_, err = f.Write([]byte("bcdefghi")) // blocks: 0bcd efgh i9 _, err = f.Write([]byte("bcdefghi")) // blocks: 0bcd efgh i9
assert.NoError(t, err) require.NoError(t, err)
// read from offset // read from offset
buf, err = io.ReadAll(f) buf, err = io.ReadAll(f)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "9", string(buf)) assert.EqualValues(t, "9", string(buf))
// read all // read all
_, err = f.Seek(0, io.SeekStart) _, err = f.Seek(0, io.SeekStart)
assert.NoError(t, err) require.NoError(t, err)
buf, err = io.ReadAll(f) buf, err = io.ReadAll(f)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "0bcdefghi9", string(buf)) assert.EqualValues(t, "0bcdefghi9", string(buf))
// write to new size // write to new size
_, err = f.Seek(-1, io.SeekEnd) _, err = f.Seek(-1, io.SeekEnd)
assert.NoError(t, err) require.NoError(t, err)
_, err = f.Write([]byte("JKLMNOP")) // blocks: 0bcd efgh iJKL MNOP _, err = f.Write([]byte("JKLMNOP")) // blocks: 0bcd efgh iJKL MNOP
assert.NoError(t, err) require.NoError(t, err)
_, err = f.Seek(0, io.SeekStart) _, err = f.Seek(0, io.SeekStart)
assert.NoError(t, err) require.NoError(t, err)
buf, err = io.ReadAll(f) buf, err = io.ReadAll(f)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "0bcdefghiJKLMNOP", string(buf)) assert.EqualValues(t, "0bcdefghiJKLMNOP", string(buf))
// write beyond EOF and fill with zero // write beyond EOF and fill with zero
_, err = f.Seek(5, io.SeekCurrent) _, 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 _, 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) _, err = f.Seek(0, io.SeekStart)
assert.NoError(t, err) require.NoError(t, err)
buf, err = io.ReadAll(f) buf, err = io.ReadAll(f)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "0bcdefghiJKLMNOP\x00\x00\x00\x00\x00xyzu", string(buf)) assert.EqualValues(t, "0bcdefghiJKLMNOP\x00\x00\x00\x00\x00xyzu", string(buf))
// write to the block with zeros // write to the block with zeros
_, err = f.Seek(-6, io.SeekCurrent) _, 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 _, 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) _, err = f.Seek(0, io.SeekStart)
assert.NoError(t, err) require.NoError(t, err)
buf, err = io.ReadAll(f) buf, err = io.ReadAll(f)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "0bcdefghiJKLMNOP\x00\x00\x00ABCDzu", string(buf)) assert.EqualValues(t, "0bcdefghiJKLMNOP\x00\x00\x00ABCDzu", string(buf))
assert.NoError(t, f.Close()) require.NoError(t, f.Close())
// test rename // test rename
err = Rename(db.DefaultContext, "test.txt", "test2.txt") 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) _, 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) f, err = OpenFile(db.DefaultContext, "test2.txt", os.O_RDONLY)
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, f.Close()) require.NoError(t, f.Close())
// test remove // test remove
err = Remove(db.DefaultContext, "test2.txt") err = Remove(db.DefaultContext, "test2.txt")
assert.NoError(t, err) require.NoError(t, err)
_, err = OpenFile(db.DefaultContext, "test2.txt", os.O_RDONLY) _, err = OpenFile(db.DefaultContext, "test2.txt", os.O_RDONLY)
assert.Error(t, err) require.Error(t, err)
// test stat // test stat
f, err = OpenFile(db.DefaultContext, "test/test.txt", os.O_RDWR|os.O_CREATE) 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() stat, err := f.Stat()
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "test.txt", stat.Name()) assert.EqualValues(t, "test.txt", stat.Name())
assert.EqualValues(t, 0, stat.Size()) assert.EqualValues(t, 0, stat.Size())
_, err = f.Write([]byte("0123456789")) _, err = f.Write([]byte("0123456789"))
assert.NoError(t, err) require.NoError(t, err)
stat, err = f.Stat() stat, err = f.Stat()
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 10, stat.Size()) assert.EqualValues(t, 10, stat.Size())
} }
@ -130,61 +131,61 @@ func TestDbfsReadWrite(t *testing.T) {
defer changeDefaultFileBlockSize(4)() defer changeDefaultFileBlockSize(4)()
f1, err := OpenFile(db.DefaultContext, "test.log", os.O_RDWR|os.O_CREATE) f1, err := OpenFile(db.DefaultContext, "test.log", os.O_RDWR|os.O_CREATE)
assert.NoError(t, err) require.NoError(t, err)
defer f1.Close() defer f1.Close()
f2, err := OpenFile(db.DefaultContext, "test.log", os.O_RDONLY) f2, err := OpenFile(db.DefaultContext, "test.log", os.O_RDONLY)
assert.NoError(t, err) require.NoError(t, err)
defer f2.Close() defer f2.Close()
_, err = f1.Write([]byte("line 1\n")) _, err = f1.Write([]byte("line 1\n"))
assert.NoError(t, err) require.NoError(t, err)
f2r := bufio.NewReader(f2) f2r := bufio.NewReader(f2)
line, err := f2r.ReadString('\n') line, err := f2r.ReadString('\n')
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "line 1\n", line) assert.EqualValues(t, "line 1\n", line)
_, err = f2r.ReadString('\n') _, err = f2r.ReadString('\n')
assert.ErrorIs(t, err, io.EOF) require.ErrorIs(t, err, io.EOF)
_, err = f1.Write([]byte("line 2\n")) _, err = f1.Write([]byte("line 2\n"))
assert.NoError(t, err) require.NoError(t, err)
line, err = f2r.ReadString('\n') line, err = f2r.ReadString('\n')
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "line 2\n", line) assert.EqualValues(t, "line 2\n", line)
_, err = f2r.ReadString('\n') _, err = f2r.ReadString('\n')
assert.ErrorIs(t, err, io.EOF) require.ErrorIs(t, err, io.EOF)
} }
func TestDbfsSeekWrite(t *testing.T) { func TestDbfsSeekWrite(t *testing.T) {
defer changeDefaultFileBlockSize(4)() defer changeDefaultFileBlockSize(4)()
f, err := OpenFile(db.DefaultContext, "test2.log", os.O_RDWR|os.O_CREATE) f, err := OpenFile(db.DefaultContext, "test2.log", os.O_RDWR|os.O_CREATE)
assert.NoError(t, err) require.NoError(t, err)
defer f.Close() defer f.Close()
n, err := f.Write([]byte("111")) n, err := f.Write([]byte("111"))
assert.NoError(t, err) require.NoError(t, err)
_, err = f.Seek(int64(n), io.SeekStart) _, err = f.Seek(int64(n), io.SeekStart)
assert.NoError(t, err) require.NoError(t, err)
_, err = f.Write([]byte("222")) _, err = f.Write([]byte("222"))
assert.NoError(t, err) require.NoError(t, err)
_, err = f.Seek(int64(n), io.SeekStart) _, err = f.Seek(int64(n), io.SeekStart)
assert.NoError(t, err) require.NoError(t, err)
_, err = f.Write([]byte("333")) _, err = f.Write([]byte("333"))
assert.NoError(t, err) require.NoError(t, err)
fr, err := OpenFile(db.DefaultContext, "test2.log", os.O_RDONLY) fr, err := OpenFile(db.DefaultContext, "test2.log", os.O_RDONLY)
assert.NoError(t, err) require.NoError(t, err)
defer f.Close() defer f.Close()
buf, err := io.ReadAll(fr) buf, err := io.ReadAll(fr)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "111333", string(buf)) assert.EqualValues(t, "111333", string(buf))
} }

View file

@ -14,21 +14,20 @@ import (
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestFixtureGeneration(t *testing.T) { 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) { test := func(ctx context.Context, gen func(ctx context.Context) (string, error), name string) {
expected, err := gen(ctx) expected, err := gen(ctx)
if !assert.NoError(t, err) { require.NoError(t, err)
return
}
p := filepath.Join(unittest.FixturesDir(), name+".yml") p := filepath.Join(unittest.FixturesDir(), name+".yml")
bytes, err := os.ReadFile(p) bytes, err := os.ReadFile(p)
if !assert.NoError(t, err) { require.NoError(t, err)
return
}
data := string(util.NormalizeEOL(bytes)) data := string(util.NormalizeEOL(bytes))
assert.EqualValues(t, expected, data, "Differences detected for %s", p) assert.EqualValues(t, expected, data, "Differences detected for %s", p)
} }

View file

@ -10,37 +10,38 @@ import (
"github.com/hashicorp/go-version" "github.com/hashicorp/go-version"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestForgejoSemVerSetGet(t *testing.T) { func TestForgejoSemVerSetGet(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
ctx := db.DefaultContext ctx := db.DefaultContext
newVersion, err := version.NewVersion("v1.2.3") newVersion, err := version.NewVersion("v1.2.3")
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, SetVersionString(ctx, newVersion.String())) require.NoError(t, SetVersionString(ctx, newVersion.String()))
databaseVersion, err := GetVersion(ctx) databaseVersion, err := GetVersion(ctx)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, newVersion.String(), databaseVersion.String()) assert.EqualValues(t, newVersion.String(), databaseVersion.String())
assert.True(t, newVersion.Equal(databaseVersion)) assert.True(t, newVersion.Equal(databaseVersion))
} }
func TestForgejoSemVerMissing(t *testing.T) { func TestForgejoSemVerMissing(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
ctx := db.DefaultContext ctx := db.DefaultContext
e := db.GetEngine(ctx) e := db.GetEngine(ctx)
_, err := e.Exec("delete from forgejo_sem_ver") _, err := e.Exec("delete from forgejo_sem_ver")
assert.NoError(t, err) require.NoError(t, err)
v, err := GetVersion(ctx) v, err := GetVersion(ctx)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "1.0.0", v.String()) assert.EqualValues(t, "1.0.0", v.String())
_, err = e.Exec("drop table forgejo_sem_ver") _, err = e.Exec("drop table forgejo_sem_ver")
assert.NoError(t, err) require.NoError(t, err)
v, err = GetVersion(ctx) v, err = GetVersion(ctx)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, "1.0.0", v.String()) assert.EqualValues(t, "1.0.0", v.String())
} }

View file

@ -8,7 +8,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" 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. // 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. // Ensure error if there's no row in Forgejo Version.
err := EnsureUpToDate(x) err := EnsureUpToDate(x)
assert.Error(t, err) require.Error(t, err)
// Insert 'good' Forgejo Version row. // Insert 'good' Forgejo Version row.
_, err = x.InsertOne(&ForgejoVersion{ID: 1, Version: ExpectedVersion()}) _, err = x.InsertOne(&ForgejoVersion{ID: 1, Version: ExpectedVersion()})
assert.NoError(t, err) require.NoError(t, err)
err = EnsureUpToDate(x) err = EnsureUpToDate(x)
assert.NoError(t, err) require.NoError(t, err)
// Modify forgejo version to have a lower version. // Modify forgejo version to have a lower version.
_, err = x.Exec("UPDATE `forgejo_version` SET version = ? WHERE id = 1", ExpectedVersion()-1) _, err = x.Exec("UPDATE `forgejo_version` SET version = ? WHERE id = 1", ExpectedVersion()-1)
assert.NoError(t, err) require.NoError(t, err)
err = EnsureUpToDate(x) err = EnsureUpToDate(x)
assert.Error(t, err) require.Error(t, err)
} }

View file

@ -9,6 +9,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_RemoveSSHSignaturesFromReleaseNotes(t *testing.T) { 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)) x, deferable := migration_tests.PrepareTestEnv(t, 0, new(Release))
defer deferable() defer deferable()
assert.NoError(t, RemoveSSHSignaturesFromReleaseNotes(x)) require.NoError(t, RemoveSSHSignaturesFromReleaseNotes(x))
var releases []Release var releases []Release
err := x.Table("release").OrderBy("id ASC").Find(&releases) err := x.Table("release").OrderBy("id ASC").Find(&releases)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, releases, 3) assert.Len(t, releases, 3)
assert.Equal(t, "", releases[0].Note) assert.Equal(t, "", releases[0].Note)

View file

@ -16,17 +16,18 @@ import (
"code.gitea.io/gitea/modules/optional" "code.gitea.io/gitea/modules/optional"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestAddDeletedBranch(t *testing.T) { func TestAddDeletedBranch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
assert.EqualValues(t, git.Sha1ObjectFormat.Name(), repo.ObjectFormatName) assert.EqualValues(t, git.Sha1ObjectFormat.Name(), repo.ObjectFormatName)
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1}) firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1})
assert.True(t, firstBranch.IsDeleted) assert.True(t, firstBranch.IsDeleted)
assert.NoError(t, git_model.AddDeletedBranch(db.DefaultContext, repo.ID, firstBranch.Name, firstBranch.DeletedByID)) require.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, "branch2", int64(1)))
secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: repo.ID, Name: "branch2"}) secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: repo.ID, Name: "branch2"})
assert.True(t, secondBranch.IsDeleted) 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) _, 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) { func TestGetDeletedBranches(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
branches, err := db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{ branches, err := db.Find[git_model.Branch](db.DefaultContext, git_model.FindBranchOptions{
@ -52,19 +53,19 @@ func TestGetDeletedBranches(t *testing.T) {
RepoID: repo.ID, RepoID: repo.ID,
IsDeletedBranch: optional.Some(true), IsDeletedBranch: optional.Some(true),
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, branches, 2) assert.Len(t, branches, 2)
} }
func TestGetDeletedBranch(t *testing.T) { func TestGetDeletedBranch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1}) firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1})
assert.NotNil(t, getDeletedBranch(t, firstBranch)) assert.NotNil(t, getDeletedBranch(t, firstBranch))
} }
func TestDeletedBranchLoadUser(t *testing.T) { func TestDeletedBranchLoadUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1}) firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1})
secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 2}) secondBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 2})
@ -83,13 +84,13 @@ func TestDeletedBranchLoadUser(t *testing.T) {
} }
func TestRemoveDeletedBranch(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}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1}) firstBranch := unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 1})
err := git_model.RemoveDeletedBranchByID(db.DefaultContext, repo.ID, 1) err := git_model.RemoveDeletedBranchByID(db.DefaultContext, repo.ID, 1)
assert.NoError(t, err) require.NoError(t, err)
unittest.AssertNotExistsBean(t, firstBranch) unittest.AssertNotExistsBean(t, firstBranch)
unittest.AssertExistsAndLoadBean(t, &git_model.Branch{ID: 2}) 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}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
deletedBranch, err := git_model.GetDeletedBranchByID(db.DefaultContext, repo.ID, branch.ID) deletedBranch, err := git_model.GetDeletedBranchByID(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.ID, deletedBranch.ID)
assert.Equal(t, branch.Name, deletedBranch.Name) assert.Equal(t, branch.Name, deletedBranch.Name)
assert.Equal(t, branch.CommitID, deletedBranch.CommitID) 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) { 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") branch, exist, err := git_model.FindRenamedBranch(db.DefaultContext, 1, "dev")
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, exist) assert.True(t, exist)
assert.Equal(t, "master", branch.To) assert.Equal(t, "master", branch.To)
_, exist, err = git_model.FindRenamedBranch(db.DefaultContext, 1, "unknow") _, exist, err = git_model.FindRenamedBranch(db.DefaultContext, 1, "unknow")
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, exist) assert.False(t, exist)
} }
func TestRenameBranch(t *testing.T) { func TestRenameBranch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
_isDefault := false _isDefault := false
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(db.DefaultContext)
defer committer.Close() defer committer.Close()
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, git_model.UpdateProtectBranch(ctx, repo1, &git_model.ProtectedBranch{ require.NoError(t, git_model.UpdateProtectBranch(ctx, repo1, &git_model.ProtectedBranch{
RepoID: repo1.ID, RepoID: repo1.ID,
RuleName: "master", RuleName: "master",
}, git_model.WhitelistOptions{})) }, 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 _isDefault = isDefault
return nil return nil
})) }))
@ -160,7 +161,7 @@ func TestRenameBranch(t *testing.T) {
} }
func TestOnlyGetDeletedBranchOnCorrectRepo(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. // Get deletedBranch with ID of 1 on repo with ID 2.
// This should return a nil branch as this deleted branch // 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) deletedBranch, err := git_model.GetDeletedBranchByID(db.DefaultContext, repo2.ID, 1)
// Expect error, and the returned branch is nil. // Expect error, and the returned branch is nil.
assert.Error(t, err) require.Error(t, err)
assert.Nil(t, deletedBranch) assert.Nil(t, deletedBranch)
// Now get the deletedBranch with ID of 1 on repo with ID 1. // 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) deletedBranch, err = git_model.GetDeletedBranchByID(db.DefaultContext, repo1.ID, 1)
// Expect no error, and the returned branch to be not nil. // Expect no error, and the returned branch to be not nil.
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, deletedBranch) assert.NotNil(t, deletedBranch)
} }
func TestFindBranchesByRepoAndBranchName(t *testing.T) { 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. // With no repos or branches given, we find no branches.
branches, err := git_model.FindBranchesByRepoAndBranchName(db.DefaultContext, map[int64]string{}) branches, err := git_model.FindBranchesByRepoAndBranchName(db.DefaultContext, map[int64]string{})
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, branches, 0) assert.Empty(t, branches)
} }

View file

@ -17,10 +17,11 @@ import (
"code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGetCommitStatuses(t *testing.T) { func TestGetCommitStatuses(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
@ -31,8 +32,8 @@ func TestGetCommitStatuses(t *testing.T) {
RepoID: repo1.ID, RepoID: repo1.ID,
SHA: sha1, SHA: sha1,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int(maxResults), 5) assert.Equal(t, 5, int(maxResults))
assert.Len(t, statuses, 5) assert.Len(t, statuses, 5)
assert.Equal(t, "ci/awesomeness", statuses[0].Context) assert.Equal(t, "ci/awesomeness", statuses[0].Context)
@ -60,8 +61,8 @@ func TestGetCommitStatuses(t *testing.T) {
RepoID: repo1.ID, RepoID: repo1.ID,
SHA: sha1, SHA: sha1,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int(maxResults), 5) assert.Equal(t, 5, int(maxResults))
assert.Empty(t, statuses) assert.Empty(t, statuses)
} }
@ -189,16 +190,16 @@ func Test_CalcCommitStatus(t *testing.T) {
} }
func TestFindRepoRecentCommitStatusContexts(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}) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo2) gitRepo, err := gitrepo.OpenRepository(git.DefaultContext, repo2)
assert.NoError(t, err) require.NoError(t, err)
defer gitRepo.Close() defer gitRepo.Close()
commit, err := gitRepo.GetBranchCommit(repo2.DefaultBranch) commit, err := gitRepo.GetBranchCommit(repo2.DefaultBranch)
assert.NoError(t, err) require.NoError(t, err)
defer func() { defer func() {
_, err := db.DeleteByBean(db.DefaultContext, &git_model.CommitStatus{ _, err := db.DeleteByBean(db.DefaultContext, &git_model.CommitStatus{
@ -206,7 +207,7 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
CreatorID: user2.ID, CreatorID: user2.ID,
SHA: commit.ID.String(), SHA: commit.ID.String(),
}) })
assert.NoError(t, err) require.NoError(t, err)
}() }()
err = git_model.NewCommitStatus(db.DefaultContext, git_model.NewCommitStatusOptions{ err = git_model.NewCommitStatus(db.DefaultContext, git_model.NewCommitStatusOptions{
@ -219,7 +220,7 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
Context: "compliance/lint-backend", Context: "compliance/lint-backend",
}, },
}) })
assert.NoError(t, err) require.NoError(t, err)
err = git_model.NewCommitStatus(db.DefaultContext, git_model.NewCommitStatusOptions{ err = git_model.NewCommitStatus(db.DefaultContext, git_model.NewCommitStatusOptions{
Repo: repo2, Repo: repo2,
@ -231,10 +232,10 @@ func TestFindRepoRecentCommitStatusContexts(t *testing.T) {
Context: "compliance/lint-backend", Context: "compliance/lint-backend",
}, },
}) })
assert.NoError(t, err) require.NoError(t, err)
contexts, err := git_model.FindRepoRecentCommitStatusContexts(db.DefaultContext, repo2.ID, time.Hour) 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) { if assert.Len(t, contexts, 1) {
assert.Equal(t, "compliance/lint-backend", contexts[0]) assert.Equal(t, "compliance/lint-backend", contexts[0])
} }

View file

@ -14,6 +14,7 @@ import (
"code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestIterateRepositoryIDsWithLFSMetaObjects(t *testing.T) { func TestIterateRepositoryIDsWithLFSMetaObjects(t *testing.T) {
@ -24,7 +25,7 @@ func TestIterateRepositoryIDsWithLFSMetaObjects(t *testing.T) {
Dirs: []string{"models/git/TestIterateRepositoryIDsWithLFSMetaObjects/"}, Dirs: []string{"models/git/TestIterateRepositoryIDsWithLFSMetaObjects/"},
}, },
)() )()
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
type repocount struct { type repocount struct {
repoid int64 repoid int64
@ -40,7 +41,7 @@ func TestIterateRepositoryIDsWithLFSMetaObjects(t *testing.T) {
cases = append(cases, repocount{repoID, count}) cases = append(cases, repocount{repoID, count})
return nil return nil
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, expected, cases) assert.EqualValues(t, expected, cases)
}) })
@ -52,13 +53,13 @@ func TestIterateRepositoryIDsWithLFSMetaObjects(t *testing.T) {
cases = append(cases, repocount{repoID, count}) cases = append(cases, repocount{repoID, count})
return nil return nil
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, expected, cases) assert.EqualValues(t, expected, cases)
}) })
} }
func TestIterateLFSMetaObjectsForRepo(t *testing.T) { func TestIterateLFSMetaObjectsForRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
expectedIDs := []int64{1, 2, 3, 4} expectedIDs := []int64{1, 2, 3, 4}
@ -70,7 +71,7 @@ func TestIterateLFSMetaObjectsForRepo(t *testing.T) {
actualIDs = append(actualIDs, lo.ID) actualIDs = append(actualIDs, lo.ID)
return nil return nil
}, &IterateLFSMetaObjectsForRepoOptions{}) }, &IterateLFSMetaObjectsForRepoOptions{})
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, expectedIDs, actualIDs) assert.EqualValues(t, expectedIDs, actualIDs)
}) })
@ -82,7 +83,7 @@ func TestIterateLFSMetaObjectsForRepo(t *testing.T) {
actualIDs = append(actualIDs, lo.ID) actualIDs = append(actualIDs, lo.ID)
return nil return nil
}, &IterateLFSMetaObjectsForRepoOptions{}) }, &IterateLFSMetaObjectsForRepoOptions{})
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, expectedIDs, actualIDs) assert.EqualValues(t, expectedIDs, actualIDs)
t.Run("Batch handles updates", func(t *testing.T) { 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 { err := IterateLFSMetaObjectsForRepo(db.DefaultContext, 54, func(ctx context.Context, lo *LFSMetaObject) error {
actualIDs = append(actualIDs, lo.ID) actualIDs = append(actualIDs, lo.ID)
_, err := db.DeleteByID[LFSMetaObject](ctx, lo.ID) _, err := db.DeleteByID[LFSMetaObject](ctx, lo.ID)
assert.NoError(t, err) require.NoError(t, err)
return nil return nil
}, &IterateLFSMetaObjectsForRepoOptions{}) }, &IterateLFSMetaObjectsForRepoOptions{})
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, expectedIDs, actualIDs) assert.EqualValues(t, expectedIDs, actualIDs)
}) })
}) })

View file

@ -8,6 +8,7 @@ import (
"testing" "testing"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestBranchRuleMatchPriority(t *testing.T) { func TestBranchRuleMatchPriority(t *testing.T) {
@ -67,7 +68,7 @@ func TestBranchRuleMatchPriority(t *testing.T) {
matchedPB := pbs.GetFirstMatched(kase.BranchName) matchedPB := pbs.GetFirstMatched(kase.BranchName)
if matchedPB == nil { if matchedPB == nil {
if kase.ExpectedMatchIdx >= 0 { 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 { } else {
assert.EqualValues(t, kase.Rules[kase.ExpectedMatchIdx], matchedPB.RuleName) assert.EqualValues(t, kase.Rules[kase.ExpectedMatchIdx], matchedPB.RuleName)

View file

@ -11,36 +11,37 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestIsUserAllowed(t *testing.T) { func TestIsUserAllowed(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
pt := &git_model.ProtectedTag{} pt := &git_model.ProtectedTag{}
allowed, err := git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) allowed, err := git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, allowed) assert.False(t, allowed)
pt = &git_model.ProtectedTag{ pt = &git_model.ProtectedTag{
AllowlistUserIDs: []int64{1}, AllowlistUserIDs: []int64{1},
} }
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, allowed) assert.True(t, allowed)
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, allowed) assert.False(t, allowed)
pt = &git_model.ProtectedTag{ pt = &git_model.ProtectedTag{
AllowlistTeamIDs: []int64{1}, AllowlistTeamIDs: []int64{1},
} }
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, allowed) assert.False(t, allowed)
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, allowed) assert.True(t, allowed)
pt = &git_model.ProtectedTag{ pt = &git_model.ProtectedTag{
@ -48,11 +49,11 @@ func TestIsUserAllowed(t *testing.T) {
AllowlistTeamIDs: []int64{1}, AllowlistTeamIDs: []int64{1},
} }
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, allowed) assert.True(t, allowed)
allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2) allowed, err = git_model.IsUserAllowedModifyTag(db.DefaultContext, pt, 2)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, allowed) assert.True(t, allowed)
} }
@ -136,7 +137,7 @@ func TestIsUserAllowedToControlTag(t *testing.T) {
for n, c := range cases { for n, c := range cases {
isAllowed, err := git_model.IsUserAllowedToControlTag(db.DefaultContext, protectedTags, c.name, c.userid) 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) 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 { for n, c := range cases {
isAllowed, err := git_model.IsUserAllowedToControlTag(db.DefaultContext, protectedTags, c.name, c.userid) 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) assert.Equal(t, c.allowed, isAllowed, "case %d: error should match", n)
} }
}) })

View file

@ -12,42 +12,43 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestUpdateAssignee(t *testing.T) { func TestUpdateAssignee(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
// Fake issue with assignees // Fake issue with assignees
issue, err := issues_model.GetIssueByID(db.DefaultContext, 1) issue, err := issues_model.GetIssueByID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
err = issue.LoadAttributes(db.DefaultContext) err = issue.LoadAttributes(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
// Assign multiple users // Assign multiple users
user2, err := user_model.GetUserByID(db.DefaultContext, 2) 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) _, _, 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) 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) _, _, 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 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) _, _, 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 // Check if he got removed
isAssigned, err := issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user1) isAssigned, err := issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user1)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, isAssigned) assert.False(t, isAssigned)
// Check if they're all there // Check if they're all there
err = issue.LoadAssignees(db.DefaultContext) err = issue.LoadAssignees(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
var expectedAssignees []*user_model.User var expectedAssignees []*user_model.User
expectedAssignees = append(expectedAssignees, user2, org3) expectedAssignees = append(expectedAssignees, user2, org3)
@ -58,37 +59,37 @@ func TestUpdateAssignee(t *testing.T) {
// Check if the user is assigned // Check if the user is assigned
isAssigned, err = issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user2) isAssigned, err = issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, user2)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, isAssigned) assert.True(t, isAssigned)
// This user should not be assigned // This user should not be assigned
isAssigned, err = issues_model.IsUserAssignedToIssue(db.DefaultContext, issue, &user_model.User{ID: 4}) 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) assert.False(t, isAssigned)
} }
func TestMakeIDsFromAPIAssigneesToAdd(t *testing.T) { 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: 1})
_ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) _ = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
IDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{""}) IDs, err := issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{""})
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, []int64{}, IDs) assert.Equal(t, []int64{}, IDs)
_, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{"none_existing_user"}) _, 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"}) IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user1", []string{"user1"})
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, []int64{1}, IDs) assert.Equal(t, []int64{1}, IDs)
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user2", []string{""}) IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "user2", []string{""})
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, []int64{2}, IDs) assert.Equal(t, []int64{2}, IDs)
IDs, err = issues_model.MakeIDsFromAPIAssigneesToAdd(db.DefaultContext, "", []string{"user1", "user2"}) 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) assert.Equal(t, []int64{1, 2}, IDs)
} }

View file

@ -16,7 +16,7 @@ import (
) )
func TestCommentListLoadUser(t *testing.T) { func TestCommentListLoadUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &Issue{}) issue := unittest.AssertExistsAndLoadBean(t, &Issue{})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID})
@ -78,7 +78,7 @@ func TestCommentListLoadUser(t *testing.T) {
comment.AssigneeID = testCase.assignee comment.AssigneeID = testCase.assignee
comment.Assignee = nil comment.Assignee = nil
assert.NoError(t, list.loadAssignees(db.DefaultContext)) require.NoError(t, list.loadAssignees(db.DefaultContext))
require.NotNil(t, comment.Assignee) require.NotNil(t, comment.Assignee)
assert.Equal(t, testCase.user.ID, comment.Assignee.ID) assert.Equal(t, testCase.user.ID, comment.Assignee.ID)
}) })

View file

@ -15,10 +15,11 @@ import (
"code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestCreateComment(t *testing.T) { func TestCreateComment(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID})
@ -32,7 +33,7 @@ func TestCreateComment(t *testing.T) {
Issue: issue, Issue: issue,
Content: "Hello", Content: "Hello",
}) })
assert.NoError(t, err) require.NoError(t, err)
then := time.Now().Unix() then := time.Now().Unix()
assert.EqualValues(t, issues_model.CommentTypeComment, comment.Type) assert.EqualValues(t, issues_model.CommentTypeComment, comment.Type)
@ -47,12 +48,12 @@ func TestCreateComment(t *testing.T) {
} }
func TestFetchCodeConversations(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}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
res, err := issues_model.FetchCodeConversations(db.DefaultContext, issue, user, false) 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")
assert.Contains(t, res["README.md"], int64(4)) assert.Contains(t, res["README.md"], int64(4))
assert.Len(t, res["README.md"][4], 1) 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}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
res, err = issues_model.FetchCodeConversations(db.DefaultContext, issue, user2, false) res, err = issues_model.FetchCodeConversations(db.DefaultContext, issue, user2, false)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, res, 1) assert.Len(t, res, 1)
} }
func TestAsCommentType(t *testing.T) { 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(""))
assert.Equal(t, issues_model.CommentTypeUndefined, issues_model.AsCommentType("nonsense")) assert.Equal(t, issues_model.CommentTypeUndefined, issues_model.AsCommentType("nonsense"))
assert.Equal(t, issues_model.CommentTypeComment, issues_model.AsCommentType("comment")) 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) { 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 := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
_ = issue.LoadRepo(db.DefaultContext) _ = issue.LoadRepo(db.DefaultContext)
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: issue.Repo.OwnerID}) 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}) 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}) issueModified := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
assert.EqualValues(t, issue.NumComments+1, issueModified.NumComments) assert.EqualValues(t, issue.NumComments+1, issueModified.NumComments)
@ -100,7 +101,7 @@ func TestMigrate_InsertIssueComments(t *testing.T) {
} }
func TestUpdateCommentsMigrationsByType(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}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: issue.RepoID})
@ -115,9 +116,9 @@ func TestUpdateCommentsMigrationsByType(t *testing.T) {
comment.OriginalAuthorID = 1 comment.OriginalAuthorID = 1
comment.PosterID = 0 comment.PosterID = 0
_, err := db.GetEngine(db.DefaultContext).ID(comment.ID).Cols("original_author", "original_author_id", "poster_id").Update(comment) _, 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}) comment = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 1, IssueID: issue.ID})
assert.Empty(t, comment.OriginalAuthor) assert.Empty(t, comment.OriginalAuthor)

View file

@ -12,10 +12,11 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestContentHistory(t *testing.T) { func TestContentHistory(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
dbCtx := db.DefaultContext dbCtx := db.DefaultContext
timeStampNow := timeutil.TimeStampNow() timeStampNow := timeutil.TimeStampNow()
@ -80,7 +81,7 @@ func TestContentHistory(t *testing.T) {
} }
func TestHasIssueContentHistory(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. // 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) _ = issues_model.SaveIssueContentHistory(db.DefaultContext, 1, 11, 100, timeutil.TimeStampNow(), "c-a", true)

View file

@ -12,51 +12,52 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestCreateIssueDependency(t *testing.T) { func TestCreateIssueDependency(t *testing.T) {
// Prepare // Prepare
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user1, err := user_model.GetUserByID(db.DefaultContext, 1) user1, err := user_model.GetUserByID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2) 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 // Create a dependency and check if it was successful
err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2) 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 // Do it again to see if it will check if the dependency already exists
err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2) err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue1, issue2)
assert.Error(t, err) require.Error(t, err)
assert.True(t, issues_model.IsErrDependencyExists(err)) assert.True(t, issues_model.IsErrDependencyExists(err))
// Check for circular dependencies // Check for circular dependencies
err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue2, issue1) err = issues_model.CreateIssueDependency(db.DefaultContext, user1, issue2, issue1)
assert.Error(t, err) require.Error(t, err)
assert.True(t, issues_model.IsErrCircularDependency(err)) assert.True(t, issues_model.IsErrCircularDependency(err))
_ = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{Type: issues_model.CommentTypeAddDependency, PosterID: user1.ID, IssueID: issue1.ID}) _ = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{Type: issues_model.CommentTypeAddDependency, PosterID: user1.ID, IssueID: issue1.ID})
// Check if dependencies left is correct // Check if dependencies left is correct
left, err := issues_model.IssueNoDependenciesLeft(db.DefaultContext, issue1) left, err := issues_model.IssueNoDependenciesLeft(db.DefaultContext, issue1)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, left) assert.False(t, left)
// Close #2 and check again // Close #2 and check again
_, err = issues_model.ChangeIssueStatus(db.DefaultContext, issue2, user1, true) _, 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) left, err = issues_model.IssueNoDependenciesLeft(db.DefaultContext, issue1)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, left) assert.True(t, left)
// Test removing the dependency // Test removing the dependency
err = issues_model.RemoveIssueDependency(db.DefaultContext, user1, issue1, issue2, issues_model.DependencyTypeBlockedBy) err = issues_model.RemoveIssueDependency(db.DefaultContext, user1, issue1, issue2, issues_model.DependencyTypeBlockedBy)
assert.NoError(t, err) require.NoError(t, err)
} }

View file

@ -12,27 +12,28 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGetMaxIssueIndexForRepo(t *testing.T) { func TestGetMaxIssueIndexForRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
maxPR, err := issues_model.GetMaxIssueIndexForRepo(db.DefaultContext, repo.ID) 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) issue := testCreateIssue(t, repo.ID, repo.OwnerID, "title1", "content1", false)
assert.Greater(t, issue.Index, maxPR) assert.Greater(t, issue.Index, maxPR)
maxPR, err = issues_model.GetMaxIssueIndexForRepo(db.DefaultContext, repo.ID) 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) pull := testCreateIssue(t, repo.ID, repo.OwnerID, "title2", "content2", true)
assert.Greater(t, pull.Index, maxPR) assert.Greater(t, pull.Index, maxPR)
maxPR, err = issues_model.GetMaxIssueIndexForRepo(db.DefaultContext, repo.ID) maxPR, err = issues_model.GetMaxIssueIndexForRepo(db.DefaultContext, repo.ID)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, maxPR, pull.Index) assert.Equal(t, maxPR, pull.Index)
} }

View file

@ -12,17 +12,18 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestNewIssueLabelsScope(t *testing.T) { func TestNewIssueLabelsScope(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 18}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 18})
label1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 7}) label1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 7})
label2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8}) label2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) 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.Len(t, issue.Labels, 1)
assert.Equal(t, label2.ID, issue.Labels[0].ID) assert.Equal(t, label2.ID, issue.Labels[0].ID)

View file

@ -17,7 +17,7 @@ import (
) )
func TestIssueList_LoadRepositories(t *testing.T) { func TestIssueList_LoadRepositories(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issueList := issues_model.IssueList{ issueList := issues_model.IssueList{
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}), unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}),
@ -26,7 +26,7 @@ func TestIssueList_LoadRepositories(t *testing.T) {
} }
repos, err := issueList.LoadRepositories(db.DefaultContext) repos, err := issueList.LoadRepositories(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, repos, 2) assert.Len(t, repos, 2)
for _, issue := range issueList { for _, issue := range issueList {
assert.EqualValues(t, issue.RepoID, issue.Repo.ID) assert.EqualValues(t, issue.RepoID, issue.Repo.ID)
@ -34,14 +34,14 @@ func TestIssueList_LoadRepositories(t *testing.T) {
} }
func TestIssueList_LoadAttributes(t *testing.T) { func TestIssueList_LoadAttributes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
setting.Service.EnableTimetracking = true setting.Service.EnableTimetracking = true
issueList := issues_model.IssueList{ issueList := issues_model.IssueList{
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}), unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}),
unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 4}), 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 { for _, issue := range issueList {
assert.EqualValues(t, issue.RepoID, issue.Repo.ID) assert.EqualValues(t, issue.RepoID, issue.Repo.ID)
for _, label := range issue.Labels { 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 { for _, issue := range issueList {
assert.Equal(t, issue.ID == 1, issue.IsRead, "unexpected is_read value for issue[%d]", issue.ID) assert.Equal(t, issue.ID == 1, issue.IsRead, "unexpected is_read value for issue[%d]", issue.ID)
} }
} }
func TestIssueListLoadUser(t *testing.T) { func TestIssueListLoadUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
@ -121,7 +121,7 @@ func TestIssueListLoadUser(t *testing.T) {
issue.PosterID = testCase.poster issue.PosterID = testCase.poster
issue.Poster = nil issue.Poster = nil
assert.NoError(t, list.LoadPosters(db.DefaultContext)) require.NoError(t, list.LoadPosters(db.DefaultContext))
require.NotNil(t, issue.Poster) require.NotNil(t, issue.Poster)
assert.Equal(t, testCase.user.ID, issue.Poster.ID) assert.Equal(t, testCase.user.ID, issue.Poster.ID)
}) })

View file

@ -19,11 +19,12 @@ import (
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/builder" "xorm.io/builder"
) )
func TestIssue_ReplaceLabels(t *testing.T) { func TestIssue_ReplaceLabels(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(issueID int64, labelIDs, expectedLabelIDs []int64) { testSuccess := func(issueID int64, labelIDs, expectedLabelIDs []int64) {
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issueID}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issueID})
@ -34,7 +35,7 @@ func TestIssue_ReplaceLabels(t *testing.T) {
for i, labelID := range labelIDs { for i, labelID := range labelIDs {
labels[i] = unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID, RepoID: repo.ID}) 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)) unittest.AssertCount(t, &issues_model.IssueLabel{IssueID: issueID}, len(expectedLabelIDs))
for _, labelID := range expectedLabelIDs { for _, labelID := range expectedLabelIDs {
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issueID, LabelID: labelID}) 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) { func Test_GetIssueIDsByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
ids, err := issues_model.GetIssueIDsByRepoID(db.DefaultContext, 1) ids, err := issues_model.GetIssueIDsByRepoID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, ids, 5) assert.Len(t, ids, 5)
} }
func TestIssueAPIURL(t *testing.T) { func TestIssueAPIURL(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
err := issue.LoadAttributes(db.DefaultContext) 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)) assert.Equal(t, "https://try.gitea.io/api/v1/repos/user2/repo1/issues/1", issue.APIURL(db.DefaultContext))
} }
func TestGetIssuesByIDs(t *testing.T) { func TestGetIssuesByIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(expectedIssueIDs, nonExistentIssueIDs []int64) { testSuccess := func(expectedIssueIDs, nonExistentIssueIDs []int64) {
issues, err := issues_model.GetIssuesByIDs(db.DefaultContext, append(expectedIssueIDs, nonExistentIssueIDs...), true) issues, err := issues_model.GetIssuesByIDs(db.DefaultContext, append(expectedIssueIDs, nonExistentIssueIDs...), true)
assert.NoError(t, err) require.NoError(t, err)
actualIssueIDs := make([]int64, len(issues)) actualIssueIDs := make([]int64, len(issues))
for i, issue := range issues { for i, issue := range issues {
actualIssueIDs[i] = issue.ID actualIssueIDs[i] = issue.ID
@ -85,21 +86,22 @@ func TestGetIssuesByIDs(t *testing.T) {
} }
func TestGetParticipantIDsByIssue(t *testing.T) { func TestGetParticipantIDsByIssue(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
checkParticipants := func(issueID int64, userIDs []int) { checkParticipants := func(issueID int64, userIDs []int) {
issue, err := issues_model.GetIssueByID(db.DefaultContext, issueID) issue, err := issues_model.GetIssueByID(db.DefaultContext, issueID)
assert.NoError(t, err) require.NoError(t, err)
participants, err := issue.GetParticipantIDsByIssue(db.DefaultContext) participants, err := issue.GetParticipantIDsByIssue(db.DefaultContext)
if assert.NoError(t, err) { require.NoError(t, err)
participantsIDs := make([]int, len(participants))
for i, uid := range participants { participantsIDs := make([]int, len(participants))
participantsIDs[i] = int(uid) for i, uid := range participants {
} participantsIDs[i] = int(uid)
sort.Ints(participantsIDs)
sort.Ints(userIDs)
assert.Equal(t, userIDs, participantsIDs)
} }
sort.Ints(participantsIDs)
sort.Ints(userIDs)
assert.Equal(t, userIDs, participantsIDs)
} }
// User 1 is issue1 poster (see fixtures/issue.yml) // 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 {3, 2}, // pull-request, has no labels
} }
for _, test := range tests { for _, test := range tests {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: test.issueID})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: test.doerID}) 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}) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: test.issueID})
} }
} }
func TestUpdateIssueCols(t *testing.T) { func TestUpdateIssueCols(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{})
const newTitle = "New Title for unit test" const newTitle = "New Title for unit test"
@ -138,7 +140,7 @@ func TestUpdateIssueCols(t *testing.T) {
issue.Content = "This should have no effect" issue.Content = "This should have no effect"
now := time.Now().Unix() 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() then := time.Now().Unix()
updatedIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issue.ID}) updatedIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issue.ID})
@ -148,7 +150,7 @@ func TestUpdateIssueCols(t *testing.T) {
} }
func TestIssues(t *testing.T) { func TestIssues(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
for _, test := range []struct { for _, test := range []struct {
Opts issues_model.IssuesOptions Opts issues_model.IssuesOptions
ExpectedIssueIDs []int64 ExpectedIssueIDs []int64
@ -212,7 +214,7 @@ func TestIssues(t *testing.T) {
}, },
} { } {
issues, err := issues_model.Issues(db.DefaultContext, &test.Opts) 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)) { if assert.Len(t, issues, len(test.ExpectedIssueIDs)) {
for i, issue := range issues { for i, issue := range issues {
assert.EqualValues(t, test.ExpectedIssueIDs[i], issue.ID) assert.EqualValues(t, test.ExpectedIssueIDs[i], issue.ID)
@ -222,10 +224,10 @@ func TestIssues(t *testing.T) {
} }
func TestIssue_loadTotalTimes(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) ms, err := issues_model.GetIssueByID(db.DefaultContext, 2)
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, ms.LoadTotalTimes(db.DefaultContext)) require.NoError(t, ms.LoadTotalTimes(db.DefaultContext))
assert.Equal(t, int64(3682), ms.TotalTrackedTime) assert.Equal(t, int64(3682), ms.TotalTrackedTime)
} }
@ -243,10 +245,10 @@ func testInsertIssue(t *testing.T, title, content string, expectIndex int64) *is
Content: content, Content: content,
} }
err := issues_model.NewIssue(db.DefaultContext, repo, &issue, nil, nil) 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) has, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Get(&newIssue)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, has) assert.True(t, has)
assert.EqualValues(t, issue.Title, newIssue.Title) assert.EqualValues(t, issue.Title, newIssue.Title)
assert.EqualValues(t, issue.Content, newIssue.Content) 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) { 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 // 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) issue := testInsertIssue(t, "my issue1", "special issue's comments?", 6)
_, err := db.DeleteByID[issues_model.Issue](db.DefaultContext, issue.ID) _, err := db.DeleteByID[issues_model.Issue](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) issue = testInsertIssue(t, `my issue2, this is my son's love \n \r \ `, "special issue's '' comments?", 7)
_, err = db.DeleteByID[issues_model.Issue](db.DefaultContext, issue.ID) _, err = db.DeleteByID[issues_model.Issue](db.DefaultContext, issue.ID)
assert.NoError(t, err) require.NoError(t, err)
} }
func TestIssue_ResolveMentions(t *testing.T) { 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) { testSuccess := func(owner, repo, doer string, mentions []string, expected []int64) {
o := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: owner}) 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} issue := &issues_model.Issue{RepoID: r.ID}
d := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: doer}) d := unittest.AssertExistsAndLoadBean(t, &user_model.User{LowerName: doer})
resolved, err := issues_model.ResolveIssueMentionsByVisibility(db.DefaultContext, issue, d, mentions) resolved, err := issues_model.ResolveIssueMentionsByVisibility(db.DefaultContext, issue, d, mentions)
assert.NoError(t, err) require.NoError(t, err)
ids := make([]int64, len(resolved)) ids := make([]int64, len(resolved))
for i, user := range resolved { for i, user := range resolved {
ids[i] = user.ID ids[i] = user.ID
@ -305,21 +307,33 @@ func TestIssue_ResolveMentions(t *testing.T) {
} }
func TestResourceIndex(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 var wg sync.WaitGroup
for i := 0; i < 100; i++ { for i := 0; i < 100; i++ {
wg.Add(1) 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) testInsertIssue(t, fmt.Sprintf("issue %d", i+1), "my issue", 0)
wg.Done() 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) { 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, // Because the condition is to have chunked database look-ups,
// We have to more issues than `maxQueryParameters`, we will insert. // We have to more issues than `maxQueryParameters`, we will insert.
@ -355,7 +369,7 @@ func TestCorrectIssueStats(t *testing.T) {
} }
// Just to be sure. // Just to be sure.
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, issueAmount, total) assert.EqualValues(t, issueAmount, total)
// Now we will call the GetIssueStats with these IDs and if working, // 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. // Now check the values.
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, issueStats.OpenCount, issueAmount) assert.EqualValues(t, issueStats.OpenCount, issueAmount)
} }
func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) { func TestMilestoneList_LoadTotalTrackedTimes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
miles := issues_model.MilestoneList{ miles := issues_model.MilestoneList{
unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}), 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) assert.Equal(t, int64(3682), miles[0].TotalTrackedTime)
} }
func TestLoadTotalTrackedTime(t *testing.T) { func TestLoadTotalTrackedTime(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) 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) assert.Equal(t, int64(3682), milestone.TotalTrackedTime)
} }
func TestCountIssues(t *testing.T) { 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{}) count, err := issues_model.CountIssues(db.DefaultContext, &issues_model.IssuesOptions{})
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 22, count) assert.EqualValues(t, 22, count)
} }
func TestIssueLoadAttributes(t *testing.T) { func TestIssueLoadAttributes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
setting.Service.EnableTimetracking = true setting.Service.EnableTimetracking = true
issueList := issues_model.IssueList{ issueList := issues_model.IssueList{
@ -407,7 +421,7 @@ func TestIssueLoadAttributes(t *testing.T) {
} }
for _, issue := range issueList { 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) assert.EqualValues(t, issue.RepoID, issue.Repo.ID)
for _, label := range issue.Labels { for _, label := range issue.Labels {
assert.EqualValues(t, issue.RepoID, label.RepoID) assert.EqualValues(t, issue.RepoID, label.RepoID)
@ -442,13 +456,13 @@ func TestIssueLoadAttributes(t *testing.T) {
} }
func assertCreateIssues(t *testing.T, isPull bool) { func assertCreateIssues(t *testing.T, isPull bool) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
reponame := "repo1" reponame := "repo1"
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame})
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID})
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1})
milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{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{ reaction := &issues_model.Reaction{
Type: "heart", Type: "heart",
UserID: owner.ID, UserID: owner.ID,
@ -469,7 +483,7 @@ func assertCreateIssues(t *testing.T, isPull bool) {
Reactions: []*issues_model.Reaction{reaction}, Reactions: []*issues_model.Reaction{reaction},
} }
err := issues_model.InsertIssues(db.DefaultContext, is) err := issues_model.InsertIssues(db.DefaultContext, is)
assert.NoError(t, err) require.NoError(t, err)
i := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: title}) i := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: title})
unittest.AssertExistsAndLoadBean(t, &issues_model.Reaction{Type: "heart", UserID: owner.ID, IssueID: i.ID}) unittest.AssertExistsAndLoadBean(t, &issues_model.Reaction{Type: "heart", UserID: owner.ID, IssueID: i.ID})

View file

@ -11,11 +11,11 @@ import (
repo_model "code.gitea.io/gitea/models/repo" repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
func Test_NewIssueUsers(t *testing.T) { 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}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
newIssue := &issues_model.Issue{ newIssue := &issues_model.Issue{
@ -29,7 +29,7 @@ func Test_NewIssueUsers(t *testing.T) {
// artificially insert new issue // artificially insert new issue
unittest.AssertSuccessfulInsert(t, newIssue) 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 // issue_user table should now have entries for new issue
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: newIssue.ID, UID: newIssue.PosterID}) 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) { func TestUpdateIssueUserByRead(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) 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") 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") 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) { func TestUpdateIssueUsersByMentions(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
uids := []int64{2, 5} 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 { for _, uid := range uids {
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1") unittest.AssertExistsAndLoadBean(t, &issues_model.IssueUser{IssueID: issue.ID, UID: uid}, "is_mentioned=1")
} }

View file

@ -11,57 +11,58 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestCreateOrUpdateIssueWatch(t *testing.T) { 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}) iw := unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 3, IssueID: 1})
assert.True(t, iw.IsWatching) 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}) iw = unittest.AssertExistsAndLoadBean(t, &issues_model.IssueWatch{UserID: 1, IssueID: 1})
assert.False(t, iw.IsWatching) assert.False(t, iw.IsWatching)
} }
func TestGetIssueWatch(t *testing.T) { func TestGetIssueWatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
_, exists, err := issues_model.GetIssueWatch(db.DefaultContext, 9, 1) _, exists, err := issues_model.GetIssueWatch(db.DefaultContext, 9, 1)
assert.True(t, exists) assert.True(t, exists)
assert.NoError(t, err) require.NoError(t, err)
iw, exists, err := issues_model.GetIssueWatch(db.DefaultContext, 2, 2) iw, exists, err := issues_model.GetIssueWatch(db.DefaultContext, 2, 2)
assert.True(t, exists) assert.True(t, exists)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, iw.IsWatching) assert.False(t, iw.IsWatching)
_, exists, err = issues_model.GetIssueWatch(db.DefaultContext, 3, 1) _, exists, err = issues_model.GetIssueWatch(db.DefaultContext, 3, 1)
assert.False(t, exists) assert.False(t, exists)
assert.NoError(t, err) require.NoError(t, err)
} }
func TestGetIssueWatchers(t *testing.T) { 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{}) iws, err := issues_model.GetIssueWatchers(db.DefaultContext, 1, db.ListOptions{})
assert.NoError(t, err) require.NoError(t, err)
// Watcher is inactive, thus 0 // Watcher is inactive, thus 0
assert.Len(t, iws, 0) assert.Empty(t, iws)
iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 2, db.ListOptions{}) iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 2, db.ListOptions{})
assert.NoError(t, err) require.NoError(t, err)
// Watcher is explicit not watching // Watcher is explicit not watching
assert.Len(t, iws, 0) assert.Empty(t, iws)
iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 5, db.ListOptions{}) iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 5, db.ListOptions{})
assert.NoError(t, err) require.NoError(t, err)
// Issue has no Watchers // Issue has no Watchers
assert.Len(t, iws, 0) assert.Empty(t, iws)
iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 7, db.ListOptions{}) iws, err = issues_model.GetIssueWatchers(db.DefaultContext, 7, db.ListOptions{})
assert.NoError(t, err) require.NoError(t, err)
// Issue has one watcher // Issue has one watcher
assert.Len(t, iws, 1) assert.Len(t, iws, 1)
} }

View file

@ -15,10 +15,11 @@ import (
"code.gitea.io/gitea/modules/references" "code.gitea.io/gitea/modules/references"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestXRef_AddCrossReferences(t *testing.T) { func TestXRef_AddCrossReferences(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
// Issue #1 to test against // Issue #1 to test against
itarget := testCreateIssue(t, 1, 2, "title1", "content1", false) itarget := testCreateIssue(t, 1, 2, "title1", "content1", false)
@ -69,7 +70,7 @@ func TestXRef_AddCrossReferences(t *testing.T) {
} }
func TestXRef_NeuterCrossReferences(t *testing.T) { func TestXRef_NeuterCrossReferences(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
// Issue #1 to test against // Issue #1 to test against
itarget := testCreateIssue(t, 1, 2, "title1", "content1", false) 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}) d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
i.Title = "title2, no mentions" 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}) ref = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{IssueID: itarget.ID, RefIssueID: i.ID, RefCommentID: 0})
assert.Equal(t, issues_model.CommentTypeIssueRef, ref.Type) assert.Equal(t, issues_model.CommentTypeIssueRef, ref.Type)
@ -91,7 +92,7 @@ func TestXRef_NeuterCrossReferences(t *testing.T) {
} }
func TestXRef_ResolveCrossReferences(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}) 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) i2 := testCreateIssue(t, 1, 2, "title2", "content2", false)
i3 := testCreateIssue(t, 1, 2, "title3", "content3", false) i3 := testCreateIssue(t, 1, 2, "title3", "content3", false)
_, err := issues_model.ChangeIssueStatus(db.DefaultContext, i3, d, true) _, 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)) 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}) 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}) r4 := unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{IssueID: i3.ID, RefIssueID: pr.Issue.ID, RefCommentID: c4.ID})
refs, err := pr.ResolveCrossReferences(db.DefaultContext) refs, err := pr.ResolveCrossReferences(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, refs, 3) assert.Len(t, refs, 3)
assert.Equal(t, rp.ID, refs[0].ID, "bad ref rp: %+v", refs[0]) 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]) 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}) d := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: doer})
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
defer committer.Close() defer committer.Close()
idx, err := db.GetNextResourceIndex(ctx, "issue_index", r.ID) idx, err := db.GetNextResourceIndex(ctx, "issue_index", r.ID)
assert.NoError(t, err) require.NoError(t, err)
i := &issues_model.Issue{ i := &issues_model.Issue{
RepoID: r.ID, RepoID: r.ID,
PosterID: d.ID, PosterID: d.ID,
@ -150,11 +151,11 @@ func testCreateIssue(t *testing.T, repo, doer int64, title, content string, ispu
Repo: r, Repo: r,
Issue: i, Issue: i,
}) })
assert.NoError(t, err) require.NoError(t, err)
i, err = issues_model.GetIssueByID(ctx, i.ID) i, err = issues_model.GetIssueByID(ctx, i.ID)
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, i.AddCrossReferences(ctx, d, false)) require.NoError(t, i.AddCrossReferences(ctx, d, false))
assert.NoError(t, committer.Commit()) require.NoError(t, committer.Commit())
return i 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}) 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} 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} 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 pr.Issue = i
return pr 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} c := &issues_model.Comment{Type: issues_model.CommentTypeComment, PosterID: doer, Poster: d, IssueID: issue, Issue: i, Content: content}
ctx, committer, err := db.TxContext(db.DefaultContext) ctx, committer, err := db.TxContext(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
defer committer.Close() defer committer.Close()
err = db.Insert(ctx, c) err = db.Insert(ctx, c)
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, c.AddCrossReferences(ctx, d, false)) require.NoError(t, c.AddCrossReferences(ctx, d, false))
assert.NoError(t, committer.Commit()) require.NoError(t, committer.Commit())
return c return c
} }

View file

@ -14,17 +14,18 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestLabel_CalOpenIssues(t *testing.T) { 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 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1})
label.CalOpenIssues() label.CalOpenIssues()
assert.EqualValues(t, 2, label.NumOpenIssues) assert.EqualValues(t, 2, label.NumOpenIssues)
} }
func TestLabel_LoadSelectedLabelsAfterClick(t *testing.T) { 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 // Loading the label id:8 (scope/label2) which have a scope and an
// exclusivity with id:7 (scope/label1) // exclusivity with id:7 (scope/label1)
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8}) 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 // First test : with negative and scope
label.LoadSelectedLabelsAfterClick([]int64{1, -8}, []string{"", "scope"}) label.LoadSelectedLabelsAfterClick([]int64{1, -8}, []string{"", "scope"})
assert.Equal(t, "1", label.QueryString) assert.Equal(t, "1", label.QueryString)
assert.Equal(t, true, label.IsSelected) assert.True(t, label.IsSelected)
// Second test : with duplicates // Second test : with duplicates
label.LoadSelectedLabelsAfterClick([]int64{1, 7, 1, 7, 7}, []string{"", "scope", "", "scope", "scope"}) label.LoadSelectedLabelsAfterClick([]int64{1, 7, 1, 7, 7}, []string{"", "scope", "", "scope", "scope"})
assert.Equal(t, "1,8", label.QueryString) assert.Equal(t, "1,8", label.QueryString)
assert.Equal(t, false, label.IsSelected) assert.False(t, label.IsSelected)
// Third test : empty set // Third test : empty set
label.LoadSelectedLabelsAfterClick([]int64{}, []string{}) label.LoadSelectedLabelsAfterClick([]int64{}, []string{})
@ -46,7 +47,7 @@ func TestLabel_LoadSelectedLabelsAfterClick(t *testing.T) {
} }
func TestLabel_ExclusiveScope(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}) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 7})
assert.Equal(t, "scope", label.ExclusiveScope()) assert.Equal(t, "scope", label.ExclusiveScope())
@ -55,22 +56,22 @@ func TestLabel_ExclusiveScope(t *testing.T) {
} }
func TestNewLabels(t *testing.T) { func TestNewLabels(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
labels := []*issues_model.Label{ labels := []*issues_model.Label{
{RepoID: 2, Name: "labelName2", Color: "#123456"}, {RepoID: 2, Name: "labelName2", Color: "#123456"},
{RepoID: 3, Name: "labelName3", Color: "#123"}, {RepoID: 3, Name: "labelName3", Color: "#123"},
{RepoID: 4, Name: "labelName4", Color: "ABCDEF"}, {RepoID: 4, Name: "labelName4", Color: "ABCDEF"},
{RepoID: 5, Name: "labelName5", Color: "DEF"}, {RepoID: 5, Name: "labelName5", Color: "DEF"},
} }
assert.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: ""}))
assert.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: "#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: "#12345G"}))
assert.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: "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: "12345G"}))
for _, label := range labels { for _, label := range labels {
unittest.AssertNotExistsBean(t, label) 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 { for _, label := range labels {
unittest.AssertExistsAndLoadBean(t, label, unittest.Cond("id = ?", label.ID)) unittest.AssertExistsAndLoadBean(t, label, unittest.Cond("id = ?", label.ID))
} }
@ -78,9 +79,9 @@ func TestNewLabels(t *testing.T) {
} }
func TestGetLabelByID(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) label, err := issues_model.GetLabelByID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, label.ID) assert.EqualValues(t, 1, label.ID)
_, err = issues_model.GetLabelByID(db.DefaultContext, unittest.NonexistentID) _, err = issues_model.GetLabelByID(db.DefaultContext, unittest.NonexistentID)
@ -88,9 +89,9 @@ func TestGetLabelByID(t *testing.T) {
} }
func TestGetLabelInRepoByName(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") label, err := issues_model.GetLabelInRepoByName(db.DefaultContext, 1, "label1")
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, label.ID) assert.EqualValues(t, 1, label.ID)
assert.Equal(t, "label1", label.Name) assert.Equal(t, "label1", label.Name)
@ -102,9 +103,9 @@ func TestGetLabelInRepoByName(t *testing.T) {
} }
func TestGetLabelInRepoByNames(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"}) labelIDs, err := issues_model.GetLabelIDsInRepoByNames(db.DefaultContext, 1, []string{"label1", "label2"})
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, labelIDs, 2) assert.Len(t, labelIDs, 2)
@ -113,22 +114,22 @@ func TestGetLabelInRepoByNames(t *testing.T) {
} }
func TestGetLabelInRepoByNamesDiscardsNonExistentLabels(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 // label3 doesn't exists.. See labels.yml
labelIDs, err := issues_model.GetLabelIDsInRepoByNames(db.DefaultContext, 1, []string{"label1", "label2", "label3"}) 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.Len(t, labelIDs, 2)
assert.Equal(t, int64(1), labelIDs[0]) assert.Equal(t, int64(1), labelIDs[0])
assert.Equal(t, int64(2), labelIDs[1]) assert.Equal(t, int64(2), labelIDs[1])
assert.NoError(t, err) require.NoError(t, err)
} }
func TestGetLabelInRepoByID(t *testing.T) { func TestGetLabelInRepoByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
label, err := issues_model.GetLabelInRepoByID(db.DefaultContext, 1, 1) label, err := issues_model.GetLabelInRepoByID(db.DefaultContext, 1, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, label.ID) assert.EqualValues(t, 1, label.ID)
_, err = issues_model.GetLabelInRepoByID(db.DefaultContext, 1, -1) _, err = issues_model.GetLabelInRepoByID(db.DefaultContext, 1, -1)
@ -139,9 +140,9 @@ func TestGetLabelInRepoByID(t *testing.T) {
} }
func TestGetLabelsInRepoByIDs(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}) 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) { if assert.Len(t, labels, 2) {
assert.EqualValues(t, 1, labels[0].ID) assert.EqualValues(t, 1, labels[0].ID)
assert.EqualValues(t, 2, labels[1].ID) assert.EqualValues(t, 2, labels[1].ID)
@ -149,10 +150,10 @@ func TestGetLabelsInRepoByIDs(t *testing.T) {
} }
func TestGetLabelsByRepoID(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) { testSuccess := func(repoID int64, sortType string, expectedIssueIDs []int64) {
labels, err := issues_model.GetLabelsByRepoID(db.DefaultContext, repoID, sortType, db.ListOptions{}) 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)) assert.Len(t, labels, len(expectedIssueIDs))
for i, label := range labels { for i, label := range labels {
assert.EqualValues(t, expectedIssueIDs[i], label.ID) assert.EqualValues(t, expectedIssueIDs[i], label.ID)
@ -167,9 +168,9 @@ func TestGetLabelsByRepoID(t *testing.T) {
// Org versions // Org versions
func TestGetLabelInOrgByName(t *testing.T) { func TestGetLabelInOrgByName(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
label, err := issues_model.GetLabelInOrgByName(db.DefaultContext, 3, "orglabel3") label, err := issues_model.GetLabelInOrgByName(db.DefaultContext, 3, "orglabel3")
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 3, label.ID) assert.EqualValues(t, 3, label.ID)
assert.Equal(t, "orglabel3", label.Name) assert.Equal(t, "orglabel3", label.Name)
@ -187,9 +188,9 @@ func TestGetLabelInOrgByName(t *testing.T) {
} }
func TestGetLabelInOrgByID(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) label, err := issues_model.GetLabelInOrgByID(db.DefaultContext, 3, 3)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 3, label.ID) assert.EqualValues(t, 3, label.ID)
_, err = issues_model.GetLabelInOrgByID(db.DefaultContext, 3, -1) _, err = issues_model.GetLabelInOrgByID(db.DefaultContext, 3, -1)
@ -206,9 +207,9 @@ func TestGetLabelInOrgByID(t *testing.T) {
} }
func TestGetLabelsInOrgByIDs(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}) 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) { if assert.Len(t, labels, 2) {
assert.EqualValues(t, 3, labels[0].ID) assert.EqualValues(t, 3, labels[0].ID)
assert.EqualValues(t, 4, labels[1].ID) assert.EqualValues(t, 4, labels[1].ID)
@ -216,10 +217,10 @@ func TestGetLabelsInOrgByIDs(t *testing.T) {
} }
func TestGetLabelsByOrgID(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) { testSuccess := func(orgID int64, sortType string, expectedIssueIDs []int64) {
labels, err := issues_model.GetLabelsByOrgID(db.DefaultContext, orgID, sortType, db.ListOptions{}) 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)) assert.Len(t, labels, len(expectedIssueIDs))
for i, label := range labels { for i, label := range labels {
assert.EqualValues(t, expectedIssueIDs[i], label.ID) assert.EqualValues(t, expectedIssueIDs[i], label.ID)
@ -241,20 +242,20 @@ func TestGetLabelsByOrgID(t *testing.T) {
// //
func TestGetLabelsByIssueID(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) labels, err := issues_model.GetLabelsByIssueID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, labels, 1) { if assert.Len(t, labels, 1) {
assert.EqualValues(t, 1, labels[0].ID) assert.EqualValues(t, 1, labels[0].ID)
} }
labels, err = issues_model.GetLabelsByIssueID(db.DefaultContext, unittest.NonexistentID) labels, err = issues_model.GetLabelsByIssueID(db.DefaultContext, unittest.NonexistentID)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, labels, 0) assert.Empty(t, labels)
} }
func TestUpdateLabel(t *testing.T) { func TestUpdateLabel(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1})
// make sure update won't overwrite it // make sure update won't overwrite it
update := &issues_model.Label{ update := &issues_model.Label{
@ -267,45 +268,45 @@ func TestUpdateLabel(t *testing.T) {
} }
label.Color = update.Color label.Color = update.Color
label.Name = update.Name 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}) newLabel := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1})
assert.EqualValues(t, label.ID, newLabel.ID) assert.EqualValues(t, label.ID, newLabel.ID)
assert.EqualValues(t, label.Color, newLabel.Color) assert.EqualValues(t, label.Color, newLabel.Color)
assert.EqualValues(t, label.Name, newLabel.Name) assert.EqualValues(t, label.Name, newLabel.Name)
assert.EqualValues(t, label.Description, newLabel.Description) 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{}) unittest.CheckConsistencyFor(t, &issues_model.Label{}, &repo_model.Repository{})
} }
func TestDeleteLabel(t *testing.T) { func TestDeleteLabel(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) 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}) 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}) 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{}) unittest.CheckConsistencyFor(t, &issues_model.Label{}, &repo_model.Repository{})
} }
func TestHasIssueLabel(t *testing.T) { 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.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, 1, 2))
assert.False(t, issues_model.HasIssueLabel(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID)) assert.False(t, issues_model.HasIssueLabel(db.DefaultContext, unittest.NonexistentID, unittest.NonexistentID))
} }
func TestNewIssueLabel(t *testing.T) { func TestNewIssueLabel(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 2}) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 2})
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
// add new IssueLabel // add new IssueLabel
prevNumIssues := label.NumIssues 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.IssueLabel{IssueID: issue.ID, LabelID: label.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{
Type: issues_model.CommentTypeLabel, Type: issues_model.CommentTypeLabel,
@ -318,12 +319,12 @@ func TestNewIssueLabel(t *testing.T) {
assert.EqualValues(t, prevNumIssues+1, label.NumIssues) assert.EqualValues(t, prevNumIssues+1, label.NumIssues)
// re-add existing IssueLabel // 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{}) unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{})
} }
func TestNewIssueExclusiveLabel(t *testing.T) { func TestNewIssueExclusiveLabel(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 18}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 18})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) 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}) exclusiveLabelB := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 8})
// coexisting regular and exclusive label // coexisting regular and exclusive label
assert.NoError(t, issues_model.NewIssueLabel(db.DefaultContext, issue, otherLabel, doer)) require.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, exclusiveLabelA, doer))
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: otherLabel.ID}) 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.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
// exclusive label replaces existing one // 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: otherLabel.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.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}) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.ID})
// exclusive label replaces existing one again // 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: otherLabel.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelA.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}) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issue.ID, LabelID: exclusiveLabelB.ID})
} }
func TestNewIssueLabels(t *testing.T) { func TestNewIssueLabels(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
label1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1}) label1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 1})
label2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 2}) label2 := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: 2})
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 5}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 5})
doer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) 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.IssueLabel{IssueID: issue.ID, LabelID: label1.ID})
unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{
Type: issues_model.CommentTypeLabel, Type: issues_model.CommentTypeLabel,
@ -375,13 +376,13 @@ func TestNewIssueLabels(t *testing.T) {
assert.EqualValues(t, 1, label2.NumClosedIssues) assert.EqualValues(t, 1, label2.NumClosedIssues)
// corner case: test empty slice // 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{}) unittest.CheckConsistencyFor(t, &issues_model.Issue{}, &issues_model.Label{})
} }
func TestDeleteIssueLabel(t *testing.T) { func TestDeleteIssueLabel(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(labelID, issueID, doerID int64) { testSuccess := func(labelID, issueID, doerID int64) {
label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID}) label := unittest.AssertExistsAndLoadBean(t, &issues_model.Label{ID: labelID})
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: issueID}) 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) ctx, committer, err := db.TxContext(db.DefaultContext)
defer committer.Close() defer committer.Close()
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, issues_model.DeleteIssueLabel(ctx, issue, label, doer)) require.NoError(t, issues_model.DeleteIssueLabel(ctx, issue, label, doer))
assert.NoError(t, committer.Commit()) require.NoError(t, committer.Commit())
unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issueID, LabelID: labelID}) unittest.AssertNotExistsBean(t, &issues_model.IssueLabel{IssueID: issueID, LabelID: labelID})
unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{

View file

@ -15,11 +15,11 @@ import (
_ "code.gitea.io/gitea/models/repo" _ "code.gitea.io/gitea/models/repo"
_ "code.gitea.io/gitea/models/user" _ "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
func TestFixturesAreConsistent(t *testing.T) { func TestFixturesAreConsistent(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
unittest.CheckConsistencyFor(t, unittest.CheckConsistencyFor(t,
&issues_model.Issue{}, &issues_model.Issue{},
&issues_model.PullRequest{}, &issues_model.PullRequest{},

View file

@ -17,6 +17,7 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestMilestone_State(t *testing.T) { func TestMilestone_State(t *testing.T) {
@ -25,10 +26,10 @@ func TestMilestone_State(t *testing.T) {
} }
func TestGetMilestoneByRepoID(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) 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.ID)
assert.EqualValues(t, 1, milestone.RepoID) assert.EqualValues(t, 1, milestone.RepoID)
@ -37,7 +38,7 @@ func TestGetMilestoneByRepoID(t *testing.T) {
} }
func TestGetMilestonesByRepoID(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) { test := func(repoID int64, state api.StateType) {
var isClosed optional.Option[bool] var isClosed optional.Option[bool]
switch state { switch state {
@ -49,7 +50,7 @@ func TestGetMilestonesByRepoID(t *testing.T) {
RepoID: repo.ID, RepoID: repo.ID,
IsClosed: isClosed, IsClosed: isClosed,
}) })
assert.NoError(t, err) require.NoError(t, err)
var n int var n int
@ -86,12 +87,12 @@ func TestGetMilestonesByRepoID(t *testing.T) {
RepoID: unittest.NonexistentID, RepoID: unittest.NonexistentID,
IsClosed: optional.Some(false), IsClosed: optional.Some(false),
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, milestones, 0) assert.Empty(t, milestones)
} }
func TestGetMilestones(t *testing.T) { func TestGetMilestones(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
test := func(sortType string, sortCond func(*issues_model.Milestone) int) { test := func(sortType string, sortCond func(*issues_model.Milestone) int) {
for _, page := range []int{0, 1} { for _, page := range []int{0, 1} {
@ -104,7 +105,7 @@ func TestGetMilestones(t *testing.T) {
IsClosed: optional.Some(false), IsClosed: optional.Some(false),
SortType: sortType, SortType: sortType,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, milestones, repo.NumMilestones-repo.NumClosedMilestones) assert.Len(t, milestones, repo.NumMilestones-repo.NumClosedMilestones)
values := make([]int, len(milestones)) values := make([]int, len(milestones))
for i, milestone := range milestones { for i, milestone := range milestones {
@ -122,7 +123,7 @@ func TestGetMilestones(t *testing.T) {
Name: "", Name: "",
SortType: sortType, SortType: sortType,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, milestones, repo.NumClosedMilestones) assert.Len(t, milestones, repo.NumClosedMilestones)
values = make([]int, len(milestones)) values = make([]int, len(milestones))
for i, milestone := range milestones { for i, milestone := range milestones {
@ -152,13 +153,13 @@ func TestGetMilestones(t *testing.T) {
} }
func TestCountRepoMilestones(t *testing.T) { func TestCountRepoMilestones(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64) { test := func(repoID int64) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{ count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
RepoID: repoID, RepoID: repoID,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, repo.NumMilestones, count) assert.EqualValues(t, repo.NumMilestones, count)
} }
test(1) test(1)
@ -168,19 +169,19 @@ func TestCountRepoMilestones(t *testing.T) {
count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{ count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
RepoID: unittest.NonexistentID, RepoID: unittest.NonexistentID,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 0, count) assert.EqualValues(t, 0, count)
} }
func TestCountRepoClosedMilestones(t *testing.T) { func TestCountRepoClosedMilestones(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64) { test := func(repoID int64) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{ count, err := db.Count[issues_model.Milestone](db.DefaultContext, issues_model.FindMilestoneOptions{
RepoID: repoID, RepoID: repoID,
IsClosed: optional.Some(true), IsClosed: optional.Some(true),
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, repo.NumClosedMilestones, count) assert.EqualValues(t, repo.NumClosedMilestones, count)
} }
test(1) test(1)
@ -191,12 +192,12 @@ func TestCountRepoClosedMilestones(t *testing.T) {
RepoID: unittest.NonexistentID, RepoID: unittest.NonexistentID,
IsClosed: optional.Some(true), IsClosed: optional.Some(true),
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 0, count) assert.EqualValues(t, 0, count)
} }
func TestCountMilestonesByRepoIDs(t *testing.T) { func TestCountMilestonesByRepoIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
milestonesCount := func(repoID int64) (int, int) { milestonesCount := func(repoID int64) (int, int) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
return repo.NumOpenMilestones, repo.NumClosedMilestones return repo.NumOpenMilestones, repo.NumClosedMilestones
@ -208,7 +209,7 @@ func TestCountMilestonesByRepoIDs(t *testing.T) {
RepoIDs: []int64{1, 2}, RepoIDs: []int64{1, 2},
IsClosed: optional.Some(false), IsClosed: optional.Some(false),
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, repo1OpenCount, openCounts[1]) assert.EqualValues(t, repo1OpenCount, openCounts[1])
assert.EqualValues(t, repo2OpenCount, openCounts[2]) assert.EqualValues(t, repo2OpenCount, openCounts[2])
@ -217,13 +218,13 @@ func TestCountMilestonesByRepoIDs(t *testing.T) {
RepoIDs: []int64{1, 2}, RepoIDs: []int64{1, 2},
IsClosed: optional.Some(true), IsClosed: optional.Some(true),
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, repo1ClosedCount, closedCounts[1]) assert.EqualValues(t, repo1ClosedCount, closedCounts[1])
assert.EqualValues(t, repo2ClosedCount, closedCounts[2]) assert.EqualValues(t, repo2ClosedCount, closedCounts[2])
} }
func TestGetMilestonesByRepoIDs(t *testing.T) { func TestGetMilestonesByRepoIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2}) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 2})
test := func(sortType string, sortCond func(*issues_model.Milestone) int) { test := func(sortType string, sortCond func(*issues_model.Milestone) int) {
@ -237,7 +238,7 @@ func TestGetMilestonesByRepoIDs(t *testing.T) {
IsClosed: optional.Some(false), IsClosed: optional.Some(false),
SortType: sortType, SortType: sortType,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, openMilestones, repo1.NumOpenMilestones+repo2.NumOpenMilestones) assert.Len(t, openMilestones, repo1.NumOpenMilestones+repo2.NumOpenMilestones)
values := make([]int, len(openMilestones)) values := make([]int, len(openMilestones))
for i, milestone := range openMilestones { for i, milestone := range openMilestones {
@ -255,7 +256,7 @@ func TestGetMilestonesByRepoIDs(t *testing.T) {
IsClosed: optional.Some(true), IsClosed: optional.Some(true),
SortType: sortType, SortType: sortType,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, closedMilestones, repo1.NumClosedMilestones+repo2.NumClosedMilestones) assert.Len(t, closedMilestones, repo1.NumClosedMilestones+repo2.NumClosedMilestones)
values = make([]int, len(closedMilestones)) values = make([]int, len(closedMilestones))
for i, milestone := range closedMilestones { for i, milestone := range closedMilestones {
@ -285,74 +286,74 @@ func TestGetMilestonesByRepoIDs(t *testing.T) {
} }
func TestNewMilestone(t *testing.T) { func TestNewMilestone(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
milestone := &issues_model.Milestone{ milestone := &issues_model.Milestone{
RepoID: 1, RepoID: 1,
Name: "milestoneName", Name: "milestoneName",
Content: "milestoneContent", 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.AssertExistsAndLoadBean(t, milestone)
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{})
} }
func TestChangeMilestoneStatus(t *testing.T) { func TestChangeMilestoneStatus(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
milestone := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}) 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.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}, "is_closed=1")
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{}) 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.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1}, "is_closed=0")
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: milestone.RepoID}, &issues_model.Milestone{})
} }
func TestDeleteMilestoneByRepoID(t *testing.T) { func TestDeleteMilestoneByRepoID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
assert.NoError(t, issues_model.DeleteMilestoneByRepoID(db.DefaultContext, 1, 1)) require.NoError(t, issues_model.DeleteMilestoneByRepoID(db.DefaultContext, 1, 1))
unittest.AssertNotExistsBean(t, &issues_model.Milestone{ID: 1}) unittest.AssertNotExistsBean(t, &issues_model.Milestone{ID: 1})
unittest.CheckConsistencyFor(t, &repo_model.Repository{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) { 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 := unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1})
milestone.Name = " newMilestoneName " milestone.Name = " newMilestoneName "
milestone.Content = "newMilestoneContent" 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}) milestone = unittest.AssertExistsAndLoadBean(t, &issues_model.Milestone{ID: 1})
assert.EqualValues(t, "newMilestoneName", milestone.Name) assert.EqualValues(t, "newMilestoneName", milestone.Name)
unittest.CheckConsistencyFor(t, &issues_model.Milestone{}) unittest.CheckConsistencyFor(t, &issues_model.Milestone{})
} }
func TestUpdateMilestoneCounters(t *testing.T) { func TestUpdateMilestoneCounters(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{MilestoneID: 1}, issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{MilestoneID: 1},
"is_closed=0") "is_closed=0")
issue.IsClosed = true issue.IsClosed = true
issue.ClosedUnix = timeutil.TimeStampNow() issue.ClosedUnix = timeutil.TimeStampNow()
_, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) _, err := db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue)
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, issues_model.UpdateMilestoneCounters(db.DefaultContext, issue.MilestoneID)) require.NoError(t, issues_model.UpdateMilestoneCounters(db.DefaultContext, issue.MilestoneID))
unittest.CheckConsistencyFor(t, &issues_model.Milestone{}) unittest.CheckConsistencyFor(t, &issues_model.Milestone{})
issue.IsClosed = false issue.IsClosed = false
issue.ClosedUnix = 0 issue.ClosedUnix = 0
_, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue) _, err = db.GetEngine(db.DefaultContext).ID(issue.ID).Cols("is_closed", "closed_unix").Update(issue)
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, issues_model.UpdateMilestoneCounters(db.DefaultContext, issue.MilestoneID)) require.NoError(t, issues_model.UpdateMilestoneCounters(db.DefaultContext, issue.MilestoneID))
unittest.CheckConsistencyFor(t, &issues_model.Milestone{}) unittest.CheckConsistencyFor(t, &issues_model.Milestone{})
} }
func TestMigrate_InsertMilestones(t *testing.T) { func TestMigrate_InsertMilestones(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
reponame := "repo1" reponame := "repo1"
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame})
name := "milestonetest1" name := "milestonetest1"
@ -361,7 +362,7 @@ func TestMigrate_InsertMilestones(t *testing.T) {
Name: name, Name: name,
} }
err := issues_model.InsertMilestones(db.DefaultContext, ms) err := issues_model.InsertMilestones(db.DefaultContext, ms)
assert.NoError(t, err) require.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, ms) unittest.AssertExistsAndLoadBean(t, ms)
repoModified := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID}) repoModified := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID})
assert.EqualValues(t, repo.NumMilestones+1, repoModified.NumMilestones) assert.EqualValues(t, repo.NumMilestones+1, repoModified.NumMilestones)

View file

@ -17,42 +17,43 @@ import (
"code.gitea.io/gitea/tests" "code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestPullRequest_LoadAttributes(t *testing.T) { 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}) 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.NotNil(t, pr.Merger)
assert.Equal(t, pr.MergerID, pr.Merger.ID) assert.Equal(t, pr.MergerID, pr.Merger.ID)
} }
func TestPullRequest_LoadIssue(t *testing.T) { 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}) 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.NotNil(t, pr.Issue)
assert.Equal(t, int64(2), pr.Issue.ID) 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.NotNil(t, pr.Issue)
assert.Equal(t, int64(2), pr.Issue.ID) assert.Equal(t, int64(2), pr.Issue.ID)
} }
func TestPullRequest_LoadBaseRepo(t *testing.T) { 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}) 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.NotNil(t, pr.BaseRepo)
assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID) 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.NotNil(t, pr.BaseRepo)
assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID) assert.Equal(t, pr.BaseRepoID, pr.BaseRepo.ID)
} }
func TestPullRequest_LoadHeadRepo(t *testing.T) { 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}) 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.NotNil(t, pr.HeadRepo)
assert.Equal(t, pr.HeadRepoID, pr.HeadRepo.ID) assert.Equal(t, pr.HeadRepoID, pr.HeadRepo.ID)
} }
@ -62,7 +63,7 @@ func TestPullRequest_LoadHeadRepo(t *testing.T) {
// TODO TestNewPullRequest // TODO TestNewPullRequest
func TestPullRequestsNewest(t *testing.T) { 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{ prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: 1, Page: 1,
@ -70,7 +71,7 @@ func TestPullRequestsNewest(t *testing.T) {
State: "open", State: "open",
SortType: "newest", SortType: "newest",
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 3, count) assert.EqualValues(t, 3, count)
if assert.Len(t, prs, 3) { if assert.Len(t, prs, 3) {
assert.EqualValues(t, 5, prs[0].ID) assert.EqualValues(t, 5, prs[0].ID)
@ -80,35 +81,35 @@ func TestPullRequestsNewest(t *testing.T) {
} }
func TestLoadRequestedReviewers(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}) 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 issue := pull.Issue
assert.NoError(t, issue.LoadRepo(db.DefaultContext)) require.NoError(t, issue.LoadRepo(db.DefaultContext))
assert.Len(t, pull.RequestedReviewers, 0) assert.Empty(t, pull.RequestedReviewers)
user1, err := user_model.GetUserByID(db.DefaultContext, 1) 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{}) 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.NotNil(t, comment)
assert.NoError(t, pull.LoadRequestedReviewers(db.DefaultContext)) require.NoError(t, pull.LoadRequestedReviewers(db.DefaultContext))
assert.Len(t, pull.RequestedReviewers, 1) assert.Len(t, pull.RequestedReviewers, 1)
comment, err = issues_model.RemoveReviewRequest(db.DefaultContext, issue, user1, &user_model.User{}) comment, err = issues_model.RemoveReviewRequest(db.DefaultContext, issue, user1, &user_model.User{})
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, comment) assert.NotNil(t, comment)
pull.RequestedReviewers = nil pull.RequestedReviewers = nil
assert.NoError(t, pull.LoadRequestedReviewers(db.DefaultContext)) require.NoError(t, pull.LoadRequestedReviewers(db.DefaultContext))
assert.Empty(t, pull.RequestedReviewers) assert.Empty(t, pull.RequestedReviewers)
} }
func TestPullRequestsOldest(t *testing.T) { 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{ prs, count, err := issues_model.PullRequests(db.DefaultContext, 1, &issues_model.PullRequestsOptions{
ListOptions: db.ListOptions{ ListOptions: db.ListOptions{
Page: 1, Page: 1,
@ -116,7 +117,7 @@ func TestPullRequestsOldest(t *testing.T) {
State: "open", State: "open",
SortType: "oldest", SortType: "oldest",
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 3, count) assert.EqualValues(t, 3, count)
if assert.Len(t, prs, 3) { if assert.Len(t, prs, 3) {
assert.EqualValues(t, 1, prs[0].ID) assert.EqualValues(t, 1, prs[0].ID)
@ -126,32 +127,32 @@ func TestPullRequestsOldest(t *testing.T) {
} }
func TestGetUnmergedPullRequest(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) 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) assert.Equal(t, int64(2), pr.ID)
_, err = issues_model.GetUnmergedPullRequest(db.DefaultContext, 1, 9223372036854775807, "branch1", "master", issues_model.PullRequestFlowGithub) _, 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)) assert.True(t, issues_model.IsErrPullRequestNotExist(err))
} }
func TestHasUnmergedPullRequestsByHeadInfo(t *testing.T) { func TestHasUnmergedPullRequestsByHeadInfo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
exist, err := issues_model.HasUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "branch2") exist, err := issues_model.HasUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "branch2")
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, exist) assert.True(t, exist)
exist, err = issues_model.HasUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "not_exist_branch") exist, err = issues_model.HasUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "not_exist_branch")
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, exist) assert.False(t, exist)
} }
func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) { func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
prs, err := issues_model.GetUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "branch2") prs, err := issues_model.GetUnmergedPullRequestsByHeadInfo(db.DefaultContext, 1, "branch2")
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, prs, 1) assert.Len(t, prs, 1)
for _, pr := range prs { for _, pr := range prs {
assert.Equal(t, int64(1), pr.HeadRepoID) assert.Equal(t, int64(1), pr.HeadRepoID)
@ -161,25 +162,25 @@ func TestGetUnmergedPullRequestsByHeadInfo(t *testing.T) {
func TestGetUnmergedPullRequestsByHeadInfoMax(t *testing.T) { func TestGetUnmergedPullRequestsByHeadInfoMax(t *testing.T) {
defer tests.AddFixtures("models/fixtures/TestGetUnmergedPullRequestsByHeadInfoMax/")() defer tests.AddFixtures("models/fixtures/TestGetUnmergedPullRequestsByHeadInfoMax/")()
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repoID := int64(1) repoID := int64(1)
olderThan := int64(0) olderThan := int64(0)
// for NULL created field the olderThan condition is ignored // for NULL created field the olderThan condition is ignored
prs, err := issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, "branch2") 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) assert.Equal(t, int64(1), prs[0].HeadRepoID)
// test for when the created field is set // test for when the created field is set
branch := "branchmax" branch := "branchmax"
prs, err = issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, branch) prs, err = issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, branch)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, prs, 0) assert.Empty(t, prs)
olderThan = time.Now().UnixNano() olderThan = time.Now().UnixNano()
assert.NoError(t, err) require.NoError(t, err)
prs, err = issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, branch) prs, err = issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, branch)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, prs, 1) assert.Len(t, prs, 1)
for _, pr := range prs { for _, pr := range prs {
assert.Equal(t, int64(1), pr.HeadRepoID) assert.Equal(t, int64(1), pr.HeadRepoID)
@ -235,16 +236,16 @@ func TestGetUnmergedPullRequestsByHeadInfoMax(t *testing.T) {
// expect no match // expect no match
_, err = db.GetEngine(db.DefaultContext).Exec(update, testCase.nomatch, testCase.id) _, 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) prs, err = issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, branch)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, prs, 0) assert.Empty(t, prs)
// expect one match // expect one match
_, err = db.GetEngine(db.DefaultContext).Exec(update, testCase.match, testCase.id) _, 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) prs, err = issues_model.GetUnmergedPullRequestsByHeadInfoMax(db.DefaultContext, repoID, olderThan, branch)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, prs, 1) assert.Len(t, prs, 1)
// identical to the known PR // identical to the known PR
@ -254,9 +255,9 @@ func TestGetUnmergedPullRequestsByHeadInfoMax(t *testing.T) {
} }
func TestGetUnmergedPullRequestsByBaseInfo(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") prs, err := issues_model.GetUnmergedPullRequestsByBaseInfo(db.DefaultContext, 1, "master")
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, prs, 1) assert.Len(t, prs, 1)
pr := prs[0] pr := prs[0]
assert.Equal(t, int64(2), pr.ID) assert.Equal(t, int64(2), pr.ID)
@ -265,46 +266,46 @@ func TestGetUnmergedPullRequestsByBaseInfo(t *testing.T) {
} }
func TestGetPullRequestByIndex(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) 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(1), pr.BaseRepoID)
assert.Equal(t, int64(2), pr.Index) assert.Equal(t, int64(2), pr.Index)
_, err = issues_model.GetPullRequestByIndex(db.DefaultContext, 9223372036854775807, 9223372036854775807) _, err = issues_model.GetPullRequestByIndex(db.DefaultContext, 9223372036854775807, 9223372036854775807)
assert.Error(t, err) require.Error(t, err)
assert.True(t, issues_model.IsErrPullRequestNotExist(err)) assert.True(t, issues_model.IsErrPullRequestNotExist(err))
_, err = issues_model.GetPullRequestByIndex(db.DefaultContext, 1, 0) _, err = issues_model.GetPullRequestByIndex(db.DefaultContext, 1, 0)
assert.Error(t, err) require.Error(t, err)
assert.True(t, issues_model.IsErrPullRequestNotExist(err)) assert.True(t, issues_model.IsErrPullRequestNotExist(err))
} }
func TestGetPullRequestByID(t *testing.T) { func TestGetPullRequestByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
pr, err := issues_model.GetPullRequestByID(db.DefaultContext, 1) 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(1), pr.ID)
assert.Equal(t, int64(2), pr.IssueID) assert.Equal(t, int64(2), pr.IssueID)
_, err = issues_model.GetPullRequestByID(db.DefaultContext, 9223372036854775807) _, err = issues_model.GetPullRequestByID(db.DefaultContext, 9223372036854775807)
assert.Error(t, err) require.Error(t, err)
assert.True(t, issues_model.IsErrPullRequestNotExist(err)) assert.True(t, issues_model.IsErrPullRequestNotExist(err))
} }
func TestGetPullRequestByIssueID(t *testing.T) { func TestGetPullRequestByIssueID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
pr, err := issues_model.GetPullRequestByIssueID(db.DefaultContext, 2) pr, err := issues_model.GetPullRequestByIssueID(db.DefaultContext, 2)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(2), pr.IssueID) assert.Equal(t, int64(2), pr.IssueID)
_, err = issues_model.GetPullRequestByIssueID(db.DefaultContext, 9223372036854775807) _, err = issues_model.GetPullRequestByIssueID(db.DefaultContext, 9223372036854775807)
assert.Error(t, err) require.Error(t, err)
assert.True(t, issues_model.IsErrPullRequestNotExist(err)) assert.True(t, issues_model.IsErrPullRequestNotExist(err))
} }
func TestPullRequest_Update(t *testing.T) { 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 := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
pr.BaseBranch = "baseBranch" pr.BaseBranch = "baseBranch"
pr.HeadBranch = "headBranch" pr.HeadBranch = "headBranch"
@ -317,13 +318,13 @@ func TestPullRequest_Update(t *testing.T) {
} }
func TestPullRequest_UpdateCols(t *testing.T) { func TestPullRequest_UpdateCols(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
pr := &issues_model.PullRequest{ pr := &issues_model.PullRequest{
ID: 1, ID: 1,
BaseBranch: "baseBranch", BaseBranch: "baseBranch",
HeadBranch: "headBranch", 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}) pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1})
assert.Equal(t, "master", pr.BaseBranch) assert.Equal(t, "master", pr.BaseBranch)
@ -332,25 +333,25 @@ func TestPullRequest_UpdateCols(t *testing.T) {
} }
func TestPullRequestList_LoadAttributes(t *testing.T) { func TestPullRequestList_LoadAttributes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
prs := []*issues_model.PullRequest{ prs := []*issues_model.PullRequest{
unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}), unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}),
unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2}), 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 { for _, pr := range prs {
assert.NotNil(t, pr.Issue) assert.NotNil(t, pr.Issue)
assert.Equal(t, pr.IssueID, pr.Issue.ID) 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 // TODO TestAddTestPullRequestTask
func TestPullRequest_IsWorkInProgress(t *testing.T) { 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 := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
pr.LoadIssue(db.DefaultContext) pr.LoadIssue(db.DefaultContext)
@ -365,7 +366,7 @@ func TestPullRequest_IsWorkInProgress(t *testing.T) {
} }
func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(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 := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 2})
pr.LoadIssue(db.DefaultContext) pr.LoadIssue(db.DefaultContext)
@ -381,23 +382,23 @@ func TestPullRequest_GetWorkInProgressPrefixWorkInProgress(t *testing.T) {
} }
func TestDeleteOrphanedObjects(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{}) 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}) _, 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") 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) assert.EqualValues(t, 3, orphaned)
err = db.DeleteOrphanedObjects(db.DefaultContext, "pull_request", "issue", "pull_request.issue_id=issue.id") 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{}) countAfter, err := db.GetEngine(db.DefaultContext).Count(&issues_model.PullRequest{})
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, countBefore, countAfter) assert.EqualValues(t, countBefore, countAfter)
} }
@ -424,7 +425,7 @@ func TestParseCodeOwnersLine(t *testing.T) {
} }
func TestGetApprovers(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}) pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 5})
// Official reviews are already deduplicated. Allow unofficial reviews // Official reviews are already deduplicated. Allow unofficial reviews
// to assert that there are no duplicated approvers. // to assert that there are no duplicated approvers.
@ -435,19 +436,19 @@ func TestGetApprovers(t *testing.T) {
} }
func TestGetPullRequestByMergedCommit(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") pr, err := issues_model.GetPullRequestByMergedCommit(db.DefaultContext, 1, "1a8823cd1a9549fde083f992f6b9b87a7ab74fb3")
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, pr.ID) assert.EqualValues(t, 1, pr.ID)
_, err = issues_model.GetPullRequestByMergedCommit(db.DefaultContext, 0, "1a8823cd1a9549fde083f992f6b9b87a7ab74fb3") _, 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, "") _, 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) { func TestMigrate_InsertPullRequests(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
reponame := "repo1" reponame := "repo1"
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{Name: reponame})
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo.OwnerID}) 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) err := issues_model.InsertPullRequests(db.DefaultContext, p)
assert.NoError(t, err) require.NoError(t, err)
_ = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{IssueID: i.ID}) _ = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{IssueID: i.ID})

View file

@ -14,6 +14,7 @@ import (
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func addReaction(t *testing.T, doerID, issueID, commentID int64, content string) { 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, Type: content,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, reaction) assert.NotNil(t, reaction)
} }
func TestIssueAddReaction(t *testing.T) { func TestIssueAddReaction(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
@ -44,7 +45,7 @@ func TestIssueAddReaction(t *testing.T) {
} }
func TestIssueAddDuplicateReaction(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}) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
@ -57,7 +58,7 @@ func TestIssueAddDuplicateReaction(t *testing.T) {
IssueID: issue1ID, IssueID: issue1ID,
Type: "heart", Type: "heart",
}) })
assert.Error(t, err) require.Error(t, err)
assert.Equal(t, issues_model.ErrReactionAlreadyExist{Reaction: "heart"}, err) assert.Equal(t, issues_model.ErrReactionAlreadyExist{Reaction: "heart"}, err)
existingR := unittest.AssertExistsAndLoadBean(t, &issues_model.Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1ID}) 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) { func TestIssueDeleteReaction(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) 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") addReaction(t, user1.ID, issue1ID, 0, "heart")
err := issues_model.DeleteIssueReaction(db.DefaultContext, user1.ID, issue1ID, "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}) unittest.AssertNotExistsBean(t, &issues_model.Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1ID})
} }
func TestIssueReactionCount(t *testing.T) { func TestIssueReactionCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
setting.UI.ReactionMaxUserNum = 2 setting.UI.ReactionMaxUserNum = 2
@ -104,10 +105,10 @@ func TestIssueReactionCount(t *testing.T) {
reactionsList, _, err := issues_model.FindReactions(db.DefaultContext, issues_model.FindReactionsOptions{ reactionsList, _, err := issues_model.FindReactions(db.DefaultContext, issues_model.FindReactionsOptions{
IssueID: issueID, IssueID: issueID,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, reactionsList, 7) assert.Len(t, reactionsList, 7)
_, err = reactionsList.LoadUsers(db.DefaultContext, repo) _, err = reactionsList.LoadUsers(db.DefaultContext, repo)
assert.NoError(t, err) require.NoError(t, err)
reactions := reactionsList.GroupByType() reactions := reactionsList.GroupByType()
assert.Len(t, reactions["heart"], 4) assert.Len(t, reactions["heart"], 4)
@ -122,7 +123,7 @@ func TestIssueReactionCount(t *testing.T) {
} }
func TestIssueCommentAddReaction(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}) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
@ -135,7 +136,7 @@ func TestIssueCommentAddReaction(t *testing.T) {
} }
func TestIssueCommentDeleteReaction(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}) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
@ -154,7 +155,7 @@ func TestIssueCommentDeleteReaction(t *testing.T) {
IssueID: issue1ID, IssueID: issue1ID,
CommentID: comment1ID, CommentID: comment1ID,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, reactionsList, 4) assert.Len(t, reactionsList, 4)
reactions := reactionsList.GroupByType() reactions := reactionsList.GroupByType()
@ -163,7 +164,7 @@ func TestIssueCommentDeleteReaction(t *testing.T) {
} }
func TestIssueCommentReactionCount(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}) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
@ -171,7 +172,7 @@ func TestIssueCommentReactionCount(t *testing.T) {
var comment1ID int64 = 1 var comment1ID int64 = 1
addReaction(t, user1.ID, issue1ID, comment1ID, "heart") 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}) unittest.AssertNotExistsBean(t, &issues_model.Reaction{Type: "heart", UserID: user1.ID, IssueID: issue1ID, CommentID: comment1ID})
} }

View file

@ -13,40 +13,41 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGetReviewByID(t *testing.T) { func TestGetReviewByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
review, err := issues_model.GetReviewByID(db.DefaultContext, 1) 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, "Demo Review", review.Content)
assert.Equal(t, issues_model.ReviewTypeApprove, review.Type) assert.Equal(t, issues_model.ReviewTypeApprove, review.Type)
_, err = issues_model.GetReviewByID(db.DefaultContext, 23892) _, err = issues_model.GetReviewByID(db.DefaultContext, 23892)
assert.Error(t, err) require.Error(t, err)
assert.True(t, issues_model.IsErrReviewNotExist(err), "IsErrReviewNotExist") assert.True(t, issues_model.IsErrReviewNotExist(err), "IsErrReviewNotExist")
} }
func TestReview_LoadAttributes(t *testing.T) { 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}) 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.Issue)
assert.NotNil(t, review.Reviewer) assert.NotNil(t, review.Reviewer)
invalidReview1 := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 2}) 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}) 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) { 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}) review := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 4})
assert.NoError(t, review.LoadAttributes(db.DefaultContext)) require.NoError(t, review.LoadAttributes(db.DefaultContext))
assert.NoError(t, review.LoadCodeComments(db.DefaultContext)) require.NoError(t, review.LoadCodeComments(db.DefaultContext))
assert.Len(t, review.CodeComments, 1) assert.Len(t, review.CodeComments, 1)
assert.Equal(t, int64(4), review.CodeComments["README.md"][int64(4)][0].Line) 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) { 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{ reviews, err := issues_model.FindReviews(db.DefaultContext, issues_model.FindReviewOptions{
Type: issues_model.ReviewTypeApprove, Type: issues_model.ReviewTypeApprove,
IssueID: 2, IssueID: 2,
ReviewerID: 1, ReviewerID: 1,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, reviews, 1) assert.Len(t, reviews, 1)
assert.Equal(t, "Demo Review", reviews[0].Content) assert.Equal(t, "Demo Review", reviews[0].Content)
} }
func TestFindLatestReviews(t *testing.T) { 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{ reviews, err := issues_model.FindLatestReviews(db.DefaultContext, issues_model.FindReviewOptions{
Type: issues_model.ReviewTypeApprove, Type: issues_model.ReviewTypeApprove,
IssueID: 11, IssueID: 11,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, reviews, 2) assert.Len(t, reviews, 2)
assert.Equal(t, "duplicate review from user5 (latest)", reviews[0].Content) 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) assert.Equal(t, "singular review from org6 and final review for this pr", reviews[1].Content)
} }
func TestGetCurrentReview(t *testing.T) { func TestGetCurrentReview(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
review, err := issues_model.GetCurrentReview(db.DefaultContext, user, issue) review, err := issues_model.GetCurrentReview(db.DefaultContext, user, issue)
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, review) assert.NotNil(t, review)
assert.Equal(t, issues_model.ReviewTypePending, review.Type) assert.Equal(t, issues_model.ReviewTypePending, review.Type)
assert.Equal(t, "Pending Review", review.Content) assert.Equal(t, "Pending Review", review.Content)
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 7}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 7})
review2, err := issues_model.GetCurrentReview(db.DefaultContext, user2, issue) 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.True(t, issues_model.IsErrReviewNotExist(err))
assert.Nil(t, review2) assert.Nil(t, review2)
} }
func TestCreateReview(t *testing.T) { func TestCreateReview(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
@ -114,13 +115,13 @@ func TestCreateReview(t *testing.T) {
Issue: issue, Issue: issue,
Reviewer: user, Reviewer: user,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "New Review", review.Content) assert.Equal(t, "New Review", review.Content)
unittest.AssertExistsAndLoadBean(t, &issues_model.Review{Content: "New Review"}) unittest.AssertExistsAndLoadBean(t, &issues_model.Review{Content: "New Review"})
} }
func TestGetReviewersByIssueID(t *testing.T) { func TestGetReviewersByIssueID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 3})
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) 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) allReviews, err := issues_model.GetReviewsByIssueID(db.DefaultContext, issue.ID)
assert.NoError(t, err) require.NoError(t, err)
for _, review := range allReviews { for _, review := range allReviews {
assert.NoError(t, review.LoadReviewer(db.DefaultContext)) require.NoError(t, review.LoadReviewer(db.DefaultContext))
} }
if assert.Len(t, allReviews, 3) { if assert.Len(t, allReviews, 3) {
for i, review := range allReviews { for i, review := range allReviews {
@ -159,8 +160,8 @@ func TestGetReviewersByIssueID(t *testing.T) {
} }
allReviews, err = issues_model.GetReviewsByIssueID(db.DefaultContext, issue.ID) allReviews, err = issues_model.GetReviewsByIssueID(db.DefaultContext, issue.ID)
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, allReviews.LoadReviewers(db.DefaultContext)) require.NoError(t, allReviews.LoadReviewers(db.DefaultContext))
if assert.Len(t, allReviews, 3) { if assert.Len(t, allReviews, 3) {
for i, review := range allReviews { for i, review := range allReviews {
assert.Equal(t, expectedReviews[i].Reviewer, review.Reviewer) assert.Equal(t, expectedReviews[i].Reviewer, review.Reviewer)
@ -171,7 +172,7 @@ func TestGetReviewersByIssueID(t *testing.T) {
} }
func TestDismissReview(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}) rejectReviewExample := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample := unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) 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, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.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}) rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
assert.True(t, rejectReviewExample.Dismissed) assert.True(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.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}) rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
assert.True(t, rejectReviewExample.Dismissed) assert.True(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.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}) rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
assert.True(t, rejectReviewExample.Dismissed) assert.True(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.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}) rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
assert.True(t, rejectReviewExample.Dismissed) assert.True(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.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}) rejectReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 9})
requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11}) requestReviewExample = unittest.AssertExistsAndLoadBean(t, &issues_model.Review{ID: 11})
assert.True(t, rejectReviewExample.Dismissed) assert.True(t, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.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, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed)
assert.False(t, approveReviewExample.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, rejectReviewExample.Dismissed)
assert.False(t, requestReviewExample.Dismissed) assert.False(t, requestReviewExample.Dismissed)
assert.True(t, approveReviewExample.Dismissed) assert.True(t, approveReviewExample.Dismissed)
} }
func TestDeleteReview(t *testing.T) { func TestDeleteReview(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
@ -238,7 +239,7 @@ func TestDeleteReview(t *testing.T) {
Issue: issue, Issue: issue,
Reviewer: user, Reviewer: user,
}) })
assert.NoError(t, err) require.NoError(t, err)
review2, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{ review2, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{
Content: "Official approval", Content: "Official approval",
@ -247,21 +248,21 @@ func TestDeleteReview(t *testing.T) {
Issue: issue, Issue: issue,
Reviewer: user, 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) _, err = issues_model.GetReviewByID(db.DefaultContext, review2.ID)
assert.Error(t, err) require.Error(t, err)
assert.True(t, issues_model.IsErrReviewNotExist(err), "IsErrReviewNotExist") assert.True(t, issues_model.IsErrReviewNotExist(err), "IsErrReviewNotExist")
review1, err = issues_model.GetReviewByID(db.DefaultContext, review1.ID) review1, err = issues_model.GetReviewByID(db.DefaultContext, review1.ID)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, review1.Official) assert.True(t, review1.Official)
} }
func TestDeleteDismissedReview(t *testing.T) { func TestDeleteDismissedReview(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2}) issue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2})
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
@ -273,8 +274,8 @@ func TestDeleteDismissedReview(t *testing.T) {
Issue: issue, Issue: issue,
Reviewer: user, Reviewer: user,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, issues_model.DismissReview(db.DefaultContext, review, true)) require.NoError(t, issues_model.DismissReview(db.DefaultContext, review, true))
comment, err := issues_model.CreateComment(db.DefaultContext, &issues_model.CreateCommentOptions{ comment, err := issues_model.CreateComment(db.DefaultContext, &issues_model.CreateCommentOptions{
Type: issues_model.CommentTypeDismissReview, Type: issues_model.CommentTypeDismissReview,
Doer: user, Doer: user,
@ -283,19 +284,19 @@ func TestDeleteDismissedReview(t *testing.T) {
ReviewID: review.ID, ReviewID: review.ID,
Content: "dismiss", Content: "dismiss",
}) })
assert.NoError(t, err) require.NoError(t, err)
unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: comment.ID}) 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}) unittest.AssertNotExistsBean(t, &issues_model.Comment{ID: comment.ID})
} }
func TestAddReviewRequest(t *testing.T) { func TestAddReviewRequest(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
pull := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: 1}) 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 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}) reviewer := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
_, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{ _, err := issues_model.CreateReview(db.DefaultContext, issues_model.CreateReviewOptions{
Issue: issue, Issue: issue,
@ -303,18 +304,18 @@ func TestAddReviewRequest(t *testing.T) {
Type: issues_model.ReviewTypeReject, Type: issues_model.ReviewTypeReject,
}) })
assert.NoError(t, err) require.NoError(t, err)
pull.HasMerged = false pull.HasMerged = false
assert.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) require.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged"))
issue.IsClosed = true issue.IsClosed = true
_, err = issues_model.AddReviewRequest(db.DefaultContext, issue, reviewer, &user_model.User{}) _, 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)) assert.True(t, issues_model.IsErrReviewRequestOnClosedPR(err))
pull.HasMerged = true pull.HasMerged = true
assert.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged")) require.NoError(t, pull.UpdateCols(db.DefaultContext, "has_merged"))
issue.IsClosed = false issue.IsClosed = false
_, err = issues_model.AddReviewRequest(db.DefaultContext, issue, reviewer, &user_model.User{}) _, 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)) assert.True(t, issues_model.IsErrReviewRequestOnClosedPR(err))
} }

View file

@ -13,66 +13,67 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestCancelStopwatch(t *testing.T) { func TestCancelStopwatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user1, err := user_model.GetUserByID(db.DefaultContext, 1) user1, err := user_model.GetUserByID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2) issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2)
assert.NoError(t, err) require.NoError(t, err)
err = issues_model.CancelStopwatch(db.DefaultContext, user1, issue1) 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.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}) _ = 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) { 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.True(t, issues_model.StopwatchExists(db.DefaultContext, 1, 1))
assert.False(t, issues_model.StopwatchExists(db.DefaultContext, 1, 2)) assert.False(t, issues_model.StopwatchExists(db.DefaultContext, 1, 2))
} }
func TestHasUserStopwatch(t *testing.T) { func TestHasUserStopwatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
exists, sw, _, err := issues_model.HasUserStopwatch(db.DefaultContext, 1) exists, sw, _, err := issues_model.HasUserStopwatch(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, exists) assert.True(t, exists)
assert.Equal(t, int64(1), sw.ID) assert.Equal(t, int64(1), sw.ID)
exists, _, _, err = issues_model.HasUserStopwatch(db.DefaultContext, 3) exists, _, _, err = issues_model.HasUserStopwatch(db.DefaultContext, 3)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, exists) assert.False(t, exists)
} }
func TestCreateOrStopIssueStopwatch(t *testing.T) { func TestCreateOrStopIssueStopwatch(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user2, err := user_model.GetUserByID(db.DefaultContext, 2) user2, err := user_model.GetUserByID(db.DefaultContext, 2)
assert.NoError(t, err) require.NoError(t, err)
org3, err := user_model.GetUserByID(db.DefaultContext, 3) org3, err := user_model.GetUserByID(db.DefaultContext, 3)
assert.NoError(t, err) require.NoError(t, err)
issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
issue2, err := issues_model.GetIssueByID(db.DefaultContext, 2) 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}) sw := unittest.AssertExistsAndLoadBean(t, &issues_model.Stopwatch{UserID: 3, IssueID: 1})
assert.LessOrEqual(t, sw.CreatedUnix, timeutil.TimeStampNow()) 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.AssertNotExistsBean(t, &issues_model.Stopwatch{UserID: 2, IssueID: 2})
unittest.AssertExistsAndLoadBean(t, &issues_model.TrackedTime{UserID: 2, IssueID: 2}) unittest.AssertExistsAndLoadBean(t, &issues_model.TrackedTime{UserID: 2, IssueID: 2})
} }

View file

@ -14,20 +14,21 @@ import (
"code.gitea.io/gitea/modules/optional" "code.gitea.io/gitea/modules/optional"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestAddTime(t *testing.T) { func TestAddTime(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
org3, err := user_model.GetUserByID(db.DefaultContext, 3) org3, err := user_model.GetUserByID(db.DefaultContext, 3)
assert.NoError(t, err) require.NoError(t, err)
issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1) issue1, err := issues_model.GetIssueByID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
// 3661 = 1h 1min 1s // 3661 = 1h 1min 1s
trackedTime, err := issues_model.AddTime(db.DefaultContext, org3, issue1, 3661, time.Now()) 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(3), trackedTime.UserID)
assert.Equal(t, int64(1), trackedTime.IssueID) assert.Equal(t, int64(1), trackedTime.IssueID)
assert.Equal(t, int64(3661), trackedTime.Time) assert.Equal(t, int64(3661), trackedTime.Time)
@ -40,51 +41,51 @@ func TestAddTime(t *testing.T) {
} }
func TestGetTrackedTimes(t *testing.T) { func TestGetTrackedTimes(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
// by Issue // by Issue
times, err := issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 1}) 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.Len(t, times, 1)
assert.Equal(t, int64(400), times[0].Time) assert.Equal(t, int64(400), times[0].Time)
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: -1}) times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: -1})
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, times, 0) assert.Empty(t, times)
// by User // by User
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{UserID: 1}) 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.Len(t, times, 3)
assert.Equal(t, int64(400), times[0].Time) assert.Equal(t, int64(400), times[0].Time)
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{UserID: 3}) times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{UserID: 3})
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, times, 0) assert.Empty(t, times)
// by Repo // by Repo
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{RepositoryID: 2}) 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.Len(t, times, 3)
assert.Equal(t, int64(1), times[0].Time) assert.Equal(t, int64(1), times[0].Time)
issue, err := issues_model.GetIssueByID(db.DefaultContext, times[0].IssueID) issue, err := issues_model.GetIssueByID(db.DefaultContext, times[0].IssueID)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, issue.RepoID, int64(2)) assert.Equal(t, int64(2), issue.RepoID)
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{RepositoryID: 1}) 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) assert.Len(t, times, 5)
times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{RepositoryID: 10}) times, err = issues_model.GetTrackedTimes(db.DefaultContext, &issues_model.FindTrackedTimesOptions{RepositoryID: 10})
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, times, 0) assert.Empty(t, times)
} }
func TestTotalTimesForEachUser(t *testing.T) { 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}) 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) assert.Len(t, total, 1)
for user, time := range total { for user, time := range total {
assert.EqualValues(t, 1, user.ID) 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}) 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) assert.Len(t, total, 2)
for user, time := range total { for user, time := range total {
if user.ID == 2 { if user.ID == 2 {
@ -100,12 +101,12 @@ func TestTotalTimesForEachUser(t *testing.T) {
} else if user.ID == 1 { } else if user.ID == 1 {
assert.EqualValues(t, 20, time) assert.EqualValues(t, 20, time)
} else { } else {
assert.Error(t, assert.AnError) require.Error(t, assert.AnError)
} }
} }
total, err = issues_model.TotalTimesForEachUser(db.DefaultContext, &issues_model.FindTrackedTimesOptions{IssueID: 5}) 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) assert.Len(t, total, 1)
for user, time := range total { for user, time := range total {
assert.EqualValues(t, 2, user.ID) 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}) 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) assert.Len(t, total, 2)
} }
func TestGetIssueTotalTrackedTime(t *testing.T) { 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)) 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) assert.EqualValues(t, 3682, ttt)
ttt, err = issues_model.GetIssueTotalTrackedTime(db.DefaultContext, &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.Some(true)) ttt, err = issues_model.GetIssueTotalTrackedTime(db.DefaultContext, &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.Some(true))
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 0, ttt) assert.EqualValues(t, 0, ttt)
ttt, err = issues_model.GetIssueTotalTrackedTime(db.DefaultContext, &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.None[bool]()) ttt, err = issues_model.GetIssueTotalTrackedTime(db.DefaultContext, &issues_model.IssuesOptions{MilestoneIDs: []int64{1}}, optional.None[bool]())
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 3682, ttt) assert.EqualValues(t, 3682, ttt)
} }

View file

@ -15,12 +15,12 @@ import (
_ "code.gitea.io/gitea/models/actions" _ "code.gitea.io/gitea/models/actions"
_ "code.gitea.io/gitea/models/system" _ "code.gitea.io/gitea/models/system"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
// TestFixturesAreConsistent assert that test fixtures are consistent // TestFixturesAreConsistent assert that test fixtures are consistent
func TestFixturesAreConsistent(t *testing.T) { func TestFixturesAreConsistent(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
unittest.CheckConsistencyFor(t, unittest.CheckConsistencyFor(t,
&user_model.User{}, &user_model.User{},
&repo_model.Repository{}, &repo_model.Repository{},

View file

@ -25,7 +25,7 @@ import (
"code.gitea.io/gitea/modules/testlogger" "code.gitea.io/gitea/modules/testlogger"
"code.gitea.io/gitea/modules/util" "code.gitea.io/gitea/modules/util"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
"xorm.io/xorm" "xorm.io/xorm"
) )
@ -38,11 +38,11 @@ func PrepareTestEnv(t *testing.T, skip int, syncModels ...any) (*xorm.Engine, fu
ourSkip := 2 ourSkip := 2
ourSkip += skip ourSkip += skip
deferFn := testlogger.PrintCurrentTest(t, ourSkip) deferFn := testlogger.PrintCurrentTest(t, ourSkip)
assert.NoError(t, os.RemoveAll(setting.RepoRootPath)) require.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, unittest.CopyDir(path.Join(filepath.Dir(setting.AppPath), "tests/gitea-repositories-meta"), setting.RepoRootPath))
ownerDirs, err := os.ReadDir(setting.RepoRootPath) ownerDirs, err := os.ReadDir(setting.RepoRootPath)
if err != nil { 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 { for _, ownerDir := range ownerDirs {
if !ownerDir.Type().IsDir() { 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())) repoDirs, err := os.ReadDir(filepath.Join(setting.RepoRootPath, ownerDir.Name()))
if err != nil { 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 { 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", "pack"), 0o755)
@ -66,7 +66,7 @@ func PrepareTestEnv(t *testing.T, skip int, syncModels ...any) (*xorm.Engine, fu
} }
x, err := newXORMEngine() x, err := newXORMEngine()
assert.NoError(t, err) require.NoError(t, err)
if x != nil { if x != nil {
oldDefer := deferFn oldDefer := deferFn
deferFn = func() { deferFn = func() {

View file

@ -10,6 +10,7 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_DeleteOrphanedIssueLabels(t *testing.T) { 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 // Load issue labels that exist in the database pre-migration
if err := x.Find(&issueLabels); err != nil { if err := x.Find(&issueLabels); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
for _, issueLabel := range issueLabels { for _, issueLabel := range issueLabels {
@ -56,14 +57,14 @@ func Test_DeleteOrphanedIssueLabels(t *testing.T) {
// Run the migration // Run the migration
if err := DeleteOrphanedIssueLabels(x); err != nil { if err := DeleteOrphanedIssueLabels(x); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
// Load the remaining issue-labels // Load the remaining issue-labels
issueLabels = issueLabels[:0] issueLabels = issueLabels[:0]
if err := x.Find(&issueLabels); err != nil { if err := x.Find(&issueLabels); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
for _, issueLabel := range issueLabels { for _, issueLabel := range issueLabels {

View file

@ -10,6 +10,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_AddPrimaryEmail2EmailAddress(t *testing.T) { func Test_AddPrimaryEmail2EmailAddress(t *testing.T) {
@ -28,7 +29,7 @@ func Test_AddPrimaryEmail2EmailAddress(t *testing.T) {
defer deferable() defer deferable()
err := AddPrimaryEmail2EmailAddress(x) err := AddPrimaryEmail2EmailAddress(x)
assert.NoError(t, err) require.NoError(t, err)
type EmailAddress struct { type EmailAddress struct {
ID int64 `xorm:"pk autoincr"` ID int64 `xorm:"pk autoincr"`
@ -41,12 +42,12 @@ func Test_AddPrimaryEmail2EmailAddress(t *testing.T) {
users := make([]User, 0, 20) users := make([]User, 0, 20)
err = x.Find(&users) err = x.Find(&users)
assert.NoError(t, err) require.NoError(t, err)
for _, user := range users { for _, user := range users {
var emailAddress EmailAddress var emailAddress EmailAddress
has, err := x.Where("lower_email=?", strings.ToLower(user.Email)).Get(&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, has)
assert.True(t, emailAddress.IsPrimary) assert.True(t, emailAddress.IsPrimary)
assert.EqualValues(t, user.IsActive, emailAddress.IsActivated) assert.EqualValues(t, user.IsActive, emailAddress.IsActivated)

View file

@ -9,6 +9,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_AddIssueResourceIndexTable(t *testing.T) { func Test_AddIssueResourceIndexTable(t *testing.T) {
@ -29,7 +30,7 @@ func Test_AddIssueResourceIndexTable(t *testing.T) {
// Run the migration // Run the migration
if err := AddIssueResourceIndexTable(x); err != nil { if err := AddIssueResourceIndexTable(x); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
@ -43,12 +44,12 @@ func Test_AddIssueResourceIndexTable(t *testing.T) {
for { for {
indexes := make([]ResourceIndex, 0, batchSize) indexes := make([]ResourceIndex, 0, batchSize)
err := x.Table("issue_index").Limit(batchSize, start).Find(&indexes) err := x.Table("issue_index").Limit(batchSize, start).Find(&indexes)
assert.NoError(t, err) require.NoError(t, err)
for _, idx := range indexes { for _, idx := range indexes {
var maxIndex int var maxIndex int
has, err := x.SQL("SELECT max(`index`) FROM issue WHERE repo_id = ?", idx.GroupID).Get(&maxIndex) 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.True(t, has)
assert.EqualValues(t, maxIndex, idx.MaxIndex) assert.EqualValues(t, maxIndex, idx.MaxIndex)
} }

View file

@ -10,6 +10,7 @@ import (
"code.gitea.io/gitea/modules/json" "code.gitea.io/gitea/modules/json"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
// LoginSource represents an external way for authorizing users. // LoginSource represents an external way for authorizing users.
@ -45,7 +46,7 @@ func Test_UnwrapLDAPSourceCfg(t *testing.T) {
// Run the migration // Run the migration
if err := UnwrapLDAPSourceCfg(x); err != nil { if err := UnwrapLDAPSourceCfg(x); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
@ -53,7 +54,7 @@ func Test_UnwrapLDAPSourceCfg(t *testing.T) {
for start := 0; ; start += batchSize { for start := 0; ; start += batchSize {
sources := make([]*LoginSource, 0, batchSize) sources := make([]*LoginSource, 0, batchSize)
if err := x.Table("login_source").Limit(batchSize, start).Find(&sources); err != nil { if err := x.Table("login_source").Limit(batchSize, start).Find(&sources); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
@ -66,12 +67,12 @@ func Test_UnwrapLDAPSourceCfg(t *testing.T) {
expected := map[string]any{} expected := map[string]any{}
if err := json.Unmarshal([]byte(source.Cfg), &converted); err != nil { if err := json.Unmarshal([]byte(source.Cfg), &converted); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
if err := json.Unmarshal([]byte(source.Expected), &expected); err != nil { if err := json.Unmarshal([]byte(source.Expected), &expected); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }

View file

@ -9,6 +9,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_AddRepoIDForAttachment(t *testing.T) { func Test_AddRepoIDForAttachment(t *testing.T) {
@ -39,7 +40,7 @@ func Test_AddRepoIDForAttachment(t *testing.T) {
// Run the migration // Run the migration
if err := AddRepoIDForAttachment(x); err != nil { if err := AddRepoIDForAttachment(x); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
@ -54,26 +55,26 @@ func Test_AddRepoIDForAttachment(t *testing.T) {
var issueAttachments []*NewAttachment var issueAttachments []*NewAttachment
err := x.Table("attachment").Where("issue_id > 0").Find(&issueAttachments) err := x.Table("attachment").Where("issue_id > 0").Find(&issueAttachments)
assert.NoError(t, err) require.NoError(t, err)
for _, attach := range issueAttachments { for _, attach := range issueAttachments {
assert.Greater(t, attach.RepoID, int64(0)) assert.Greater(t, attach.RepoID, int64(0))
assert.Greater(t, attach.IssueID, int64(0)) assert.Greater(t, attach.IssueID, int64(0))
var issue Issue var issue Issue
has, err := x.ID(attach.IssueID).Get(&issue) has, err := x.ID(attach.IssueID).Get(&issue)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, has) assert.True(t, has)
assert.EqualValues(t, attach.RepoID, issue.RepoID) assert.EqualValues(t, attach.RepoID, issue.RepoID)
} }
var releaseAttachments []*NewAttachment var releaseAttachments []*NewAttachment
err = x.Table("attachment").Where("release_id > 0").Find(&releaseAttachments) err = x.Table("attachment").Where("release_id > 0").Find(&releaseAttachments)
assert.NoError(t, err) require.NoError(t, err)
for _, attach := range releaseAttachments { for _, attach := range releaseAttachments {
assert.Greater(t, attach.RepoID, int64(0)) assert.Greater(t, attach.RepoID, int64(0))
assert.Greater(t, attach.ReleaseID, int64(0)) assert.Greater(t, attach.ReleaseID, int64(0))
var release Release var release Release
has, err := x.ID(attach.ReleaseID).Get(&release) has, err := x.ID(attach.ReleaseID).Get(&release)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, has) assert.True(t, has)
assert.EqualValues(t, attach.RepoID, release.RepoID) assert.EqualValues(t, attach.RepoID, release.RepoID)
} }

View file

@ -9,6 +9,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_AddTableCommitStatusIndex(t *testing.T) { func Test_AddTableCommitStatusIndex(t *testing.T) {
@ -30,7 +31,7 @@ func Test_AddTableCommitStatusIndex(t *testing.T) {
// Run the migration // Run the migration
if err := AddTableCommitStatusIndex(x); err != nil { if err := AddTableCommitStatusIndex(x); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
@ -46,12 +47,12 @@ func Test_AddTableCommitStatusIndex(t *testing.T) {
for { for {
indexes := make([]CommitStatusIndex, 0, batchSize) indexes := make([]CommitStatusIndex, 0, batchSize)
err := x.Table("commit_status_index").Limit(batchSize, start).Find(&indexes) err := x.Table("commit_status_index").Limit(batchSize, start).Find(&indexes)
assert.NoError(t, err) require.NoError(t, err)
for _, idx := range indexes { for _, idx := range indexes {
var maxIndex int var maxIndex int
has, err := x.SQL("SELECT max(`index`) FROM commit_status WHERE repo_id = ? AND sha = ?", idx.RepoID, idx.SHA).Get(&maxIndex) 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.True(t, has)
assert.EqualValues(t, maxIndex, idx.MaxIndex) assert.EqualValues(t, maxIndex, idx.MaxIndex)
} }

View file

@ -11,6 +11,7 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/xorm/schemas" "xorm.io/xorm/schemas"
) )
@ -20,9 +21,9 @@ func TestParseU2FRegistration(t *testing.T) {
const testRegRespHex = "0504b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9402a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c253082013c3081e4a003020102020a47901280001155957352300a06082a8648ce3d0403023017311530130603550403130c476e756262792050696c6f74301e170d3132303831343138323933325a170d3133303831343138323933325a3031312f302d0603550403132650696c6f74476e756262792d302e342e312d34373930313238303030313135353935373335323059301306072a8648ce3d020106082a8648ce3d030107034200048d617e65c9508e64bcc5673ac82a6799da3c1446682c258c463fffdf58dfd2fa3e6c378b53d795c4a4dffb4199edd7862f23abaf0203b4b8911ba0569994e101300a06082a8648ce3d0403020347003044022060cdb6061e9c22262d1aac1d96d8c70829b2366531dda268832cb836bcd30dfa0220631b1459f09e6330055722c8d89b7f48883b9089b88d60d1d9795902b30410df304502201471899bcc3987e62e8202c9b39c33c19033f7340352dba80fcab017db9230e402210082677d673d891933ade6f617e5dbde2e247e70423fd5ad7804a6d3d3961ef871" const testRegRespHex = "0504b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9402a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c253082013c3081e4a003020102020a47901280001155957352300a06082a8648ce3d0403023017311530130603550403130c476e756262792050696c6f74301e170d3132303831343138323933325a170d3133303831343138323933325a3031312f302d0603550403132650696c6f74476e756262792d302e342e312d34373930313238303030313135353935373335323059301306072a8648ce3d020106082a8648ce3d030107034200048d617e65c9508e64bcc5673ac82a6799da3c1446682c258c463fffdf58dfd2fa3e6c378b53d795c4a4dffb4199edd7862f23abaf0203b4b8911ba0569994e101300a06082a8648ce3d0403020347003044022060cdb6061e9c22262d1aac1d96d8c70829b2366531dda268832cb836bcd30dfa0220631b1459f09e6330055722c8d89b7f48883b9089b88d60d1d9795902b30410df304502201471899bcc3987e62e8202c9b39c33c19033f7340352dba80fcab017db9230e402210082677d673d891933ade6f617e5dbde2e247e70423fd5ad7804a6d3d3961ef871"
regResp, err := hex.DecodeString(testRegRespHex) regResp, err := hex.DecodeString(testRegRespHex)
assert.NoError(t, err) require.NoError(t, err)
pubKey, keyHandle, err := parseU2FRegistration(regResp) pubKey, keyHandle, err := parseU2FRegistration(regResp)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "04b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9", hex.EncodeToString(pubKey.Bytes())) assert.Equal(t, "04b174bc49c7ca254b70d2e5c207cee9cf174820ebd77ea3c65508c26da51b657c1cc6b952f8621697936482da0a6d3d3826a59095daf6cd7c03e2e60385d2f6d9", hex.EncodeToString(pubKey.Bytes()))
assert.Equal(t, "2a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c25", hex.EncodeToString(keyHandle)) assert.Equal(t, "2a552dfdb7477ed65fd84133f86196010b2215b57da75d315b7b9e8fe2e3925a6019551bab61d16591659cbaf00b4950f7abfe6660e2e006f76868b772d70c25", hex.EncodeToString(keyHandle))
} }
@ -71,19 +72,17 @@ func Test_RemigrateU2FCredentials(t *testing.T) {
// Run the migration // Run the migration
if err := RemigrateU2FCredentials(x); err != nil { if err := RemigrateU2FCredentials(x); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
expected := []ExpectedWebauthnCredential{} expected := []ExpectedWebauthnCredential{}
if err := x.Table("expected_webauthn_credential").Asc("id").Find(&expected); !assert.NoError(t, err) { err := x.Table("expected_webauthn_credential").Asc("id").Find(&expected)
return require.NoError(t, err)
}
got := []ExpectedWebauthnCredential{} got := []ExpectedWebauthnCredential{}
if err := x.Table("webauthn_credential").Select("id, credential_id").Asc("id").Find(&got); !assert.NoError(t, err) { err = x.Table("webauthn_credential").Select("id, credential_id").Asc("id").Find(&got)
return require.NoError(t, err)
}
assert.EqualValues(t, expected, got) assert.EqualValues(t, expected, got)
} }

View file

@ -10,6 +10,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_StoreWebauthnCredentialIDAsBytes(t *testing.T) { func Test_StoreWebauthnCredentialIDAsBytes(t *testing.T) {
@ -44,20 +45,16 @@ func Test_StoreWebauthnCredentialIDAsBytes(t *testing.T) {
return return
} }
if err := StoreWebauthnCredentialIDAsBytes(x); err != nil { err := StoreWebauthnCredentialIDAsBytes(x)
assert.NoError(t, err) require.NoError(t, err)
return
}
expected := []ExpectedWebauthnCredential{} expected := []ExpectedWebauthnCredential{}
if err := x.Table("expected_webauthn_credential").Asc("id").Find(&expected); !assert.NoError(t, err) { err = x.Table("expected_webauthn_credential").Asc("id").Find(&expected)
return require.NoError(t, err)
}
got := []ConvertedWebauthnCredential{} got := []ConvertedWebauthnCredential{}
if err := x.Table("webauthn_credential").Select("id, credential_id_bytes").Asc("id").Find(&got); !assert.NoError(t, err) { err = x.Table("webauthn_credential").Select("id, credential_id_bytes").Asc("id").Find(&got)
return require.NoError(t, err)
}
for i, e := range expected { for i, e := range expected {
credIDBytes, _ := base32.HexEncoding.DecodeString(e.CredentialID) credIDBytes, _ := base32.HexEncoding.DecodeString(e.CredentialID)

View file

@ -10,6 +10,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_UpdateOpenMilestoneCounts(t *testing.T) { func Test_UpdateOpenMilestoneCounts(t *testing.T) {
@ -23,19 +24,17 @@ func Test_UpdateOpenMilestoneCounts(t *testing.T) {
} }
if err := UpdateOpenMilestoneCounts(x); err != nil { if err := UpdateOpenMilestoneCounts(x); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
expected := []ExpectedMilestone{} expected := []ExpectedMilestone{}
if err := x.Table("expected_milestone").Asc("id").Find(&expected); !assert.NoError(t, err) { err := x.Table("expected_milestone").Asc("id").Find(&expected)
return require.NoError(t, err)
}
got := []issues.Milestone{} got := []issues.Milestone{}
if err := x.Table("milestone").Asc("id").Find(&got); !assert.NoError(t, err) { err = x.Table("milestone").Asc("id").Find(&got)
return require.NoError(t, err)
}
for i, e := range expected { for i, e := range expected {
got := got[i] got := got[i]

View file

@ -9,6 +9,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_AddConfidentialClientColumnToOAuth2ApplicationTable(t *testing.T) { func Test_AddConfidentialClientColumnToOAuth2ApplicationTable(t *testing.T) {
@ -25,7 +26,7 @@ func Test_AddConfidentialClientColumnToOAuth2ApplicationTable(t *testing.T) {
} }
if err := AddConfidentialClientColumnToOAuth2ApplicationTable(x); err != nil { if err := AddConfidentialClientColumnToOAuth2ApplicationTable(x); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
@ -36,9 +37,8 @@ func Test_AddConfidentialClientColumnToOAuth2ApplicationTable(t *testing.T) {
} }
got := []ExpectedOAuth2Application{} got := []ExpectedOAuth2Application{}
if err := x.Table("oauth2_application").Select("id, confidential_client").Find(&got); !assert.NoError(t, err) { err := x.Table("oauth2_application").Select("id, confidential_client").Find(&got)
return require.NoError(t, err)
}
assert.NotEmpty(t, got) assert.NotEmpty(t, got)
for _, e := range got { for _, e := range got {

View file

@ -13,6 +13,7 @@ import (
webhook_module "code.gitea.io/gitea/modules/webhook" webhook_module "code.gitea.io/gitea/modules/webhook"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) { func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) {
@ -46,19 +47,17 @@ func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) {
} }
if err := AddHeaderAuthorizationEncryptedColWebhook(x); err != nil { if err := AddHeaderAuthorizationEncryptedColWebhook(x); err != nil {
assert.NoError(t, err) require.NoError(t, err)
return return
} }
expected := []ExpectedWebhook{} expected := []ExpectedWebhook{}
if err := x.Table("expected_webhook").Asc("id").Find(&expected); !assert.NoError(t, err) { err := x.Table("expected_webhook").Asc("id").Find(&expected)
return require.NoError(t, err)
}
got := []Webhook{} got := []Webhook{}
if err := x.Table("webhook").Select("id, meta, header_authorization_encrypted").Asc("id").Find(&got); !assert.NoError(t, err) { err = x.Table("webhook").Select("id, meta, header_authorization_encrypted").Asc("id").Find(&got)
return require.NoError(t, err)
}
for i, e := range expected { for i, e := range expected {
assert.Equal(t, e.Meta, got[i].Meta) assert.Equal(t, e.Meta, got[i].Meta)
@ -68,20 +67,20 @@ func Test_AddHeaderAuthorizationEncryptedColWebhook(t *testing.T) {
} else { } else {
cipherhex := got[i].HeaderAuthorizationEncrypted cipherhex := got[i].HeaderAuthorizationEncrypted
cleartext, err := secret.DecryptSecret(setting.SecretKey, cipherhex) cleartext, err := secret.DecryptSecret(setting.SecretKey, cipherhex)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, e.HeaderAuthorization, cleartext) assert.Equal(t, e.HeaderAuthorization, cleartext)
} }
} }
// ensure that no hook_task has some remaining "access_token" // ensure that no hook_task has some remaining "access_token"
hookTasks := []HookTask{} hookTasks := []HookTask{}
if err := x.Table("hook_task").Select("id, payload_content").Asc("id").Find(&hookTasks); !assert.NoError(t, err) { err = x.Table("hook_task").Select("id, payload_content").Asc("id").Find(&hookTasks)
return require.NoError(t, err)
}
for _, h := range hookTasks { for _, h := range hookTasks {
var m map[string]any var m map[string]any
err := json.Unmarshal([]byte(h.PayloadContent), &m) err := json.Unmarshal([]byte(h.PayloadContent), &m)
assert.NoError(t, err) require.NoError(t, err)
assert.Nil(t, m["access_token"]) assert.Nil(t, m["access_token"])
} }
} }

View file

@ -11,6 +11,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
type testCase struct { type testCase struct {
@ -75,27 +76,27 @@ func Test_ConvertScopedAccessTokens(t *testing.T) {
// verify that no fixtures were loaded // verify that no fixtures were loaded
count, err := x.Count(&AccessToken{}) count, err := x.Count(&AccessToken{})
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(0), count) assert.Equal(t, int64(0), count)
for _, tc := range tests { for _, tc := range tests {
_, err = x.Insert(&AccessToken{ _, err = x.Insert(&AccessToken{
Scope: string(tc.Old), Scope: string(tc.Old),
}) })
assert.NoError(t, err) require.NoError(t, err)
} }
// migrate the scopes // migrate the scopes
err = ConvertScopedAccessTokens(x) err = ConvertScopedAccessTokens(x)
assert.NoError(t, err) require.NoError(t, err)
// migrate the scopes again (migration should be idempotent) // migrate the scopes again (migration should be idempotent)
err = ConvertScopedAccessTokens(x) err = ConvertScopedAccessTokens(x)
assert.NoError(t, err) require.NoError(t, err)
tokens := make([]AccessToken, 0) tokens := make([]AccessToken, 0)
err = x.Find(&tokens) err = x.Find(&tokens)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, len(tests), len(tokens)) assert.Equal(t, len(tests), len(tokens))
// sort the tokens (insertion order by auto-incrementing primary key) // sort the tokens (insertion order by auto-incrementing primary key)

View file

@ -8,7 +8,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" 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) { 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)) x, deferable := migration_tests.PrepareTestEnv(t, 0, new(IssueUser))
defer deferable() defer deferable()
assert.NoError(t, AddCombinedIndexToIssueUser(x)) require.NoError(t, AddCombinedIndexToIssueUser(x))
} }

View file

@ -9,6 +9,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/xorm" "xorm.io/xorm"
) )
@ -81,7 +82,7 @@ func Test_RepositoryFormat(t *testing.T) {
x, deferable := PrepareOldRepository(t) x, deferable := PrepareOldRepository(t)
defer deferable() defer deferable()
assert.NoError(t, AdjustDBForSha256(x)) require.NoError(t, AdjustDBForSha256(x))
type Repository struct { type Repository struct {
ID int64 `xorm:"pk autoincr"` ID int64 `xorm:"pk autoincr"`
@ -92,27 +93,27 @@ func Test_RepositoryFormat(t *testing.T) {
// check we have some records to migrate // check we have some records to migrate
count, err := x.Count(new(Repository)) count, err := x.Count(new(Repository))
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 4, count) assert.EqualValues(t, 4, count)
repo.ObjectFormatName = "sha256" repo.ObjectFormatName = "sha256"
_, err = x.Insert(repo) _, err = x.Insert(repo)
assert.NoError(t, err) require.NoError(t, err)
id := repo.ID id := repo.ID
count, err = x.Count(new(Repository)) count, err = x.Count(new(Repository))
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 5, count) assert.EqualValues(t, 5, count)
repo = new(Repository) repo = new(Repository)
ok, err := x.ID(2).Get(repo) ok, err := x.ID(2).Get(repo)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, true, ok) assert.True(t, ok)
assert.EqualValues(t, "sha1", repo.ObjectFormatName) assert.EqualValues(t, "sha1", repo.ObjectFormatName)
repo = new(Repository) repo = new(Repository)
ok, err = x.ID(id).Get(repo) ok, err = x.ID(id).Get(repo)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, true, ok) assert.True(t, ok)
assert.EqualValues(t, "sha256", repo.ObjectFormatName) assert.EqualValues(t, "sha256", repo.ObjectFormatName)
} }

View file

@ -12,6 +12,7 @@ import (
webhook_module "code.gitea.io/gitea/modules/webhook" webhook_module "code.gitea.io/gitea/modules/webhook"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_AddPayloadVersionToHookTaskTable(t *testing.T) { func Test_AddPayloadVersionToHookTaskTable(t *testing.T) {
@ -40,14 +41,14 @@ func Test_AddPayloadVersionToHookTaskTable(t *testing.T) {
return return
} }
assert.NoError(t, AddPayloadVersionToHookTaskTable(x)) require.NoError(t, AddPayloadVersionToHookTaskTable(x))
expected := []HookTaskMigrated{} 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) assert.Len(t, expected, 2)
got := []HookTaskMigrated{} 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 { for i, expected := range expected {
expected, got := expected, got[i] expected, got := expected, got[i]

View file

@ -11,6 +11,7 @@ import (
"code.gitea.io/gitea/models/project" "code.gitea.io/gitea/models/project"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func Test_CheckProjectColumnsConsistency(t *testing.T) { func Test_CheckProjectColumnsConsistency(t *testing.T) {
@ -21,24 +22,24 @@ func Test_CheckProjectColumnsConsistency(t *testing.T) {
return return
} }
assert.NoError(t, CheckProjectColumnsConsistency(x)) require.NoError(t, CheckProjectColumnsConsistency(x))
// check if default column was added // check if default column was added
var defaultColumn project.Column var defaultColumn project.Column
has, err := x.Where("project_id=? AND `default` = ?", 1, true).Get(&defaultColumn) 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.True(t, has)
assert.Equal(t, int64(1), defaultColumn.ProjectID) assert.Equal(t, int64(1), defaultColumn.ProjectID)
assert.True(t, defaultColumn.Default) assert.True(t, defaultColumn.Default)
// check if multiple defaults, previous were removed and last will be kept // check if multiple defaults, previous were removed and last will be kept
expectDefaultColumn, err := project.GetColumn(db.DefaultContext, 2) expectDefaultColumn, err := project.GetColumn(db.DefaultContext, 2)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(2), expectDefaultColumn.ProjectID) assert.Equal(t, int64(2), expectDefaultColumn.ProjectID)
assert.False(t, expectDefaultColumn.Default) assert.False(t, expectDefaultColumn.Default)
expectNonDefaultColumn, err := project.GetColumn(db.DefaultContext, 3) expectNonDefaultColumn, err := project.GetColumn(db.DefaultContext, 3)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(2), expectNonDefaultColumn.ProjectID) assert.Equal(t, int64(2), expectNonDefaultColumn.ProjectID)
assert.True(t, expectNonDefaultColumn.Default) assert.True(t, expectNonDefaultColumn.Default)
} }

View file

@ -10,6 +10,7 @@ import (
migration_tests "code.gitea.io/gitea/models/migrations/test" migration_tests "code.gitea.io/gitea/models/migrations/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"xorm.io/xorm/schemas" "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() 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.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() 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) assert.EqualValues(t, 1, cnt)
tables, err := x.DBMetas() tables, err := x.DBMetas()
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, len(tables)) assert.Len(t, tables, 1)
found := false found := false
for _, index := range tables[0].Indexes { for _, index := range tables[0].Indexes {
if index.Type == schemas.UniqueType { if index.Type == schemas.UniqueType {

View file

@ -16,14 +16,15 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestTeam_AddMember(t *testing.T) { func TestTeam_AddMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(teamID, userID int64) { test := func(teamID, userID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) 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.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: userID, TeamID: teamID})
unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &user_model.User{ID: team.OrgID}) 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) { func TestTeam_RemoveMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(teamID, userID int64) { testSuccess := func(teamID, userID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) 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.AssertNotExistsBean(t, &organization.TeamUser{UID: userID, TeamID: teamID})
unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID})
} }
@ -52,30 +53,30 @@ func TestTeam_RemoveMember(t *testing.T) {
} }
func TestIsUsableTeamName(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"))) assert.True(t, db.IsErrNameReserved(organization.IsUsableTeamName("new")))
} }
func TestNewTeam(t *testing.T) { func TestNewTeam(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
const teamName = "newTeamName" const teamName = "newTeamName"
team := &organization.Team{Name: teamName, OrgID: 3} 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.AssertExistsAndLoadBean(t, &organization.Team{Name: teamName})
unittest.CheckConsistencyFor(t, &organization.Team{}, &user_model.User{ID: team.OrgID}) unittest.CheckConsistencyFor(t, &organization.Team{}, &user_model.User{ID: team.OrgID})
} }
func TestUpdateTeam(t *testing.T) { func TestUpdateTeam(t *testing.T) {
// successful update // successful update
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2})
team.LowerName = "newname" team.LowerName = "newname"
team.Name = "newName" team.Name = "newName"
team.Description = strings.Repeat("A long description!", 100) team.Description = strings.Repeat("A long description!", 100)
team.AccessMode = perm.AccessModeAdmin 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"}) team = unittest.AssertExistsAndLoadBean(t, &organization.Team{Name: "newName"})
assert.True(t, strings.HasPrefix(team.Description, "A long description!")) assert.True(t, strings.HasPrefix(team.Description, "A long description!"))
@ -88,7 +89,7 @@ func TestUpdateTeam(t *testing.T) {
func TestUpdateTeam2(t *testing.T) { func TestUpdateTeam2(t *testing.T) {
// update to already-existing team // update to already-existing team
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2})
team.LowerName = "owners" team.LowerName = "owners"
@ -101,10 +102,10 @@ func TestUpdateTeam2(t *testing.T) {
} }
func TestDeleteTeam(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}) 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.Team{ID: team.ID})
unittest.AssertNotExistsBean(t, &organization.TeamRepo{TeamID: team.ID}) unittest.AssertNotExistsBean(t, &organization.TeamRepo{TeamID: team.ID})
unittest.AssertNotExistsBean(t, &organization.TeamUser{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}) user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
accessMode, err := access_model.AccessLevel(db.DefaultContext, user, repo) accessMode, err := access_model.AccessLevel(db.DefaultContext, user, repo)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, accessMode < perm.AccessModeWrite) assert.Less(t, accessMode, perm.AccessModeWrite)
} }
func TestAddTeamMember(t *testing.T) { func TestAddTeamMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(teamID, userID int64) { test := func(teamID, userID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) 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.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: userID, TeamID: teamID})
unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}, &user_model.User{ID: team.OrgID}) 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) { func TestRemoveTeamMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(teamID, userID int64) { testSuccess := func(teamID, userID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) 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.AssertNotExistsBean(t, &organization.TeamUser{UID: userID, TeamID: teamID})
unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID}) unittest.CheckConsistencyFor(t, &organization.Team{ID: teamID})
} }
@ -151,19 +152,19 @@ func TestRemoveTeamMember(t *testing.T) {
} }
func TestRepository_RecalculateAccesses3(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}) team5 := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 5})
user29 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 29}) user29 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 29})
has, err := db.GetEngine(db.DefaultContext).Get(&access_model.Access{UserID: 29, RepoID: 23}) 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) assert.False(t, has)
// adding user29 to team5 should add an explicit access row for repo 23 // adding user29 to team5 should add an explicit access row for repo 23
// even though repo 23 is public // 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}) 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) assert.True(t, has)
} }

View file

@ -12,16 +12,17 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestUser_RemoveMember(t *testing.T) { func TestUser_RemoveMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
// remove a user that is a member // remove a user that is a member
unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{UID: 4, OrgID: 3}) unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{UID: 4, OrgID: 3})
prevNumMembers := org.NumMembers 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}) unittest.AssertNotExistsBean(t, &organization.OrgUser{UID: 4, OrgID: 3})
org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
assert.Equal(t, prevNumMembers-1, org.NumMembers) 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 // remove a user that is not a member
unittest.AssertNotExistsBean(t, &organization.OrgUser{UID: 5, OrgID: 3}) unittest.AssertNotExistsBean(t, &organization.OrgUser{UID: 5, OrgID: 3})
prevNumMembers = org.NumMembers 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}) unittest.AssertNotExistsBean(t, &organization.OrgUser{UID: 5, OrgID: 3})
org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) org = unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
assert.Equal(t, prevNumMembers, org.NumMembers) assert.Equal(t, prevNumMembers, org.NumMembers)
@ -38,14 +39,14 @@ func TestUser_RemoveMember(t *testing.T) {
} }
func TestRemoveOrgUser(t *testing.T) { func TestRemoveOrgUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(orgID, userID int64) { testSuccess := func(orgID, userID int64) {
org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: orgID}) org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: orgID})
expectedNumMembers := org.NumMembers expectedNumMembers := org.NumMembers
if unittest.BeanExists(t, &organization.OrgUser{OrgID: orgID, UID: userID}) { if unittest.BeanExists(t, &organization.OrgUser{OrgID: orgID, UID: userID}) {
expectedNumMembers-- 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}) unittest.AssertNotExistsBean(t, &organization.OrgUser{OrgID: orgID, UID: userID})
org = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: orgID}) org = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: orgID})
assert.EqualValues(t, expectedNumMembers, org.NumMembers) assert.EqualValues(t, expectedNumMembers, org.NumMembers)
@ -54,7 +55,7 @@ func TestRemoveOrgUser(t *testing.T) {
testSuccess(3, 4) testSuccess(3, 4)
err := RemoveOrgUser(db.DefaultContext, 7, 5) err := RemoveOrgUser(db.DefaultContext, 7, 5)
assert.Error(t, err) require.Error(t, err)
assert.True(t, organization.IsErrLastOrgOwner(err)) assert.True(t, organization.IsErrLastOrgOwner(err))
unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{OrgID: 7, UID: 5}) unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{OrgID: 7, UID: 5})
unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{}) unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{})

View file

@ -14,10 +14,11 @@ import (
"code.gitea.io/gitea/modules/structs" "code.gitea.io/gitea/modules/structs"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestUser_IsOwnedBy(t *testing.T) { func TestUser_IsOwnedBy(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
for _, testCase := range []struct { for _, testCase := range []struct {
OrgID int64 OrgID int64
UserID int64 UserID int64
@ -32,13 +33,13 @@ func TestUser_IsOwnedBy(t *testing.T) {
} { } {
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID})
isOwner, err := org.IsOwnedBy(db.DefaultContext, testCase.UserID) isOwner, err := org.IsOwnedBy(db.DefaultContext, testCase.UserID)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, testCase.ExpectedOwner, isOwner) assert.Equal(t, testCase.ExpectedOwner, isOwner)
} }
} }
func TestUser_IsOrgMember(t *testing.T) { func TestUser_IsOrgMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
for _, testCase := range []struct { for _, testCase := range []struct {
OrgID int64 OrgID int64
UserID int64 UserID int64
@ -53,16 +54,16 @@ func TestUser_IsOrgMember(t *testing.T) {
} { } {
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: testCase.OrgID})
isMember, err := org.IsOrgMember(db.DefaultContext, testCase.UserID) isMember, err := org.IsOrgMember(db.DefaultContext, testCase.UserID)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, testCase.ExpectedMember, isMember) assert.Equal(t, testCase.ExpectedMember, isMember)
} }
} }
func TestUser_GetTeam(t *testing.T) { func TestUser_GetTeam(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
team, err := org.GetTeam(db.DefaultContext, "team1") 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, org.ID, team.OrgID)
assert.Equal(t, "team1", team.LowerName) assert.Equal(t, "team1", team.LowerName)
@ -75,10 +76,10 @@ func TestUser_GetTeam(t *testing.T) {
} }
func TestUser_GetOwnerTeam(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}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
team, err := org.GetOwnerTeam(db.DefaultContext) team, err := org.GetOwnerTeam(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, org.ID, team.OrgID) assert.Equal(t, org.ID, team.OrgID)
nonOrg := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 2}) nonOrg := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 2})
@ -87,10 +88,10 @@ func TestUser_GetOwnerTeam(t *testing.T) {
} }
func TestUser_GetTeams(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}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
teams, err := org.LoadTeams(db.DefaultContext) teams, err := org.LoadTeams(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, teams, 5) { if assert.Len(t, teams, 5) {
assert.Equal(t, int64(1), teams[0].ID) assert.Equal(t, int64(1), teams[0].ID)
assert.Equal(t, int64(2), teams[1].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) { func TestUser_GetMembers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
members, _, err := org.GetMembers(db.DefaultContext) members, _, err := org.GetMembers(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, members, 3) { if assert.Len(t, members, 3) {
assert.Equal(t, int64(2), members[0].ID) assert.Equal(t, int64(2), members[0].ID)
assert.Equal(t, int64(28), members[1].ID) assert.Equal(t, int64(28), members[1].ID)
@ -113,10 +114,10 @@ func TestUser_GetMembers(t *testing.T) {
} }
func TestGetOrgByName(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") org, err := organization.GetOrgByName(db.DefaultContext, "org3")
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 3, org.ID) assert.EqualValues(t, 3, org.ID)
assert.Equal(t, "org3", org.Name) assert.Equal(t, "org3", org.Name)
@ -128,19 +129,19 @@ func TestGetOrgByName(t *testing.T) {
} }
func TestCountOrganizations(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{}) 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}) 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) assert.Equal(t, expected, cnt)
} }
func TestIsOrganizationOwner(t *testing.T) { func TestIsOrganizationOwner(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(orgID, userID int64, expected bool) { test := func(orgID, userID int64, expected bool) {
isOwner, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, userID) isOwner, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, userID)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, expected, isOwner) assert.EqualValues(t, expected, isOwner)
} }
test(3, 2, true) test(3, 2, true)
@ -151,10 +152,10 @@ func TestIsOrganizationOwner(t *testing.T) {
} }
func TestIsOrganizationMember(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) { test := func(orgID, userID int64, expected bool) {
isMember, err := organization.IsOrganizationMember(db.DefaultContext, orgID, userID) isMember, err := organization.IsOrganizationMember(db.DefaultContext, orgID, userID)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, expected, isMember) assert.EqualValues(t, expected, isMember)
} }
test(3, 2, true) test(3, 2, true)
@ -166,10 +167,10 @@ func TestIsOrganizationMember(t *testing.T) {
} }
func TestIsPublicMembership(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) { test := func(orgID, userID int64, expected bool) {
isMember, err := organization.IsPublicMembership(db.DefaultContext, orgID, userID) isMember, err := organization.IsPublicMembership(db.DefaultContext, orgID, userID)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, expected, isMember) assert.EqualValues(t, expected, isMember)
} }
test(3, 2, true) test(3, 2, true)
@ -181,13 +182,13 @@ func TestIsPublicMembership(t *testing.T) {
} }
func TestFindOrgs(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{ orgs, err := db.Find[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
UserID: 4, UserID: 4,
IncludePrivate: true, IncludePrivate: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, orgs, 1) { if assert.Len(t, orgs, 1) {
assert.EqualValues(t, 3, orgs[0].ID) assert.EqualValues(t, 3, orgs[0].ID)
} }
@ -196,26 +197,26 @@ func TestFindOrgs(t *testing.T) {
UserID: 4, UserID: 4,
IncludePrivate: false, IncludePrivate: false,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, orgs, 0) assert.Empty(t, orgs)
total, err := db.Count[organization.Organization](db.DefaultContext, organization.FindOrgOptions{ total, err := db.Count[organization.Organization](db.DefaultContext, organization.FindOrgOptions{
UserID: 4, UserID: 4,
IncludePrivate: true, IncludePrivate: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, total) assert.EqualValues(t, 1, total)
} }
func TestGetOrgUsersByOrgID(t *testing.T) { func TestGetOrgUsersByOrgID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
orgUsers, err := organization.GetOrgUsersByOrgID(db.DefaultContext, &organization.FindOrgMembersOpts{ orgUsers, err := organization.GetOrgUsersByOrgID(db.DefaultContext, &organization.FindOrgMembersOpts{
ListOptions: db.ListOptions{}, ListOptions: db.ListOptions{},
OrgID: 3, OrgID: 3,
PublicOnly: false, PublicOnly: false,
}) })
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, orgUsers, 3) { if assert.Len(t, orgUsers, 3) {
assert.Equal(t, organization.OrgUser{ assert.Equal(t, organization.OrgUser{
ID: orgUsers[0].ID, ID: orgUsers[0].ID,
@ -242,15 +243,15 @@ func TestGetOrgUsersByOrgID(t *testing.T) {
OrgID: unittest.NonexistentID, OrgID: unittest.NonexistentID,
PublicOnly: false, PublicOnly: false,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, orgUsers, 0) assert.Empty(t, orgUsers)
} }
func TestChangeOrgUserStatus(t *testing.T) { func TestChangeOrgUserStatus(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(orgID, userID int64, public bool) { 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}) orgUser := unittest.AssertExistsAndLoadBean(t, &organization.OrgUser{OrgID: orgID, UID: userID})
assert.Equal(t, public, orgUser.IsPublic) 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, 2, false) testSuccess(3, 2, false)
testSuccess(3, 4, true) 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) { func TestUser_GetUserTeamIDs(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
testSuccess := func(userID int64, expected []int64) { testSuccess := func(userID int64, expected []int64) {
teamIDs, err := org.GetUserTeamIDs(db.DefaultContext, userID) teamIDs, err := org.GetUserTeamIDs(db.DefaultContext, userID)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, expected, teamIDs) assert.Equal(t, expected, teamIDs)
} }
testSuccess(2, []int64{1, 2, 14}) testSuccess(2, []int64{1, 2, 14})
@ -275,13 +276,13 @@ func TestUser_GetUserTeamIDs(t *testing.T) {
} }
func TestAccessibleReposEnv_CountRepos(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}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
testSuccess := func(userID, expectedCount int64) { testSuccess := func(userID, expectedCount int64) {
env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID) env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID)
assert.NoError(t, err) require.NoError(t, err)
count, err := env.CountRepos() count, err := env.CountRepos()
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, expectedCount, count) assert.EqualValues(t, expectedCount, count)
} }
testSuccess(2, 3) testSuccess(2, 3)
@ -289,13 +290,13 @@ func TestAccessibleReposEnv_CountRepos(t *testing.T) {
} }
func TestAccessibleReposEnv_RepoIDs(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}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
testSuccess := func(userID int64, expectedRepoIDs []int64) { testSuccess := func(userID int64, expectedRepoIDs []int64) {
env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID) env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID)
assert.NoError(t, err) require.NoError(t, err)
repoIDs, err := env.RepoIDs(1, 100) repoIDs, err := env.RepoIDs(1, 100)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, expectedRepoIDs, repoIDs) assert.Equal(t, expectedRepoIDs, repoIDs)
} }
testSuccess(2, []int64{3, 5, 32}) testSuccess(2, []int64{3, 5, 32})
@ -303,13 +304,13 @@ func TestAccessibleReposEnv_RepoIDs(t *testing.T) {
} }
func TestAccessibleReposEnv_Repos(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}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
testSuccess := func(userID int64, expectedRepoIDs []int64) { testSuccess := func(userID int64, expectedRepoIDs []int64) {
env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID) env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID)
assert.NoError(t, err) require.NoError(t, err)
repos, err := env.Repos(1, 100) repos, err := env.Repos(1, 100)
assert.NoError(t, err) require.NoError(t, err)
expectedRepos := make(repo_model.RepositoryList, len(expectedRepoIDs)) expectedRepos := make(repo_model.RepositoryList, len(expectedRepoIDs))
for i, repoID := range expectedRepoIDs { for i, repoID := range expectedRepoIDs {
expectedRepos[i] = unittest.AssertExistsAndLoadBean(t, expectedRepos[i] = unittest.AssertExistsAndLoadBean(t,
@ -322,13 +323,13 @@ func TestAccessibleReposEnv_Repos(t *testing.T) {
} }
func TestAccessibleReposEnv_MirrorRepos(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}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
testSuccess := func(userID int64, expectedRepoIDs []int64) { testSuccess := func(userID int64, expectedRepoIDs []int64) {
env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID) env, err := organization.AccessibleReposEnv(db.DefaultContext, org, userID)
assert.NoError(t, err) require.NoError(t, err)
repos, err := env.MirrorRepos() repos, err := env.MirrorRepos()
assert.NoError(t, err) require.NoError(t, err)
expectedRepos := make(repo_model.RepositoryList, len(expectedRepoIDs)) expectedRepos := make(repo_model.RepositoryList, len(expectedRepoIDs))
for i, repoID := range expectedRepoIDs { for i, repoID := range expectedRepoIDs {
expectedRepos[i] = unittest.AssertExistsAndLoadBean(t, expectedRepos[i] = unittest.AssertExistsAndLoadBean(t,
@ -341,7 +342,7 @@ func TestAccessibleReposEnv_MirrorRepos(t *testing.T) {
} }
func TestHasOrgVisibleTypePublic(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}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) 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}) 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, org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner)
@ -364,7 +365,7 @@ func TestHasOrgVisibleTypePublic(t *testing.T) {
} }
func TestHasOrgVisibleTypeLimited(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}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) 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}) 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, org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner)
@ -387,7 +388,7 @@ func TestHasOrgVisibleTypeLimited(t *testing.T) {
} }
func TestHasOrgVisibleTypePrivate(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}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
org3 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 3}) 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}) 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, org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization}) &organization.Organization{Name: org.Name, Type: user_model.UserTypeOrganization})
test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner) test1 := organization.HasOrgOrUserVisible(db.DefaultContext, org.AsUser(), owner)
@ -410,10 +411,10 @@ func TestHasOrgVisibleTypePrivate(t *testing.T) {
} }
func TestGetUsersWhoCanCreateOrgRepo(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) users, err := organization.GetUsersWhoCanCreateOrgRepo(db.DefaultContext, 3)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, users, 2) assert.Len(t, users, 2)
var ids []int64 var ids []int64
for i := range users { for i := range users {
@ -422,27 +423,27 @@ func TestGetUsersWhoCanCreateOrgRepo(t *testing.T) {
assert.ElementsMatch(t, ids, []int64{2, 28}) assert.ElementsMatch(t, ids, []int64{2, 28})
users, err = organization.GetUsersWhoCanCreateOrgRepo(db.DefaultContext, 7) users, err = organization.GetUsersWhoCanCreateOrgRepo(db.DefaultContext, 7)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, users, 1) assert.Len(t, users, 1)
assert.NotNil(t, users[5]) assert.NotNil(t, users[5])
} }
func TestUser_RemoveOrgRepo(t *testing.T) { func TestUser_RemoveOrgRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3}) org := unittest.AssertExistsAndLoadBean(t, &organization.Organization{ID: 3})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: org.ID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerID: org.ID})
// remove a repo that does belong to org // remove a repo that does belong to org
unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{RepoID: repo.ID, OrgID: org.ID}) 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.AssertNotExistsBean(t, &organization.TeamRepo{RepoID: repo.ID, OrgID: org.ID})
unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID}) // repo should still exist unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repo.ID}) // repo should still exist
// remove a repo that does not belong to org // 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}) 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, unittest.CheckConsistencyFor(t,
&user_model.User{ID: org.ID}, &user_model.User{ID: org.ID},
@ -452,7 +453,7 @@ func TestUser_RemoveOrgRepo(t *testing.T) {
func TestCreateOrganization(t *testing.T) { func TestCreateOrganization(t *testing.T) {
// successful creation of org // successful creation of org
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
const newOrgName = "neworg" const newOrgName = "neworg"
@ -461,7 +462,7 @@ func TestCreateOrganization(t *testing.T) {
} }
unittest.AssertNotExistsBean(t, &user_model.User{Name: newOrgName, Type: user_model.UserTypeOrganization}) 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, org = unittest.AssertExistsAndLoadBean(t,
&organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization}) &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
ownerTeam := unittest.AssertExistsAndLoadBean(t, ownerTeam := unittest.AssertExistsAndLoadBean(t,
@ -472,7 +473,7 @@ func TestCreateOrganization(t *testing.T) {
func TestCreateOrganization2(t *testing.T) { func TestCreateOrganization2(t *testing.T) {
// unauthorized creation of org // unauthorized creation of org
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5})
const newOrgName = "neworg" const newOrgName = "neworg"
@ -482,7 +483,7 @@ func TestCreateOrganization2(t *testing.T) {
unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization}) unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
err := organization.CreateOrganization(db.DefaultContext, org, owner) err := organization.CreateOrganization(db.DefaultContext, org, owner)
assert.Error(t, err) require.Error(t, err)
assert.True(t, organization.IsErrUserNotAllowedCreateOrg(err)) assert.True(t, organization.IsErrUserNotAllowedCreateOrg(err))
unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization}) unittest.AssertNotExistsBean(t, &organization.Organization{Name: newOrgName, Type: user_model.UserTypeOrganization})
unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{}) unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{})
@ -490,24 +491,24 @@ func TestCreateOrganization2(t *testing.T) {
func TestCreateOrganization3(t *testing.T) { func TestCreateOrganization3(t *testing.T) {
// create org with same name as existent org // 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}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
org := &organization.Organization{Name: "org3"} // should already exist org := &organization.Organization{Name: "org3"} // should already exist
unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: org.Name}) // sanity check unittest.AssertExistsAndLoadBean(t, &user_model.User{Name: org.Name}) // sanity check
err := organization.CreateOrganization(db.DefaultContext, org, owner) err := organization.CreateOrganization(db.DefaultContext, org, owner)
assert.Error(t, err) require.Error(t, err)
assert.True(t, user_model.IsErrUserAlreadyExist(err)) assert.True(t, user_model.IsErrUserAlreadyExist(err))
unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{}) unittest.CheckConsistencyFor(t, &user_model.User{}, &organization.Team{})
} }
func TestCreateOrganization4(t *testing.T) { func TestCreateOrganization4(t *testing.T) {
// create org with unusable name // create org with unusable name
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
err := organization.CreateOrganization(db.DefaultContext, &organization.Organization{Name: "assets"}, owner) err := organization.CreateOrganization(db.DefaultContext, &organization.Organization{Name: "assets"}, owner)
assert.Error(t, err) require.Error(t, err)
assert.True(t, db.IsErrNameReserved(err)) assert.True(t, db.IsErrNameReserved(err))
unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{}) unittest.CheckConsistencyFor(t, &organization.Organization{}, &organization.Team{})
} }

View file

@ -14,10 +14,11 @@ import (
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestUserIsPublicMember(t *testing.T) { func TestUserIsPublicMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
tt := []struct { tt := []struct {
uid int64 uid int64
@ -38,14 +39,14 @@ func TestUserIsPublicMember(t *testing.T) {
func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) { func testUserIsPublicMember(t *testing.T, uid, orgID int64, expected bool) {
user, err := user_model.GetUserByID(db.DefaultContext, uid) 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) is, err := organization.IsPublicMembership(db.DefaultContext, orgID, user.ID)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, expected, is) assert.Equal(t, expected, is)
} }
func TestIsUserOrgOwner(t *testing.T) { func TestIsUserOrgOwner(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
tt := []struct { tt := []struct {
uid int64 uid int64
@ -66,14 +67,14 @@ func TestIsUserOrgOwner(t *testing.T) {
func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) { func testIsUserOrgOwner(t *testing.T, uid, orgID int64, expected bool) {
user, err := user_model.GetUserByID(db.DefaultContext, uid) 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) is, err := organization.IsOrganizationOwner(db.DefaultContext, orgID, user.ID)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, expected, is) assert.Equal(t, expected, is)
} }
func TestUserListIsPublicMember(t *testing.T) { func TestUserListIsPublicMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
tt := []struct { tt := []struct {
orgid int64 orgid int64
expected map[int64]bool expected map[int64]bool
@ -93,14 +94,14 @@ func TestUserListIsPublicMember(t *testing.T) {
func testUserListIsPublicMember(t *testing.T, orgID int64, expected map[int64]bool) { func testUserListIsPublicMember(t *testing.T, orgID int64, expected map[int64]bool) {
org, err := organization.GetOrgByID(db.DefaultContext, orgID) org, err := organization.GetOrgByID(db.DefaultContext, orgID)
assert.NoError(t, err) require.NoError(t, err)
_, membersIsPublic, err := org.GetMembers(db.DefaultContext) _, membersIsPublic, err := org.GetMembers(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, expected, membersIsPublic) assert.Equal(t, expected, membersIsPublic)
} }
func TestUserListIsUserOrgOwner(t *testing.T) { func TestUserListIsUserOrgOwner(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
tt := []struct { tt := []struct {
orgid int64 orgid int64
expected map[int64]bool expected map[int64]bool
@ -120,21 +121,21 @@ func TestUserListIsUserOrgOwner(t *testing.T) {
func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bool) { func testUserListIsUserOrgOwner(t *testing.T, orgID int64, expected map[int64]bool) {
org, err := organization.GetOrgByID(db.DefaultContext, orgID) org, err := organization.GetOrgByID(db.DefaultContext, orgID)
assert.NoError(t, err) require.NoError(t, err)
members, _, err := org.GetMembers(db.DefaultContext) members, _, err := org.GetMembers(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, expected, organization.IsUserOrgOwner(db.DefaultContext, members, orgID)) assert.Equal(t, expected, organization.IsUserOrgOwner(db.DefaultContext, members, orgID))
} }
func TestAddOrgUser(t *testing.T) { func TestAddOrgUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(orgID, userID int64, isPublic bool) { testSuccess := func(orgID, userID int64, isPublic bool) {
org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: orgID}) org := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: orgID})
expectedNumMembers := org.NumMembers expectedNumMembers := org.NumMembers
if !unittest.BeanExists(t, &organization.OrgUser{OrgID: orgID, UID: userID}) { if !unittest.BeanExists(t, &organization.OrgUser{OrgID: orgID, UID: userID}) {
expectedNumMembers++ 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} ou := &organization.OrgUser{OrgID: orgID, UID: userID}
unittest.AssertExistsAndLoadBean(t, ou) unittest.AssertExistsAndLoadBean(t, ou)
assert.Equal(t, isPublic, ou.IsPublic) assert.Equal(t, isPublic, ou.IsPublic)

View file

@ -12,10 +12,11 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestTeamInvite(t *testing.T) { func TestTeamInvite(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 2}) 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 // user 2 already added to team 2, should result in error
_, err := organization.CreateTeamInvite(db.DefaultContext, user2, team, user2.Email) _, err := organization.CreateTeamInvite(db.DefaultContext, user2, team, user2.Email)
assert.Error(t, err) require.Error(t, err)
}) })
t.Run("CreateAndRemove", func(t *testing.T) { 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") invite, err := organization.CreateTeamInvite(db.DefaultContext, user1, team, "org3@example.com")
assert.NotNil(t, invite) assert.NotNil(t, invite)
assert.NoError(t, err) require.NoError(t, err)
// Shouldn't allow duplicate invite // Shouldn't allow duplicate invite
_, err = organization.CreateTeamInvite(db.DefaultContext, user1, team, "org3@example.com") _, err = organization.CreateTeamInvite(db.DefaultContext, user1, team, "org3@example.com")
assert.Error(t, err) require.Error(t, err)
// should remove invite // 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 // invite should not exist
_, err = organization.GetInviteByToken(db.DefaultContext, invite.Token) _, err = organization.GetInviteByToken(db.DefaultContext, invite.Token)
assert.Error(t, err) require.Error(t, err)
}) })
} }

View file

@ -11,10 +11,11 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestTeam_IsOwnerTeam(t *testing.T) { func TestTeam_IsOwnerTeam(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1})
assert.True(t, team.IsOwnerTeam()) assert.True(t, team.IsOwnerTeam())
@ -24,7 +25,7 @@ func TestTeam_IsOwnerTeam(t *testing.T) {
} }
func TestTeam_IsMember(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}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: 1})
assert.True(t, team.IsMember(db.DefaultContext, 2)) assert.True(t, team.IsMember(db.DefaultContext, 2))
@ -38,11 +39,11 @@ func TestTeam_IsMember(t *testing.T) {
} }
func TestTeam_GetRepositories(t *testing.T) { func TestTeam_GetRepositories(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(teamID int64) { test := func(teamID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) 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) assert.Len(t, team.Repos, team.NumRepos)
for _, repo := range team.Repos { for _, repo := range team.Repos {
unittest.AssertExistsAndLoadBean(t, &organization.TeamRepo{TeamID: teamID, RepoID: repo.ID}) 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) { func TestTeam_GetMembers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(teamID int64) { test := func(teamID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) 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) assert.Len(t, team.Members, team.NumMembers)
for _, member := range team.Members { for _, member := range team.Members {
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID}) 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) { func TestGetTeam(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(orgID int64, name string) { testSuccess := func(orgID int64, name string) {
team, err := organization.GetTeam(db.DefaultContext, orgID, name) team, err := organization.GetTeam(db.DefaultContext, orgID, name)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, orgID, team.OrgID) assert.EqualValues(t, orgID, team.OrgID)
assert.Equal(t, name, team.Name) assert.Equal(t, name, team.Name)
} }
@ -80,17 +81,17 @@ func TestGetTeam(t *testing.T) {
testSuccess(3, "team1") testSuccess(3, "team1")
_, err := organization.GetTeam(db.DefaultContext, 3, "nonexistent") _, err := organization.GetTeam(db.DefaultContext, 3, "nonexistent")
assert.Error(t, err) require.Error(t, err)
_, err = organization.GetTeam(db.DefaultContext, unittest.NonexistentID, "Owners") _, err = organization.GetTeam(db.DefaultContext, unittest.NonexistentID, "Owners")
assert.Error(t, err) require.Error(t, err)
} }
func TestGetTeamByID(t *testing.T) { func TestGetTeamByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testSuccess := func(teamID int64) { testSuccess := func(teamID int64) {
team, err := organization.GetTeamByID(db.DefaultContext, teamID) team, err := organization.GetTeamByID(db.DefaultContext, teamID)
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, teamID, team.ID) assert.EqualValues(t, teamID, team.ID)
} }
testSuccess(1) testSuccess(1)
@ -99,14 +100,14 @@ func TestGetTeamByID(t *testing.T) {
testSuccess(4) testSuccess(4)
_, err := organization.GetTeamByID(db.DefaultContext, unittest.NonexistentID) _, err := organization.GetTeamByID(db.DefaultContext, unittest.NonexistentID)
assert.Error(t, err) require.Error(t, err)
} }
func TestIsTeamMember(t *testing.T) { func TestIsTeamMember(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(orgID, teamID, userID int64, expected bool) { test := func(orgID, teamID, userID int64, expected bool) {
isMember, err := organization.IsTeamMember(db.DefaultContext, orgID, teamID, userID) isMember, err := organization.IsTeamMember(db.DefaultContext, orgID, teamID, userID)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, expected, isMember) assert.Equal(t, expected, isMember)
} }
@ -122,14 +123,14 @@ func TestIsTeamMember(t *testing.T) {
} }
func TestGetTeamMembers(t *testing.T) { func TestGetTeamMembers(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(teamID int64) { test := func(teamID int64) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
members, err := organization.GetTeamMembers(db.DefaultContext, &organization.SearchMembersOptions{ members, err := organization.GetTeamMembers(db.DefaultContext, &organization.SearchMembersOptions{
TeamID: teamID, TeamID: teamID,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, members, team.NumMembers) assert.Len(t, members, team.NumMembers)
for _, member := range members { for _, member := range members {
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID}) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{UID: member.ID, TeamID: teamID})
@ -140,10 +141,10 @@ func TestGetTeamMembers(t *testing.T) {
} }
func TestGetUserTeams(t *testing.T) { func TestGetUserTeams(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(userID int64) { test := func(userID int64) {
teams, _, err := organization.SearchTeam(db.DefaultContext, &organization.SearchTeamOptions{UserID: userID}) teams, _, err := organization.SearchTeam(db.DefaultContext, &organization.SearchTeamOptions{UserID: userID})
assert.NoError(t, err) require.NoError(t, err)
for _, team := range teams { for _, team := range teams {
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{TeamID: team.ID, UID: userID}) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{TeamID: team.ID, UID: userID})
} }
@ -154,10 +155,10 @@ func TestGetUserTeams(t *testing.T) {
} }
func TestGetUserOrgTeams(t *testing.T) { func TestGetUserOrgTeams(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(orgID, userID int64) { test := func(orgID, userID int64) {
teams, err := organization.GetUserOrgTeams(db.DefaultContext, orgID, userID) teams, err := organization.GetUserOrgTeams(db.DefaultContext, orgID, userID)
assert.NoError(t, err) require.NoError(t, err)
for _, team := range teams { for _, team := range teams {
assert.EqualValues(t, orgID, team.OrgID) assert.EqualValues(t, orgID, team.OrgID)
unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{TeamID: team.ID, UID: userID}) unittest.AssertExistsAndLoadBean(t, &organization.TeamUser{TeamID: team.ID, UID: userID})
@ -169,7 +170,7 @@ func TestGetUserOrgTeams(t *testing.T) {
} }
func TestHasTeamRepo(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) { test := func(teamID, repoID int64, expected bool) {
team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID}) team := unittest.AssertExistsAndLoadBean(t, &organization.Team{ID: teamID})
@ -185,11 +186,11 @@ func TestHasTeamRepo(t *testing.T) {
} }
func TestUsersInTeamsCount(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) { test := func(teamIDs, userIDs []int64, expected int64) {
count, err := organization.UsersInTeamsCount(db.DefaultContext, teamIDs, userIDs) count, err := organization.UsersInTeamsCount(db.DefaultContext, teamIDs, userIDs)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, expected, count) assert.Equal(t, expected, count)
} }

View file

@ -16,6 +16,7 @@ import (
_ "code.gitea.io/gitea/models/activities" _ "code.gitea.io/gitea/models/activities"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestMain(m *testing.M) { func TestMain(m *testing.M) {
@ -23,7 +24,7 @@ func TestMain(m *testing.M) {
} }
func TestHasOwnerPackages(t *testing.T) { func TestHasOwnerPackages(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1}) owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 1})
@ -32,12 +33,12 @@ func TestHasOwnerPackages(t *testing.T) {
LowerName: "package", LowerName: "package",
}) })
assert.NotNil(t, p) 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 // A package without package versions gets automatically cleaned up and should return false
has, err := packages_model.HasOwnerPackages(db.DefaultContext, owner.ID) has, err := packages_model.HasOwnerPackages(db.DefaultContext, owner.ID)
assert.False(t, has) assert.False(t, has)
assert.NoError(t, err) require.NoError(t, err)
pv, err := packages_model.GetOrInsertVersion(db.DefaultContext, &packages_model.PackageVersion{ pv, err := packages_model.GetOrInsertVersion(db.DefaultContext, &packages_model.PackageVersion{
PackageID: p.ID, PackageID: p.ID,
@ -45,12 +46,12 @@ func TestHasOwnerPackages(t *testing.T) {
IsInternal: true, IsInternal: true,
}) })
assert.NotNil(t, pv) 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 // A package with an internal package version gets automatically cleaned up and should return false
has, err = packages_model.HasOwnerPackages(db.DefaultContext, owner.ID) has, err = packages_model.HasOwnerPackages(db.DefaultContext, owner.ID)
assert.False(t, has) assert.False(t, has)
assert.NoError(t, err) require.NoError(t, err)
pv, err = packages_model.GetOrInsertVersion(db.DefaultContext, &packages_model.PackageVersion{ pv, err = packages_model.GetOrInsertVersion(db.DefaultContext, &packages_model.PackageVersion{
PackageID: p.ID, PackageID: p.ID,
@ -58,10 +59,10 @@ func TestHasOwnerPackages(t *testing.T) {
IsInternal: false, IsInternal: false,
}) })
assert.NotNil(t, pv) assert.NotNil(t, pv)
assert.NoError(t, err) require.NoError(t, err)
// A package with a normal package version should return true // A package with a normal package version should return true
has, err = packages_model.HasOwnerPackages(db.DefaultContext, owner.ID) has, err = packages_model.HasOwnerPackages(db.DefaultContext, owner.ID)
assert.True(t, has) assert.True(t, has)
assert.NoError(t, err) require.NoError(t, err)
} }

View file

@ -14,10 +14,11 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestAccessLevel(t *testing.T) { func TestAccessLevel(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
user5 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) 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}) repo24 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 24})
level, err := access_model.AccessLevel(db.DefaultContext, user2, repo1) level, err := access_model.AccessLevel(db.DefaultContext, user2, repo1)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, perm_model.AccessModeOwner, level) assert.Equal(t, perm_model.AccessModeOwner, level)
level, err = access_model.AccessLevel(db.DefaultContext, user2, repo3) level, err = access_model.AccessLevel(db.DefaultContext, user2, repo3)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, perm_model.AccessModeOwner, level) assert.Equal(t, perm_model.AccessModeOwner, level)
level, err = access_model.AccessLevel(db.DefaultContext, user5, repo1) level, err = access_model.AccessLevel(db.DefaultContext, user5, repo1)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, perm_model.AccessModeRead, level) assert.Equal(t, perm_model.AccessModeRead, level)
level, err = access_model.AccessLevel(db.DefaultContext, user5, repo3) level, err = access_model.AccessLevel(db.DefaultContext, user5, repo3)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, perm_model.AccessModeNone, level) assert.Equal(t, perm_model.AccessModeNone, level)
// restricted user has no access to a public repo // restricted user has no access to a public repo
level, err = access_model.AccessLevel(db.DefaultContext, user29, repo1) level, err = access_model.AccessLevel(db.DefaultContext, user29, repo1)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, perm_model.AccessModeNone, level) assert.Equal(t, perm_model.AccessModeNone, level)
// ... unless he's a collaborator // ... unless he's a collaborator
level, err = access_model.AccessLevel(db.DefaultContext, user29, repo4) level, err = access_model.AccessLevel(db.DefaultContext, user29, repo4)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, perm_model.AccessModeWrite, level) assert.Equal(t, perm_model.AccessModeWrite, level)
// ... or a team member // ... or a team member
level, err = access_model.AccessLevel(db.DefaultContext, user29, repo24) level, err = access_model.AccessLevel(db.DefaultContext, user29, repo24)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, perm_model.AccessModeRead, level) assert.Equal(t, perm_model.AccessModeRead, level)
} }
func TestHasAccess(t *testing.T) { func TestHasAccess(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2}) user1 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5}) user2 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 5})
@ -80,47 +81,47 @@ func TestHasAccess(t *testing.T) {
assert.True(t, repo2.IsPrivate) assert.True(t, repo2.IsPrivate)
has, err := access_model.HasAccess(db.DefaultContext, user1.ID, repo1) has, err := access_model.HasAccess(db.DefaultContext, user1.ID, repo1)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, has) assert.True(t, has)
_, err = access_model.HasAccess(db.DefaultContext, user1.ID, repo2) _, 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) _, 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) _, err = access_model.HasAccess(db.DefaultContext, user2.ID, repo2)
assert.NoError(t, err) require.NoError(t, err)
} }
func TestRepository_RecalculateAccesses(t *testing.T) { func TestRepository_RecalculateAccesses(t *testing.T) {
// test with organization repo // test with organization repo
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) 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}) _, err := db.GetEngine(db.DefaultContext).Delete(&repo_model.Collaboration{UserID: 2, RepoID: 3})
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, access_model.RecalculateAccesses(db.DefaultContext, repo1)) require.NoError(t, access_model.RecalculateAccesses(db.DefaultContext, repo1))
access := &access_model.Access{UserID: 2, RepoID: 3} access := &access_model.Access{UserID: 2, RepoID: 3}
has, err := db.GetEngine(db.DefaultContext).Get(access) has, err := db.GetEngine(db.DefaultContext).Get(access)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, has) assert.True(t, has)
assert.Equal(t, perm_model.AccessModeOwner, access.Mode) assert.Equal(t, perm_model.AccessModeOwner, access.Mode)
} }
func TestRepository_RecalculateAccesses2(t *testing.T) { func TestRepository_RecalculateAccesses2(t *testing.T) {
// test with non-organization repo // test with non-organization repo
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) 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}) _, err := db.GetEngine(db.DefaultContext).Delete(&repo_model.Collaboration{UserID: 4, RepoID: 4})
assert.NoError(t, err) require.NoError(t, err)
assert.NoError(t, access_model.RecalculateAccesses(db.DefaultContext, repo1)) require.NoError(t, access_model.RecalculateAccesses(db.DefaultContext, repo1))
has, err := db.GetEngine(db.DefaultContext).Get(&access_model.Access{UserID: 4, RepoID: 4}) 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) assert.False(t, has)
} }

View file

@ -12,64 +12,65 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGetDefaultColumn(t *testing.T) { func TestGetDefaultColumn(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
projectWithoutDefault, err := GetProjectByID(db.DefaultContext, 5) projectWithoutDefault, err := GetProjectByID(db.DefaultContext, 5)
assert.NoError(t, err) require.NoError(t, err)
// check if default column was added // check if default column was added
column, err := projectWithoutDefault.GetDefaultColumn(db.DefaultContext) column, err := projectWithoutDefault.GetDefaultColumn(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(5), column.ProjectID) assert.Equal(t, int64(5), column.ProjectID)
assert.Equal(t, "Uncategorized", column.Title) assert.Equal(t, "Uncategorized", column.Title)
projectWithMultipleDefaults, err := GetProjectByID(db.DefaultContext, 6) projectWithMultipleDefaults, err := GetProjectByID(db.DefaultContext, 6)
assert.NoError(t, err) require.NoError(t, err)
// check if multiple defaults were removed // check if multiple defaults were removed
column, err = projectWithMultipleDefaults.GetDefaultColumn(db.DefaultContext) 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(6), column.ProjectID)
assert.Equal(t, int64(9), column.ID) assert.Equal(t, int64(9), column.ID)
// set 8 as default column // 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 // then 9 will become a non-default column
column, err = GetColumn(db.DefaultContext, 9) column, err = GetColumn(db.DefaultContext, 9)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(6), column.ProjectID) assert.Equal(t, int64(6), column.ProjectID)
assert.False(t, column.Default) assert.False(t, column.Default)
} }
func Test_moveIssuesToAnotherColumn(t *testing.T) { 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}) column1 := unittest.AssertExistsAndLoadBean(t, &Column{ID: 1, ProjectID: 1})
issues, err := column1.GetIssues(db.DefaultContext) issues, err := column1.GetIssues(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, issues, 1) assert.Len(t, issues, 1)
assert.EqualValues(t, 1, issues[0].ID) assert.EqualValues(t, 1, issues[0].ID)
column2 := unittest.AssertExistsAndLoadBean(t, &Column{ID: 2, ProjectID: 1}) column2 := unittest.AssertExistsAndLoadBean(t, &Column{ID: 2, ProjectID: 1})
issues, err = column2.GetIssues(db.DefaultContext) issues, err = column2.GetIssues(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, issues, 1) assert.Len(t, issues, 1)
assert.EqualValues(t, 3, issues[0].ID) assert.EqualValues(t, 3, issues[0].ID)
err = column1.moveIssuesToAnotherColumn(db.DefaultContext, column2) err = column1.moveIssuesToAnotherColumn(db.DefaultContext, column2)
assert.NoError(t, err) require.NoError(t, err)
issues, err = column1.GetIssues(db.DefaultContext) issues, err = column1.GetIssues(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, issues, 0) assert.Empty(t, issues)
issues, err = column2.GetIssues(db.DefaultContext) issues, err = column2.GetIssues(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, issues, 2) assert.Len(t, issues, 2)
assert.EqualValues(t, 3, issues[0].ID) assert.EqualValues(t, 3, issues[0].ID)
assert.EqualValues(t, 0, issues[0].Sorting) assert.EqualValues(t, 0, issues[0].Sorting)
@ -78,11 +79,11 @@ func Test_moveIssuesToAnotherColumn(t *testing.T) {
} }
func Test_MoveColumnsOnProject(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}) project1 := unittest.AssertExistsAndLoadBean(t, &Project{ID: 1})
columns, err := project1.GetColumns(db.DefaultContext) columns, err := project1.GetColumns(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, columns, 3) 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[0].Sorting) // even if there is no default sorting, the code should also work
assert.EqualValues(t, 0, columns[1].Sorting) assert.EqualValues(t, 0, columns[1].Sorting)
@ -93,10 +94,10 @@ func Test_MoveColumnsOnProject(t *testing.T) {
1: columns[2].ID, 1: columns[2].ID,
2: columns[0].ID, 2: columns[0].ID,
}) })
assert.NoError(t, err) require.NoError(t, err)
columnsAfter, err := project1.GetColumns(db.DefaultContext) columnsAfter, err := project1.GetColumns(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, columnsAfter, 3) assert.Len(t, columnsAfter, 3)
assert.EqualValues(t, columns[1].ID, columnsAfter[0].ID) assert.EqualValues(t, columns[1].ID, columnsAfter[0].ID)
assert.EqualValues(t, columns[2].ID, columnsAfter[1].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) { func Test_NewColumn(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
project1 := unittest.AssertExistsAndLoadBean(t, &Project{ID: 1}) project1 := unittest.AssertExistsAndLoadBean(t, &Project{ID: 1})
columns, err := project1.GetColumns(db.DefaultContext) columns, err := project1.GetColumns(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, columns, 3) assert.Len(t, columns, 3)
for i := 0; i < maxProjectColumns-3; i++ { for i := 0; i < maxProjectColumns-3; i++ {
@ -116,12 +117,12 @@ func Test_NewColumn(t *testing.T) {
Title: fmt.Sprintf("column-%d", i+4), Title: fmt.Sprintf("column-%d", i+4),
ProjectID: project1.ID, ProjectID: project1.ID,
}) })
assert.NoError(t, err) require.NoError(t, err)
} }
err = NewColumn(db.DefaultContext, &Column{ err = NewColumn(db.DefaultContext, &Column{
Title: "column-21", Title: "column-21",
ProjectID: project1.ID, ProjectID: project1.ID,
}) })
assert.Error(t, err) require.Error(t, err)
assert.True(t, strings.Contains(err.Error(), "maximum number of columns reached")) assert.True(t, strings.Contains(err.Error(), "maximum number of columns reached"))
} }

View file

@ -11,6 +11,7 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestIsProjectTypeValid(t *testing.T) { func TestIsProjectTypeValid(t *testing.T) {
@ -32,23 +33,23 @@ func TestIsProjectTypeValid(t *testing.T) {
} }
func TestGetProjects(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}) 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 // 1 value for this repo exists in the fixtures
assert.Len(t, projects, 1) assert.Len(t, projects, 1)
projects, err = db.Find[Project](db.DefaultContext, SearchOptions{RepoID: 3}) 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 // 1 value for this repo exists in the fixtures
assert.Len(t, projects, 1) assert.Len(t, projects, 1)
} }
func TestProject(t *testing.T) { func TestProject(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
project := &Project{ project := &Project{
Type: TypeRepository, Type: TypeRepository,
@ -60,31 +61,31 @@ func TestProject(t *testing.T) {
CreatorID: 2, CreatorID: 2,
} }
assert.NoError(t, NewProject(db.DefaultContext, project)) require.NoError(t, NewProject(db.DefaultContext, project))
_, err := GetProjectByID(db.DefaultContext, project.ID) _, err := GetProjectByID(db.DefaultContext, project.ID)
assert.NoError(t, err) require.NoError(t, err)
// Update project // Update project
project.Title = "Updated title" 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) projectFromDB, err := GetProjectByID(db.DefaultContext, project.ID)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, project.Title, projectFromDB.Title) 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 // Retrieve from DB afresh to check if it is truly closed
projectFromDB, err = GetProjectByID(db.DefaultContext, project.ID) projectFromDB, err = GetProjectByID(db.DefaultContext, project.ID)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, projectFromDB.IsClosed) assert.True(t, projectFromDB.IsClosed)
} }
func TestProjectsSort(t *testing.T) { func TestProjectsSort(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
tests := []struct { tests := []struct {
sortType string sortType string
@ -112,7 +113,7 @@ func TestProjectsSort(t *testing.T) {
projects, count, err := db.FindAndCount[Project](db.DefaultContext, SearchOptions{ projects, count, err := db.FindAndCount[Project](db.DefaultContext, SearchOptions{
OrderBy: GetSearchOrderByBySortType(tt.sortType), OrderBy: GetSearchOrderByBySortType(tt.sortType),
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, int64(6), count) assert.EqualValues(t, int64(6), count)
if assert.Len(t, projects, 6) { if assert.Len(t, projects, 6) {
for i := range projects { for i := range projects {

View file

@ -16,7 +16,7 @@ import (
) )
func TestRepoArchiveDownloadCount(t *testing.T) { func TestRepoArchiveDownloadCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
release, err := repo_model.GetReleaseByID(db.DefaultContext, 1) release, err := repo_model.GetReleaseByID(db.DefaultContext, 1)
require.NoError(t, err) require.NoError(t, err)

View file

@ -11,62 +11,63 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestIncreaseDownloadCount(t *testing.T) { 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") 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) assert.Equal(t, int64(0), attachment.DownloadCount)
// increase download count // increase download count
err = attachment.IncreaseDownloadCount(db.DefaultContext) 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") 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) assert.Equal(t, int64(1), attachment.DownloadCount)
} }
func TestGetByCommentOrIssueID(t *testing.T) { func TestGetByCommentOrIssueID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
// count of attachments from issue ID // count of attachments from issue ID
attachments, err := repo_model.GetAttachmentsByIssueID(db.DefaultContext, 1) attachments, err := repo_model.GetAttachmentsByIssueID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, attachments, 1) assert.Len(t, attachments, 1)
attachments, err = repo_model.GetAttachmentsByCommentID(db.DefaultContext, 1) attachments, err = repo_model.GetAttachmentsByCommentID(db.DefaultContext, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, attachments, 2) assert.Len(t, attachments, 2)
} }
func TestDeleteAttachments(t *testing.T) { func TestDeleteAttachments(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
count, err := repo_model.DeleteAttachmentsByIssue(db.DefaultContext, 4, false) count, err := repo_model.DeleteAttachmentsByIssue(db.DefaultContext, 4, false)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, 2, count) assert.Equal(t, 2, count)
count, err = repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false) count, err = repo_model.DeleteAttachmentsByComment(db.DefaultContext, 2, false)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, 2, count) assert.Equal(t, 2, count)
err = repo_model.DeleteAttachment(db.DefaultContext, &repo_model.Attachment{ID: 8}, false) 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") 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.True(t, repo_model.IsErrAttachmentNotExist(err))
assert.Nil(t, attachment) assert.Nil(t, attachment)
} }
func TestGetAttachmentByID(t *testing.T) { func TestGetAttachmentByID(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
attach, err := repo_model.GetAttachmentByID(db.DefaultContext, 1) 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) 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) { func TestUpdateAttachment(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
attach, err := repo_model.GetAttachmentByID(db.DefaultContext, 1) 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) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attach.UUID)
attach.Name = "new_name" 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"}) unittest.AssertExistsAndLoadBean(t, &repo_model.Attachment{Name: "new_name"})
} }
func TestGetAttachmentsByUUIDs(t *testing.T) { 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"}) 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.Len(t, attachList, 2)
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attachList[0].UUID) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11", attachList[0].UUID)
assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", attachList[1].UUID) assert.Equal(t, "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a17", attachList[1].UUID)

View file

@ -14,16 +14,17 @@ import (
user_model "code.gitea.io/gitea/models/user" user_model "code.gitea.io/gitea/models/user"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestRepository_GetCollaborators(t *testing.T) { func TestRepository_GetCollaborators(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID int64) { test := func(repoID int64) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
collaborators, err := repo_model.GetCollaborators(db.DefaultContext, repo.ID, db.ListOptions{}) 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}) 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)) assert.Len(t, collaborators, int(expectedLen))
for _, collaborator := range collaborators { for _, collaborator := range collaborators {
assert.EqualValues(t, collaborator.User.ID, collaborator.Collaboration.UserID) 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}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 22})
collaborators1, err := repo_model.GetCollaborators(db.DefaultContext, repo.ID, db.ListOptions{PageSize: 1, Page: 1}) 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) assert.Len(t, collaborators1, 1)
collaborators2, err := repo_model.GetCollaborators(db.DefaultContext, repo.ID, db.ListOptions{PageSize: 1, Page: 2}) 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.Len(t, collaborators2, 1)
assert.NotEqualValues(t, collaborators1[0].ID, collaborators2[0].ID) assert.NotEqualValues(t, collaborators1[0].ID, collaborators2[0].ID)
} }
func TestRepository_IsCollaborator(t *testing.T) { func TestRepository_IsCollaborator(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
test := func(repoID, userID int64, expected bool) { test := func(repoID, userID int64, expected bool) {
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: repoID})
actual, err := repo_model.IsCollaborator(db.DefaultContext, repo.ID, userID) actual, err := repo_model.IsCollaborator(db.DefaultContext, repo.ID, userID)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, expected, actual) assert.Equal(t, expected, actual)
} }
test(3, 2, true) test(3, 2, true)
@ -65,10 +66,10 @@ func TestRepository_IsCollaborator(t *testing.T) {
} }
func TestRepository_ChangeCollaborationAccessMode(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}) 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}) collaboration := unittest.AssertExistsAndLoadBean(t, &repo_model.Collaboration{RepoID: repo.ID, UserID: 4})
assert.EqualValues(t, perm.AccessModeAdmin, collaboration.Mode) 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}) access := unittest.AssertExistsAndLoadBean(t, &access_model.Access{UserID: 4, RepoID: repo.ID})
assert.EqualValues(t, perm.AccessModeAdmin, access.Mode) 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. // 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}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repo.ID})
} }
func TestRepository_CountCollaborators(t *testing.T) { 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}) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
count, err := db.Count[repo_model.Collaboration](db.DefaultContext, repo_model.FindCollaborationOptions{ count, err := db.Count[repo_model.Collaboration](db.DefaultContext, repo_model.FindCollaborationOptions{
RepoID: repo1.ID, RepoID: repo1.ID,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 2, count) assert.EqualValues(t, 2, count)
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 22}) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 22})
count, err = db.Count[repo_model.Collaboration](db.DefaultContext, repo_model.FindCollaborationOptions{ count, err = db.Count[repo_model.Collaboration](db.DefaultContext, repo_model.FindCollaborationOptions{
RepoID: repo2.ID, RepoID: repo2.ID,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 2, count) assert.EqualValues(t, 2, count)
// Non-existent repository. // Non-existent repository.
count, err = db.Count[repo_model.Collaboration](db.DefaultContext, repo_model.FindCollaborationOptions{ count, err = db.Count[repo_model.Collaboration](db.DefaultContext, repo_model.FindCollaborationOptions{
RepoID: unittest.NonexistentID, RepoID: unittest.NonexistentID,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 0, count) assert.EqualValues(t, 0, count)
} }
func TestRepository_IsOwnerMemberCollaborator(t *testing.T) { 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}) repo1 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
// Organisation owner. // Organisation owner.
actual, err := repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 2) actual, err := repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 2)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, actual) assert.True(t, actual)
// Team member. // Team member.
actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 4) actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 4)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, actual) assert.True(t, actual)
// Normal user. // Normal user.
actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 1) actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo1, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, actual) assert.False(t, actual)
repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repo2 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
// Collaborator. // Collaborator.
actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo2, 4) actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo2, 4)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, actual) assert.True(t, actual)
repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 15}) repo3 := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 15})
// Repository owner. // Repository owner.
actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo3, 2) actual, err = repo_model.IsOwnerMemberCollaborator(db.DefaultContext, repo3, 2)
assert.NoError(t, err) require.NoError(t, err)
assert.True(t, actual) assert.True(t, actual)
} }
func TestRepo_GetCollaboration(t *testing.T) { 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}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
// Existing collaboration. // Existing collaboration.
collab, err := repo_model.GetCollaboration(db.DefaultContext, repo.ID, 4) collab, err := repo_model.GetCollaboration(db.DefaultContext, repo.ID, 4)
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, collab) assert.NotNil(t, collab)
assert.EqualValues(t, 4, collab.UserID) assert.EqualValues(t, 4, collab.UserID)
assert.EqualValues(t, 4, collab.RepoID) assert.EqualValues(t, 4, collab.RepoID)
// Non-existing collaboration. // Non-existing collaboration.
collab, err = repo_model.GetCollaboration(db.DefaultContext, repo.ID, 1) collab, err = repo_model.GetCollaboration(db.DefaultContext, repo.ID, 1)
assert.NoError(t, err) require.NoError(t, err)
assert.Nil(t, collab) assert.Nil(t, collab)
} }
func TestGetCollaboratorWithUser(t *testing.T) { func TestGetCollaboratorWithUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
user16 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 16}) user16 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 16})
user15 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 15}) user15 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 15})
user18 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 18}) user18 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 18})
collabs, err := repo_model.GetCollaboratorWithUser(db.DefaultContext, user16.ID, user15.ID) 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.Len(t, collabs, 2)
assert.EqualValues(t, 5, collabs[0]) assert.EqualValues(t, 5, collabs[0])
assert.EqualValues(t, 7, collabs[1]) assert.EqualValues(t, 7, collabs[1])
collabs, err = repo_model.GetCollaboratorWithUser(db.DefaultContext, user16.ID, user18.ID) 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.Len(t, collabs, 2)
assert.EqualValues(t, 6, collabs[0]) assert.EqualValues(t, 6, collabs[0])
assert.EqualValues(t, 8, collabs[1]) assert.EqualValues(t, 8, collabs[1])

View file

@ -11,23 +11,24 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestGetUserFork(t *testing.T) { func TestGetUserFork(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
// User13 has repo 11 forked from repo10 // User13 has repo 11 forked from repo10
repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 10) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 10)
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, repo) assert.NotNil(t, repo)
repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13) repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13)
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, repo) assert.NotNil(t, repo)
repo, err = repo_model.GetRepositoryByID(db.DefaultContext, 9) repo, err = repo_model.GetRepositoryByID(db.DefaultContext, 9)
assert.NoError(t, err) require.NoError(t, err)
assert.NotNil(t, repo) assert.NotNil(t, repo)
repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13) repo, err = repo_model.GetUserFork(db.DefaultContext, repo.ID, 13)
assert.NoError(t, err) require.NoError(t, err)
assert.Nil(t, repo) assert.Nil(t, repo)
} }

View file

@ -13,10 +13,11 @@ import (
"code.gitea.io/gitea/modules/timeutil" "code.gitea.io/gitea/modules/timeutil"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestPushMirrorsIterate(t *testing.T) { func TestPushMirrorsIterate(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
now := timeutil.TimeStampNow() now := timeutil.TimeStampNow()

View file

@ -11,13 +11,14 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestLookupRedirect(t *testing.T) { func TestLookupRedirect(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repoID, err := repo_model.LookupRedirect(db.DefaultContext, 2, "oldrepo1") repoID, err := repo_model.LookupRedirect(db.DefaultContext, 2, "oldrepo1")
assert.NoError(t, err) require.NoError(t, err)
assert.EqualValues(t, 1, repoID) assert.EqualValues(t, 1, repoID)
_, err = repo_model.LookupRedirect(db.DefaultContext, unittest.NonexistentID, "doesnotexist") _, err = repo_model.LookupRedirect(db.DefaultContext, unittest.NonexistentID, "doesnotexist")
@ -26,10 +27,10 @@ func TestLookupRedirect(t *testing.T) {
func TestNewRedirect(t *testing.T) { func TestNewRedirect(t *testing.T) {
// redirect to a completely new name // 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}) 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{ unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
OwnerID: repo.OwnerID, OwnerID: repo.OwnerID,
@ -45,10 +46,10 @@ func TestNewRedirect(t *testing.T) {
func TestNewRedirect2(t *testing.T) { func TestNewRedirect2(t *testing.T) {
// redirect to previously used name // redirect to previously used name
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) 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{ unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
OwnerID: repo.OwnerID, OwnerID: repo.OwnerID,
@ -64,10 +65,10 @@ func TestNewRedirect2(t *testing.T) {
func TestNewRedirect3(t *testing.T) { func TestNewRedirect3(t *testing.T) {
// redirect for a previously-unredirected repo // 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}) 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{ unittest.AssertExistsAndLoadBean(t, &repo_model.Redirect{
OwnerID: repo.OwnerID, OwnerID: repo.OwnerID,

View file

@ -9,11 +9,11 @@ import (
"code.gitea.io/gitea/models/db" "code.gitea.io/gitea/models/db"
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require"
) )
func TestMigrate_InsertReleases(t *testing.T) { func TestMigrate_InsertReleases(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
a := &Attachment{ a := &Attachment{
UUID: "a0eebc91-9c0c-4ef7-bb6e-6bb9bd380a12", UUID: "a0eebc91-9c0c-4ef7-bb6e-6bb9bd380a12",
@ -23,5 +23,5 @@ func TestMigrate_InsertReleases(t *testing.T) {
} }
err := InsertReleases(db.DefaultContext, r) err := InsertReleases(db.DefaultContext, r)
assert.NoError(t, err) require.NoError(t, err)
} }

View file

@ -11,10 +11,11 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestRepositoryFlags(t *testing.T) { func TestRepositoryFlags(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}) 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 // Unless we add flags, the repo has none
flags, err := repo.ListFlags(db.DefaultContext) flags, err := repo.ListFlags(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Empty(t, flags) assert.Empty(t, flags)
// If the repo has no flags, it is not flagged // 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 // Trying to retrieve a non-existent flag indicates not found
has, _, err = repo.GetFlag(db.DefaultContext, "foo") has, _, err = repo.GetFlag(db.DefaultContext, "foo")
assert.NoError(t, err) require.NoError(t, err)
assert.False(t, has) assert.False(t, has)
// Deleting a non-existent flag fails // Deleting a non-existent flag fails
deleted, err := repo.DeleteFlag(db.DefaultContext, "no-such-flag") deleted, err := repo.DeleteFlag(db.DefaultContext, "no-such-flag")
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(0), deleted) assert.Equal(t, int64(0), deleted)
// ******************** // ********************
@ -50,15 +51,15 @@ func TestRepositoryFlags(t *testing.T) {
// Adding a flag works // Adding a flag works
err = repo.AddFlag(db.DefaultContext, "foo") err = repo.AddFlag(db.DefaultContext, "foo")
assert.NoError(t, err) require.NoError(t, err)
// Adding it again fails // Adding it again fails
err = repo.AddFlag(db.DefaultContext, "foo") err = repo.AddFlag(db.DefaultContext, "foo")
assert.Error(t, err) require.Error(t, err)
// Listing flags includes the one we added // Listing flags includes the one we added
flags, err = repo.ListFlags(db.DefaultContext) flags, err = repo.ListFlags(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, flags, 1) assert.Len(t, flags, 1)
assert.Equal(t, "foo", flags[0].Name) assert.Equal(t, "foo", flags[0].Name)
@ -72,22 +73,22 @@ func TestRepositoryFlags(t *testing.T) {
// Added flag can be retrieved // Added flag can be retrieved
_, flag, err := repo.GetFlag(db.DefaultContext, "foo") _, flag, err := repo.GetFlag(db.DefaultContext, "foo")
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, "foo", flag.Name) assert.Equal(t, "foo", flag.Name)
// Deleting a flag works // Deleting a flag works
deleted, err = repo.DeleteFlag(db.DefaultContext, "foo") deleted, err = repo.DeleteFlag(db.DefaultContext, "foo")
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(1), deleted) assert.Equal(t, int64(1), deleted)
// The list is now empty // The list is now empty
flags, err = repo.ListFlags(db.DefaultContext) flags, err = repo.ListFlags(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Empty(t, flags) assert.Empty(t, flags)
// Replacing an empty list works // Replacing an empty list works
err = repo.ReplaceAllFlags(db.DefaultContext, []string{"bar"}) err = repo.ReplaceAllFlags(db.DefaultContext, []string{"bar"})
assert.NoError(t, err) require.NoError(t, err)
// The repo is now flagged with "bar" // The repo is now flagged with "bar"
has = repo.HasFlag(db.DefaultContext, "bar") has = repo.HasFlag(db.DefaultContext, "bar")
@ -95,18 +96,18 @@ func TestRepositoryFlags(t *testing.T) {
// Replacing a tag set with another works // Replacing a tag set with another works
err = repo.ReplaceAllFlags(db.DefaultContext, []string{"baz", "quux"}) err = repo.ReplaceAllFlags(db.DefaultContext, []string{"baz", "quux"})
assert.NoError(t, err) require.NoError(t, err)
// The repo now has two tags // The repo now has two tags
flags, err = repo.ListFlags(db.DefaultContext) flags, err = repo.ListFlags(db.DefaultContext)
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, flags, 2) assert.Len(t, flags, 2)
assert.Equal(t, "baz", flags[0].Name) assert.Equal(t, "baz", flags[0].Name)
assert.Equal(t, "quux", flags[1].Name) assert.Equal(t, "quux", flags[1].Name)
// Replacing flags with an empty set deletes all flags // Replacing flags with an empty set deletes all flags
err = repo.ReplaceAllFlags(db.DefaultContext, []string{}) err = repo.ReplaceAllFlags(db.DefaultContext, []string{})
assert.NoError(t, err) require.NoError(t, err)
// The repo is now unflagged // The repo is now unflagged
flagged = repo.IsFlagged(db.DefaultContext) flagged = repo.IsFlagged(db.DefaultContext)

View file

@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/modules/optional" "code.gitea.io/gitea/modules/optional"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func getTestCases() []struct { func getTestCases() []struct {
@ -181,7 +182,7 @@ func getTestCases() []struct {
} }
func TestSearchRepository(t *testing.T) { func TestSearchRepository(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
// test search public repository on explore page // test search public repository on explore page
repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{ repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{
@ -193,7 +194,7 @@ func TestSearchRepository(t *testing.T) {
Collaborate: optional.Some(false), Collaborate: optional.Some(false),
}) })
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, repos, 1) { if assert.Len(t, repos, 1) {
assert.Equal(t, "test_repo_12", repos[0].Name) assert.Equal(t, "test_repo_12", repos[0].Name)
} }
@ -208,7 +209,7 @@ func TestSearchRepository(t *testing.T) {
Collaborate: optional.Some(false), Collaborate: optional.Some(false),
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(2), count) assert.Equal(t, int64(2), count)
assert.Len(t, repos, 2) assert.Len(t, repos, 2)
@ -223,7 +224,7 @@ func TestSearchRepository(t *testing.T) {
Collaborate: optional.Some(false), Collaborate: optional.Some(false),
}) })
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, repos, 1) { if assert.Len(t, repos, 1) {
assert.Equal(t, "test_repo_13", repos[0].Name) assert.Equal(t, "test_repo_13", repos[0].Name)
} }
@ -239,14 +240,14 @@ func TestSearchRepository(t *testing.T) {
Collaborate: optional.Some(false), Collaborate: optional.Some(false),
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(3), count) assert.Equal(t, int64(3), count)
assert.Len(t, repos, 3) assert.Len(t, repos, 3)
// Test non existing owner // Test non existing owner
repos, count, err = repo_model.SearchRepositoryByName(db.DefaultContext, &repo_model.SearchRepoOptions{OwnerID: unittest.NonexistentID}) 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.Empty(t, repos)
assert.Equal(t, int64(0), count) assert.Equal(t, int64(0), count)
@ -261,7 +262,7 @@ func TestSearchRepository(t *testing.T) {
IncludeDescription: true, IncludeDescription: true,
}) })
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, repos, 1) { if assert.Len(t, repos, 1) {
assert.Equal(t, "test_repo_14", repos[0].Name) assert.Equal(t, "test_repo_14", repos[0].Name)
} }
@ -278,7 +279,7 @@ func TestSearchRepository(t *testing.T) {
IncludeDescription: false, IncludeDescription: false,
}) })
assert.NoError(t, err) require.NoError(t, err)
assert.Empty(t, repos) assert.Empty(t, repos)
assert.Equal(t, int64(0), count) assert.Equal(t, int64(0), count)
@ -288,7 +289,7 @@ func TestSearchRepository(t *testing.T) {
t.Run(testCase.name, func(t *testing.T) { t.Run(testCase.name, func(t *testing.T) {
repos, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts) 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) assert.Equal(t, int64(testCase.count), count)
page := testCase.opts.Page page := testCase.opts.Page
@ -355,7 +356,7 @@ func TestSearchRepository(t *testing.T) {
} }
func TestCountRepository(t *testing.T) { func TestCountRepository(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testCases := getTestCases() testCases := getTestCases()
@ -363,14 +364,14 @@ func TestCountRepository(t *testing.T) {
t.Run(testCase.name, func(t *testing.T) { t.Run(testCase.name, func(t *testing.T) {
count, err := repo_model.CountRepository(db.DefaultContext, testCase.opts) count, err := repo_model.CountRepository(db.DefaultContext, testCase.opts)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(testCase.count), count) assert.Equal(t, int64(testCase.count), count)
}) })
} }
} }
func TestSearchRepositoryByTopicName(t *testing.T) { func TestSearchRepositoryByTopicName(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
testCases := []struct { testCases := []struct {
name string name string
@ -397,7 +398,7 @@ func TestSearchRepositoryByTopicName(t *testing.T) {
for _, testCase := range testCases { for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) { t.Run(testCase.name, func(t *testing.T) {
_, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts) _, count, err := repo_model.SearchRepositoryByName(db.DefaultContext, testCase.opts)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(testCase.count), count) assert.Equal(t, int64(testCase.count), count)
}) })
} }

View file

@ -18,6 +18,7 @@ import (
"code.gitea.io/gitea/modules/test" "code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
var ( var (
@ -27,58 +28,58 @@ var (
) )
func TestGetRepositoryCount(t *testing.T) { func TestGetRepositoryCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
ctx := db.DefaultContext ctx := db.DefaultContext
count, err1 := repo_model.CountRepositories(ctx, countRepospts) count, err1 := repo_model.CountRepositories(ctx, countRepospts)
privateCount, err2 := repo_model.CountRepositories(ctx, countReposptsPrivate) privateCount, err2 := repo_model.CountRepositories(ctx, countReposptsPrivate)
publicCount, err3 := repo_model.CountRepositories(ctx, countReposptsPublic) publicCount, err3 := repo_model.CountRepositories(ctx, countReposptsPublic)
assert.NoError(t, err1) require.NoError(t, err1)
assert.NoError(t, err2) require.NoError(t, err2)
assert.NoError(t, err3) require.NoError(t, err3)
assert.Equal(t, int64(3), count) assert.Equal(t, int64(3), count)
assert.Equal(t, privateCount+publicCount, count) assert.Equal(t, privateCount+publicCount, count)
} }
func TestGetPublicRepositoryCount(t *testing.T) { func TestGetPublicRepositoryCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
count, err := repo_model.CountRepositories(db.DefaultContext, countReposptsPublic) count, err := repo_model.CountRepositories(db.DefaultContext, countReposptsPublic)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(1), count) assert.Equal(t, int64(1), count)
} }
func TestGetPrivateRepositoryCount(t *testing.T) { func TestGetPrivateRepositoryCount(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
count, err := repo_model.CountRepositories(db.DefaultContext, countReposptsPrivate) count, err := repo_model.CountRepositories(db.DefaultContext, countReposptsPrivate)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, int64(2), count) assert.Equal(t, int64(2), count)
} }
func TestRepoAPIURL(t *testing.T) { func TestRepoAPIURL(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 10})
assert.Equal(t, "https://try.gitea.io/api/v1/repos/user12/repo10", repo.APIURL()) assert.Equal(t, "https://try.gitea.io/api/v1/repos/user12/repo10", repo.APIURL())
} }
func TestWatchRepo(t *testing.T) { func TestWatchRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
const repoID = 3 const repoID = 3
const userID = 2 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.AssertExistsAndLoadBean(t, &repo_model.Watch{RepoID: repoID, UserID: userID})
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}) 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.AssertNotExistsBean(t, &repo_model.Watch{RepoID: repoID, UserID: userID})
unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID}) unittest.CheckConsistencyFor(t, &repo_model.Repository{ID: repoID})
} }
func TestMetas(t *testing.T) { func TestMetas(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo := &repo_model.Repository{Name: "testRepo"} repo := &repo_model.Repository{Name: "testRepo"}
repo.Owner = &user_model.User{Name: "testOwner"} repo.Owner = &user_model.User{Name: "testOwner"}
@ -119,7 +120,7 @@ func TestMetas(t *testing.T) {
testSuccess(markup.IssueNameStyleRegexp) testSuccess(markup.IssueNameStyleRegexp)
repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 3) repo, err := repo_model.GetRepositoryByID(db.DefaultContext, 3)
assert.NoError(t, err) require.NoError(t, err)
metas = repo.ComposeMetas(db.DefaultContext) metas = repo.ComposeMetas(db.DefaultContext)
assert.Contains(t, metas, "org") assert.Contains(t, metas, "org")
@ -129,13 +130,13 @@ func TestMetas(t *testing.T) {
} }
func TestGetRepositoryByURL(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) { t.Run("InvalidPath", func(t *testing.T) {
repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, "something") repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, "something")
assert.Nil(t, repo) assert.Nil(t, repo)
assert.Error(t, err) require.Error(t, err)
}) })
t.Run("ValidHttpURL", func(t *testing.T) { t.Run("ValidHttpURL", func(t *testing.T) {
@ -143,10 +144,10 @@ func TestGetRepositoryByURL(t *testing.T) {
repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, url) repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, url)
assert.NotNil(t, repo) assert.NotNil(t, repo)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, repo.ID, int64(2)) assert.Equal(t, int64(2), repo.ID)
assert.Equal(t, repo.OwnerID, int64(2)) assert.Equal(t, int64(2), repo.OwnerID)
} }
test(t, "https://try.gitea.io/user2/repo2") 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) repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, url)
assert.NotNil(t, repo) assert.NotNil(t, repo)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, repo.ID, int64(2)) assert.Equal(t, int64(2), repo.ID)
assert.Equal(t, repo.OwnerID, int64(2)) assert.Equal(t, int64(2), repo.OwnerID)
} }
test(t, "git+ssh://sshuser@try.gitea.io/user2/repo2") 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) repo, err := repo_model.GetRepositoryByURL(db.DefaultContext, url)
assert.NotNil(t, repo) assert.NotNil(t, repo)
assert.NoError(t, err) require.NoError(t, err)
assert.Equal(t, repo.ID, int64(2)) assert.Equal(t, int64(2), repo.ID)
assert.Equal(t, repo.OwnerID, int64(2)) assert.Equal(t, int64(2), repo.OwnerID)
} }
test(t, "sshuser@try.gitea.io:user2/repo2") test(t, "sshuser@try.gitea.io:user2/repo2")

View file

@ -32,8 +32,8 @@ func TestActionsConfig(t *testing.T) {
} }
func TestRepoUnitAccessMode(t *testing.T) { func TestRepoUnitAccessMode(t *testing.T) {
assert.Equal(t, UnitAccessModeNone.ToAccessMode(perm.AccessModeAdmin), perm.AccessModeNone) assert.Equal(t, perm.AccessModeNone, UnitAccessModeNone.ToAccessMode(perm.AccessModeAdmin))
assert.Equal(t, UnitAccessModeRead.ToAccessMode(perm.AccessModeAdmin), perm.AccessModeRead) assert.Equal(t, perm.AccessModeRead, UnitAccessModeRead.ToAccessMode(perm.AccessModeAdmin))
assert.Equal(t, UnitAccessModeWrite.ToAccessMode(perm.AccessModeAdmin), perm.AccessModeWrite) assert.Equal(t, perm.AccessModeWrite, UnitAccessModeWrite.ToAccessMode(perm.AccessModeAdmin))
assert.Equal(t, UnitAccessModeUnset.ToAccessMode(perm.AccessModeRead), perm.AccessModeRead) assert.Equal(t, perm.AccessModeRead, UnitAccessModeUnset.ToAccessMode(perm.AccessModeRead))
} }

View file

@ -11,33 +11,34 @@ import (
"code.gitea.io/gitea/models/unittest" "code.gitea.io/gitea/models/unittest"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
) )
func TestStarRepo(t *testing.T) { func TestStarRepo(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
const userID = 2 const userID = 2
const repoID = 1 const repoID = 1
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) 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}) 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}) 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}) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID})
} }
func TestIsStaring(t *testing.T) { 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.True(t, repo_model.IsStaring(db.DefaultContext, 2, 4))
assert.False(t, repo_model.IsStaring(db.DefaultContext, 3, 4)) assert.False(t, repo_model.IsStaring(db.DefaultContext, 3, 4))
} }
func TestRepository_GetStargazers(t *testing.T) { func TestRepository_GetStargazers(t *testing.T) {
// repo with stargazers // repo with stargazers
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 4})
gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0})
assert.NoError(t, err) require.NoError(t, err)
if assert.Len(t, gazers, 1) { if assert.Len(t, gazers, 1) {
assert.Equal(t, int64(2), gazers[0].ID) assert.Equal(t, int64(2), gazers[0].ID)
} }
@ -45,27 +46,27 @@ func TestRepository_GetStargazers(t *testing.T) {
func TestRepository_GetStargazers2(t *testing.T) { func TestRepository_GetStargazers2(t *testing.T) {
// repo with stargazers // repo with stargazers
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 3})
gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0})
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, gazers, 0) assert.Empty(t, gazers)
} }
func TestClearRepoStars(t *testing.T) { func TestClearRepoStars(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase()) require.NoError(t, unittest.PrepareTestDatabase())
const userID = 2 const userID = 2
const repoID = 1 const repoID = 1
unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID}) 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}) 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}) 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}) unittest.AssertNotExistsBean(t, &repo_model.Star{UID: userID, RepoID: repoID})
repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) repo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1})
gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0}) gazers, err := repo_model.GetStargazers(db.DefaultContext, repo, db.ListOptions{Page: 0})
assert.NoError(t, err) require.NoError(t, err)
assert.Len(t, gazers, 0) assert.Empty(t, gazers)
} }

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