test: consolidate Go tests (#39962)

Consolidate all Go tests. Coverage is identical to before. Go tests are
around 5% faster while being 7% smaller. No non-test code is touched.
This commit is contained in:
silverwind authored and GitHub committed 2026-10-24 13:48:19 +00:00
1 parent ce7364e215
commit 8abda62312
388 files changed
+18410 -29561

No files matched your search

+27 -52
View File
@@ -9,57 +9,32 @@ import (
"github.com/stretchr/testify/assert"
)
func TestValidatePackageName(t *testing.T) {
bad := []string{
"",
".",
"..",
"-",
"a?b",
"a b",
"a/b",
}
for _, name := range bad {
assert.False(t, isValidPackageName(name), "bad=%q", name)
}
good := []string{
"a",
"1",
"a-",
"a_b",
"c.d+",
}
for _, name := range good {
assert.True(t, isValidPackageName(name), "good=%q", name)
}
}
func TestValidateFileName(t *testing.T) {
bad := []string{
"",
".",
"..",
"a?b",
"a/b",
" a",
"a ",
}
for _, name := range bad {
assert.False(t, isValidFileName(name), "bad=%q", name)
}
good := []string{
"-",
"a",
"1",
"a-",
"a_b",
"a b",
"c.d+",
`-_+=:;.()[]{}~!@#$%^& aA1`,
}
for _, name := range good {
assert.True(t, isValidFileName(name), "good=%q", name)
func TestValidateNames(t *testing.T) {
for _, test := range []struct {
name string
validate func(string) bool
bad, good []string
}{
{
name: "package",
validate: isValidPackageName,
bad: []string{"", ".", "..", "-", "a?b", "a b", "a/b"},
good: []string{"a", "1", "a-", "a_b", "c.d+"},
},
{
name: "file",
validate: isValidFileName,
bad: []string{"", ".", "..", "a?b", "a/b", " a", "a "},
good: []string{"-", "a", "1", "a-", "a_b", "a b", "c.d+", `-_+=:;.()[]{}~!@#$%^& aA1`},
},
} {
t.Run(test.name, func(t *testing.T) {
for _, name := range test.bad {
assert.False(t, test.validate(name), "bad=%q", name)
}
for _, name := range test.good {
assert.True(t, test.validate(name), "good=%q", name)
}
})
}
}
+4 -10
View File
@@ -143,17 +143,11 @@ Here are some links to the most important topics. You can find the full list of
}
input := "[Link](test.md)\n![Image](image.png)"
testRenderMarkdown(t, "gfm", false, input, `<p><a href="http://localhost:3000/user2/repo1/src/branch/main/test.md" rel="nofollow">Link</a>
response := `<p><a href="http://localhost:3000/user2/repo1/src/branch/main/test.md" rel="nofollow">Link</a>
<a href="http://localhost:3000/user2/repo1/src/branch/main/image.png" target="_blank" rel="nofollow noopener"><img src="http://localhost:3000/user2/repo1/media/branch/main/image.png" alt="Image"/></a></p>
`, http.StatusOK)
testRenderMarkdown(t, "gfm", false, input, `<p><a href="http://localhost:3000/user2/repo1/src/branch/main/test.md" rel="nofollow">Link</a>
<a href="http://localhost:3000/user2/repo1/src/branch/main/image.png" target="_blank" rel="nofollow noopener"><img src="http://localhost:3000/user2/repo1/media/branch/main/image.png" alt="Image"/></a></p>
`, http.StatusOK)
testRenderMarkup(t, "gfm", false, "", input, `<p><a href="http://localhost:3000/user2/repo1/src/branch/main/test.md" rel="nofollow">Link</a>
<a href="http://localhost:3000/user2/repo1/src/branch/main/image.png" target="_blank" rel="nofollow noopener"><img src="http://localhost:3000/user2/repo1/media/branch/main/image.png" alt="Image"/></a></p>
`, http.StatusOK)
`
testRenderMarkdown(t, "gfm", false, input, response, http.StatusOK)
testRenderMarkup(t, "gfm", false, "", input, response, http.StatusOK)
testRenderMarkup(t, "file", false, "path/new-file.md", input, `<p><a href="http://localhost:3000/user2/repo1/src/branch/main/path/test.md" rel="nofollow">Link</a>
<a href="http://localhost:3000/user2/repo1/src/branch/main/path/image.png" target="_blank" rel="nofollow noopener"><img src="http://localhost:3000/user2/repo1/media/branch/main/path/image.png" alt="Image"/></a></p>
+23 -60
View File
@@ -17,66 +17,29 @@ import (
func TestTestHookValidation(t *testing.T) {
unittest.PrepareTestEnv(t)
t.Run("Test Validation", func(t *testing.T) {
ctx, _ := contexttest.MockAPIContext(t, "user2/repo1/hooks")
contexttest.LoadRepo(t, ctx, 1)
contexttest.LoadRepoCommit(t, ctx)
contexttest.LoadUser(t, ctx, 2)
cases := []struct {
name string
hookType string
config map[string]string
status int
}{
{"Test Validation", "gitea", map[string]string{"content_type": "json", "url": "https://example.com/webhook"}, 0}, // not written yet
{"Test Validation with invalid URL", "gitea", map[string]string{"content_type": "json", "url": "example.com/webhook"}, http.StatusUnprocessableEntity},
{"Test Validation with invalid webhook type", "unknown", map[string]string{"content_type": "json", "url": "example.com/webhook"}, http.StatusUnprocessableEntity},
{"Test Validation with empty content type", "unknown", map[string]string{"url": "https://example.com/webhook"}, http.StatusUnprocessableEntity},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ctx, _ := contexttest.MockAPIContext(t, "user2/repo1/hooks")
contexttest.LoadRepo(t, ctx, 1)
contexttest.LoadRepoCommit(t, ctx)
contexttest.LoadUser(t, ctx, 2)
checkCreateHookOption(ctx, &structs.CreateHookOption{
Type: "gitea",
Config: map[string]string{
"content_type": "json",
"url": "https://example.com/webhook",
},
checkCreateHookOption(ctx, &structs.CreateHookOption{
Type: tc.hookType,
Config: tc.config,
})
assert.Equal(t, tc.status, ctx.Resp.WrittenStatus())
})
assert.Equal(t, 0, ctx.Resp.WrittenStatus()) // not written yet
})
t.Run("Test Validation with invalid URL", func(t *testing.T) {
ctx, _ := contexttest.MockAPIContext(t, "user2/repo1/hooks")
contexttest.LoadRepo(t, ctx, 1)
contexttest.LoadRepoCommit(t, ctx)
contexttest.LoadUser(t, ctx, 2)
checkCreateHookOption(ctx, &structs.CreateHookOption{
Type: "gitea",
Config: map[string]string{
"content_type": "json",
"url": "example.com/webhook",
},
})
assert.Equal(t, http.StatusUnprocessableEntity, ctx.Resp.WrittenStatus())
})
t.Run("Test Validation with invalid webhook type", func(t *testing.T) {
ctx, _ := contexttest.MockAPIContext(t, "user2/repo1/hooks")
contexttest.LoadRepo(t, ctx, 1)
contexttest.LoadRepoCommit(t, ctx)
contexttest.LoadUser(t, ctx, 2)
checkCreateHookOption(ctx, &structs.CreateHookOption{
Type: "unknown",
Config: map[string]string{
"content_type": "json",
"url": "example.com/webhook",
},
})
assert.Equal(t, http.StatusUnprocessableEntity, ctx.Resp.WrittenStatus())
})
t.Run("Test Validation with empty content type", func(t *testing.T) {
ctx, _ := contexttest.MockAPIContext(t, "user2/repo1/hooks")
contexttest.LoadRepo(t, ctx, 1)
contexttest.LoadRepoCommit(t, ctx)
contexttest.LoadUser(t, ctx, 2)
checkCreateHookOption(ctx, &structs.CreateHookOption{
Type: "unknown",
Config: map[string]string{
"url": "https://example.com/webhook",
},
})
assert.Equal(t, http.StatusUnprocessableEntity, ctx.Resp.WrittenStatus())
})
}
}
+48 -176
View File
@@ -17,183 +17,55 @@ import (
"github.com/stretchr/testify/assert"
)
func TestNewUserPost_MustChangePassword(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "admin/users/new")
func TestNewUserPost(t *testing.T) {
for _, tc := range []struct {
name string
email string
mustChangePassword bool
visibility api.VisibleType
}{
{name: "MustChangePassword", email: "gitea@gitea.io", mustChangePassword: true},
{name: "MustChangePasswordFalseAndDefaultVisibility", email: "gitea@gitea.io"},
{name: "InvalidEmail", email: "gitea@gitea.io\r\n"},
{name: "VisibilityPrivate", email: "gitea@gitea.io", visibility: api.VisibleTypePrivate},
} {
t.Run(tc.name, func(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "admin/users/new")
ctx.Doer = unittest.AssertExistsAndLoadBean(t, &user_model.User{IsAdmin: true, ID: 2})
u := unittest.AssertExistsAndLoadBean(t, &user_model.User{
IsAdmin: true,
ID: 2,
})
web.SetForm(ctx, &forms.AdminCreateUserForm{
LoginType: "local",
LoginName: "local",
UserName: "gitea",
Email: tc.email,
Password: "abc123ABC!=$",
SendNotify: false,
MustChangePassword: tc.mustChangePassword,
Visibility: tc.visibility,
})
NewUserPost(ctx)
ctx.Doer = u
username := "gitea"
email := "gitea@gitea.io"
form := forms.AdminCreateUserForm{
LoginType: "local",
LoginName: "local",
UserName: username,
Email: email,
Password: "abc123ABC!=$",
SendNotify: false,
MustChangePassword: true,
if tc.name == "InvalidEmail" {
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
return
}
assert.NotEmpty(t, ctx.Flash.SuccessMsg)
user, err := user_model.GetUserByName(ctx, "gitea")
assert.NoError(t, err)
assert.Equal(t, "gitea", user.Name)
assert.Equal(t, tc.email, user.Email)
switch tc.name {
case "MustChangePassword":
assert.True(t, user.MustChangePassword)
case "MustChangePasswordFalseAndDefaultVisibility":
assert.False(t, user.MustChangePassword)
// As default user visibility
assert.Equal(t, setting.Service.DefaultUserVisibilityMode, user.Visibility)
case "VisibilityPrivate":
// As default user visibility
assert.True(t, user.Visibility.IsPrivate())
}
})
}
web.SetForm(ctx, &form)
NewUserPost(ctx)
assert.NotEmpty(t, ctx.Flash.SuccessMsg)
u, err := user_model.GetUserByName(ctx, username)
assert.NoError(t, err)
assert.Equal(t, username, u.Name)
assert.Equal(t, email, u.Email)
assert.True(t, u.MustChangePassword)
}
func TestNewUserPost_MustChangePasswordFalse(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "admin/users/new")
u := unittest.AssertExistsAndLoadBean(t, &user_model.User{
IsAdmin: true,
ID: 2,
})
ctx.Doer = u
username := "gitea"
email := "gitea@gitea.io"
form := forms.AdminCreateUserForm{
LoginType: "local",
LoginName: "local",
UserName: username,
Email: email,
Password: "abc123ABC!=$",
SendNotify: false,
MustChangePassword: false,
}
web.SetForm(ctx, &form)
NewUserPost(ctx)
assert.NotEmpty(t, ctx.Flash.SuccessMsg)
u, err := user_model.GetUserByName(ctx, username)
assert.NoError(t, err)
assert.Equal(t, username, u.Name)
assert.Equal(t, email, u.Email)
assert.False(t, u.MustChangePassword)
}
func TestNewUserPost_InvalidEmail(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "admin/users/new")
u := unittest.AssertExistsAndLoadBean(t, &user_model.User{
IsAdmin: true,
ID: 2,
})
ctx.Doer = u
username := "gitea"
email := "gitea@gitea.io\r\n"
form := forms.AdminCreateUserForm{
LoginType: "local",
LoginName: "local",
UserName: username,
Email: email,
Password: "abc123ABC!=$",
SendNotify: false,
MustChangePassword: false,
}
web.SetForm(ctx, &form)
NewUserPost(ctx)
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
}
func TestNewUserPost_VisibilityDefaultPublic(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "admin/users/new")
u := unittest.AssertExistsAndLoadBean(t, &user_model.User{
IsAdmin: true,
ID: 2,
})
ctx.Doer = u
username := "gitea"
email := "gitea@gitea.io"
form := forms.AdminCreateUserForm{
LoginType: "local",
LoginName: "local",
UserName: username,
Email: email,
Password: "abc123ABC!=$",
SendNotify: false,
MustChangePassword: false,
}
web.SetForm(ctx, &form)
NewUserPost(ctx)
assert.NotEmpty(t, ctx.Flash.SuccessMsg)
u, err := user_model.GetUserByName(ctx, username)
assert.NoError(t, err)
assert.Equal(t, username, u.Name)
assert.Equal(t, email, u.Email)
// As default user visibility
assert.Equal(t, setting.Service.DefaultUserVisibilityMode, u.Visibility)
}
func TestNewUserPost_VisibilityPrivate(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "admin/users/new")
u := unittest.AssertExistsAndLoadBean(t, &user_model.User{
IsAdmin: true,
ID: 2,
})
ctx.Doer = u
username := "gitea"
email := "gitea@gitea.io"
form := forms.AdminCreateUserForm{
LoginType: "local",
LoginName: "local",
UserName: username,
Email: email,
Password: "abc123ABC!=$",
SendNotify: false,
MustChangePassword: false,
Visibility: api.VisibleTypePrivate,
}
web.SetForm(ctx, &form)
NewUserPost(ctx)
assert.NotEmpty(t, ctx.Flash.SuccessMsg)
u, err := user_model.GetUserByName(ctx, username)
assert.NoError(t, err)
assert.Equal(t, username, u.Name)
assert.Equal(t, email, u.Email)
// As default user visibility
assert.True(t, u.Visibility.IsPrivate())
}
+48 -65
View File
@@ -77,73 +77,56 @@ func TestViewSummaryBranchFromRun(t *testing.T) {
}
func TestConvertToViewModel(t *testing.T) {
task := &actions_model.ActionTask{
Status: actions_model.StatusSuccess,
Steps: []*actions_model.ActionTaskStep{
{Name: "Run step-name", Index: 0, Status: actions_model.StatusSuccess, LogLength: 1, Started: timeutil.TimeStamp(1), Stopped: timeutil.TimeStamp(5)},
for _, c := range []struct {
name string
task actions_model.ActionTask
expectedViewJobs []*ViewJobStep
}{
{
name: "success",
task: actions_model.ActionTask{
Status: actions_model.StatusSuccess,
Steps: []*actions_model.ActionTaskStep{
{Name: "Run step-name", Index: 0, Status: actions_model.StatusSuccess, LogLength: 1, Started: timeutil.TimeStamp(1), Stopped: timeutil.TimeStamp(5)},
},
Stopped: timeutil.TimeStamp(20),
},
expectedViewJobs: []*ViewJobStep{
{Summary: "Set up job", Duration: "0s", Status: "success"},
{Summary: "Run step-name", Duration: "4s", Status: "success"},
{Summary: "Complete job", Duration: "15s", Status: "success"},
},
},
Stopped: timeutil.TimeStamp(20),
{
name: "cancelling task does not render running steps",
task: actions_model.ActionTask{
Status: actions_model.StatusCancelling,
Steps: []*actions_model.ActionTaskStep{
{Name: "Run step-name", Index: 0, Status: actions_model.StatusRunning, LogLength: 1},
},
},
expectedViewJobs: []*ViewJobStep{
{Summary: "Set up job", Duration: "0s", Status: "success"},
{Summary: "Run step-name", Duration: "0s", Status: "cancelling"},
{Summary: "Complete job", Duration: "0s", Status: "pending"},
},
},
} {
t.Run(c.name, func(t *testing.T) {
viewJobSteps, _, err := convertToViewModel(t.Context(), translation.MockLocale{}, nil, &c.task)
require.NoError(t, err)
if c.task.Status == actions_model.StatusSuccess {
t.Run("out of range cursor step", func(t *testing.T) {
cursors := []LogCursor{{Step: -1, Expanded: true}, {Step: 3, Expanded: true}}
_, logs, err := convertToViewModel(t.Context(), translation.MockLocale{}, cursors, &c.task)
require.NoError(t, err)
assert.Empty(t, logs)
})
}
assert.Equal(t, c.expectedViewJobs, viewJobSteps)
})
}
viewJobSteps, _, err := convertToViewModel(t.Context(), translation.MockLocale{}, nil, task)
require.NoError(t, err)
t.Run("out of range cursor step", func(t *testing.T) {
cursors := []LogCursor{{Step: -1, Expanded: true}, {Step: 3, Expanded: true}}
_, logs, err := convertToViewModel(t.Context(), translation.MockLocale{}, cursors, task)
require.NoError(t, err)
assert.Empty(t, logs)
})
expectedViewJobs := []*ViewJobStep{
{
Summary: "Set up job",
Duration: "0s",
Status: "success",
},
{
Summary: "Run step-name",
Duration: "4s",
Status: "success",
},
{
Summary: "Complete job",
Duration: "15s",
Status: "success",
},
}
assert.Equal(t, expectedViewJobs, viewJobSteps)
}
func TestConvertToViewModelCancellingTaskDoesNotRenderRunningSteps(t *testing.T) {
task := &actions_model.ActionTask{
Status: actions_model.StatusCancelling,
Steps: []*actions_model.ActionTaskStep{
{Name: "Run step-name", Index: 0, Status: actions_model.StatusRunning, LogLength: 1},
},
}
viewJobSteps, _, err := convertToViewModel(t.Context(), translation.MockLocale{}, nil, task)
require.NoError(t, err)
expectedViewJobs := []*ViewJobStep{
{
Summary: "Set up job",
Duration: "0s",
Status: "success",
},
{
Summary: "Run step-name",
Duration: "0s",
Status: "cancelling",
},
{
Summary: "Complete job",
Duration: "0s",
Status: "pending",
},
}
assert.Equal(t, expectedViewJobs, viewJobSteps)
}
func TestPendingNeeds(t *testing.T) {
+46 -302
View File
@@ -8,6 +8,7 @@ import (
issues_model "gitea.dev/models/issues"
"gitea.dev/modules/references"
"gitea.dev/modules/timeutil"
"github.com/stretchr/testify/assert"
)
@@ -36,6 +37,20 @@ func TestCombineXRefComments(t *testing.T) {
}
func TestCombineLabelComments(t *testing.T) {
labelComment := func(posterID int64, content, labelName string, createdUnix timeutil.TimeStamp, addedLabels, removedLabels []*issues_model.Label) *issues_model.Comment {
return &issues_model.Comment{
Type: issues_model.CommentTypeLabel,
PosterID: posterID,
Content: content,
Label: &issues_model.Label{Name: labelName},
CreatedUnix: createdUnix,
AddedLabels: addedLabels,
RemovedLabels: removedLabels,
}
}
comment := func(posterID int64, content string) *issues_model.Comment {
return &issues_model.Comment{Type: issues_model.CommentTypeComment, PosterID: posterID, Content: content, CreatedUnix: 0}
}
kases := []struct {
name string
beforeCombined []*issues_model.Comment
@@ -44,178 +59,39 @@ func TestCombineLabelComments(t *testing.T) {
{
name: "kase 1",
beforeCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeComment,
PosterID: 1,
Content: "test",
CreatedUnix: 0,
},
labelComment(1, "1", "kind/bug", 0, nil, nil),
labelComment(1, "", "kind/bug", 0, nil, nil),
comment(1, "test"),
},
afterCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
CreatedUnix: 0,
AddedLabels: []*issues_model.Label{},
Label: &issues_model.Label{
Name: "kind/bug",
},
},
{
Type: issues_model.CommentTypeComment,
PosterID: 1,
Content: "test",
CreatedUnix: 0,
},
labelComment(1, "1", "kind/bug", 0, []*issues_model.Label{}, nil),
comment(1, "test"),
},
},
{
name: "kase 2",
beforeCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 70,
},
{
Type: issues_model.CommentTypeComment,
PosterID: 1,
Content: "test",
CreatedUnix: 0,
},
labelComment(1, "1", "kind/bug", 0, nil, nil),
labelComment(1, "", "kind/bug", 70, nil, nil),
comment(1, "test"),
},
afterCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
CreatedUnix: 0,
AddedLabels: []*issues_model.Label{
{
Name: "kind/bug",
},
},
Label: &issues_model.Label{
Name: "kind/bug",
},
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "",
CreatedUnix: 70,
RemovedLabels: []*issues_model.Label{
{
Name: "kind/bug",
},
},
Label: &issues_model.Label{
Name: "kind/bug",
},
},
{
Type: issues_model.CommentTypeComment,
PosterID: 1,
Content: "test",
CreatedUnix: 0,
},
labelComment(1, "1", "kind/bug", 0, []*issues_model.Label{{Name: "kind/bug"}}, nil),
labelComment(1, "", "kind/bug", 70, nil, []*issues_model.Label{{Name: "kind/bug"}}),
comment(1, "test"),
},
},
{
name: "kase 3",
beforeCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 2,
Content: "",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeComment,
PosterID: 1,
Content: "test",
CreatedUnix: 0,
},
labelComment(1, "1", "kind/bug", 0, nil, nil),
labelComment(2, "", "kind/bug", 0, nil, nil),
comment(1, "test"),
},
afterCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
CreatedUnix: 0,
AddedLabels: []*issues_model.Label{
{
Name: "kind/bug",
},
},
Label: &issues_model.Label{
Name: "kind/bug",
},
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 2,
Content: "",
CreatedUnix: 0,
RemovedLabels: []*issues_model.Label{
{
Name: "kind/bug",
},
},
Label: &issues_model.Label{
Name: "kind/bug",
},
},
{
Type: issues_model.CommentTypeComment,
PosterID: 1,
Content: "test",
CreatedUnix: 0,
},
labelComment(1, "1", "kind/bug", 0, []*issues_model.Label{{Name: "kind/bug"}}, nil),
labelComment(2, "", "kind/bug", 0, nil, []*issues_model.Label{{Name: "kind/bug"}}),
comment(1, "test"),
},
},
{
@@ -234,168 +110,36 @@ func TestCombineLabelComments(t *testing.T) {
{
name: "kase 4",
beforeCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "kind/backport",
},
CreatedUnix: 10,
},
labelComment(1, "1", "kind/bug", 0, nil, nil),
labelComment(1, "1", "kind/backport", 10, nil, nil),
},
afterCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
CreatedUnix: 10,
AddedLabels: []*issues_model.Label{
{
Name: "kind/bug",
},
{
Name: "kind/backport",
},
},
Label: &issues_model.Label{
Name: "kind/bug",
},
},
labelComment(1, "1", "kind/bug", 10, []*issues_model.Label{{Name: "kind/bug"}, {Name: "kind/backport"}}, nil),
},
},
{
name: "kase 5",
beforeCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeComment,
PosterID: 2,
Content: "testtest",
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
labelComment(1, "1", "kind/bug", 0, nil, nil),
comment(2, "testtest"),
labelComment(1, "", "kind/bug", 0, nil, nil),
},
afterCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "kind/bug",
},
AddedLabels: []*issues_model.Label{
{
Name: "kind/bug",
},
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeComment,
PosterID: 2,
Content: "testtest",
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "",
RemovedLabels: []*issues_model.Label{
{
Name: "kind/bug",
},
},
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
labelComment(1, "1", "kind/bug", 0, []*issues_model.Label{{Name: "kind/bug"}}, nil),
comment(2, "testtest"),
labelComment(1, "", "kind/bug", 0, nil, []*issues_model.Label{{Name: "kind/bug"}}),
},
},
{
name: "kase 6",
beforeCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "reviewed/confirmed",
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "",
Label: &issues_model.Label{
Name: "kind/bug",
},
CreatedUnix: 0,
},
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "kind/feature",
},
CreatedUnix: 0,
},
labelComment(1, "1", "kind/bug", 0, nil, nil),
labelComment(1, "1", "reviewed/confirmed", 0, nil, nil),
labelComment(1, "", "kind/bug", 0, nil, nil),
labelComment(1, "1", "kind/feature", 0, nil, nil),
},
afterCombined: []*issues_model.Comment{
{
Type: issues_model.CommentTypeLabel,
PosterID: 1,
Content: "1",
Label: &issues_model.Label{
Name: "kind/bug",
},
AddedLabels: []*issues_model.Label{
{
Name: "reviewed/confirmed",
},
{
Name: "kind/feature",
},
},
CreatedUnix: 0,
},
labelComment(1, "1", "kind/bug", 0, []*issues_model.Label{{Name: "reviewed/confirmed"}, {Name: "kind/feature"}}, nil),
},
},
{
+14 -24
View File
@@ -31,29 +31,19 @@ func TestDiffViewStyle(t *testing.T) {
})
t.Run("SignedInUser", func(t *testing.T) {
ctx, _ := contexttest.MockContext(t, "/any")
contexttest.LoadUser(t, ctx, 2)
SetDiffViewStyle(ctx)
assert.Equal(t, gitdiff.DiffStyleUnified, GetDiffViewStyle(ctx))
ctx, _ = contexttest.MockContext(t, "/any?style=split")
contexttest.LoadUser(t, ctx, 2)
SetDiffViewStyle(ctx)
assert.Equal(t, gitdiff.DiffStyleSplit, GetDiffViewStyle(ctx))
ctx, _ = contexttest.MockContext(t, "/any")
contexttest.LoadUser(t, ctx, 2)
SetDiffViewStyle(ctx)
assert.Equal(t, gitdiff.DiffStyleSplit, GetDiffViewStyle(ctx))
ctx, _ = contexttest.MockContext(t, "/any?style=unified")
contexttest.LoadUser(t, ctx, 2)
SetDiffViewStyle(ctx)
assert.Equal(t, gitdiff.DiffStyleUnified, GetDiffViewStyle(ctx))
ctx, _ = contexttest.MockContext(t, "/any")
contexttest.LoadUser(t, ctx, 2)
SetDiffViewStyle(ctx)
assert.Equal(t, gitdiff.DiffStyleUnified, GetDiffViewStyle(ctx))
for _, testCase := range []struct {
requestPath, expected string
}{
{"/any", gitdiff.DiffStyleUnified},
{"/any?style=split", gitdiff.DiffStyleSplit},
{"/any", gitdiff.DiffStyleSplit},
{"/any?style=unified", gitdiff.DiffStyleUnified},
{"/any", gitdiff.DiffStyleUnified},
} {
ctx, _ := contexttest.MockContext(t, testCase.requestPath)
contexttest.LoadUser(t, ctx, 2)
SetDiffViewStyle(ctx)
assert.Equal(t, testCase.expected, GetDiffViewStyle(ctx))
}
})
}
+25 -36
View File
@@ -53,40 +53,29 @@ func TestRenderConversation(t *testing.T) {
})
require.NotNil(t, preparedComment)
run("diff with outdated", func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) {
ctx.Data["ShowOutdatedComments"] = true
renderConversation(ctx, preparedComment, "diff")
assert.Contains(t, resp.Body.String(), `<div class="content comment-container"`)
})
run("diff without outdated", func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) {
ctx.Data["ShowOutdatedComments"] = false
renderConversation(ctx, preparedComment, "diff")
assert.Contains(t, resp.Body.String(), `conversation-not-existing`)
})
run("timeline with outdated", func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) {
ctx.Data["ShowOutdatedComments"] = true
renderConversation(ctx, preparedComment, "timeline")
assert.Contains(t, resp.Body.String(), `<div id="code-comments-`)
})
run("timeline is not affected by ShowOutdatedComments=false", func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) {
ctx.Data["ShowOutdatedComments"] = false
renderConversation(ctx, preparedComment, "timeline")
assert.Contains(t, resp.Body.String(), `<div id="code-comments-`)
})
run("diff non-existing review", func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) {
err := db.TruncateBeans(t.Context(), &issues_model.Review{})
assert.NoError(t, err)
ctx.Data["ShowOutdatedComments"] = true
renderConversation(ctx, preparedComment, "diff")
assert.Equal(t, http.StatusOK, resp.Code)
assert.NotContains(t, resp.Body.String(), common.PageInternalServerErrorMark)
})
run("timeline non-existing review", func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) {
err := db.TruncateBeans(t.Context(), &issues_model.Review{})
assert.NoError(t, err)
ctx.Data["ShowOutdatedComments"] = true
renderConversation(ctx, preparedComment, "timeline")
assert.Equal(t, http.StatusOK, resp.Code)
assert.NotContains(t, resp.Body.String(), common.PageInternalServerErrorMark)
})
for _, testCase := range []struct {
name, origin, expected string
showOutdated bool
}{
{"diff with outdated", "diff", `<div class="content comment-container"`, true},
{"diff without outdated", "diff", `conversation-not-existing`, false},
{"timeline with outdated", "timeline", `<div id="code-comments-`, true},
{"timeline is not affected by ShowOutdatedComments=false", "timeline", `<div id="code-comments-`, false},
} {
run(testCase.name, func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) {
ctx.Data["ShowOutdatedComments"] = testCase.showOutdated
renderConversation(ctx, preparedComment, testCase.origin)
assert.Contains(t, resp.Body.String(), testCase.expected)
})
}
for _, origin := range []string{"diff", "timeline"} {
run(origin+" non-existing review", func(t *testing.T, ctx *context.Context, resp *httptest.ResponseRecorder) {
err := db.TruncateBeans(t.Context(), &issues_model.Review{})
assert.NoError(t, err)
ctx.Data["ShowOutdatedComments"] = true
renderConversation(ctx, preparedComment, origin)
assert.Equal(t, http.StatusOK, resp.Code)
assert.NotContains(t, resp.Body.String(), common.PageInternalServerErrorMark)
})
}
}
+36 -115
View File
@@ -52,124 +52,45 @@ func TestAddDeployKey(t *testing.T) {
}
func TestCollaborationPost(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
contexttest.LoadUser(t, ctx, 2)
contexttest.LoadUser(t, ctx, 4)
contexttest.LoadRepo(t, ctx, 1)
for _, c := range []struct {
name, collaborator string
userID int64
}{
{"AddCollaboratorTwice", "user4", 4},
{"InactiveUser", "user9", 9},
{"NonExistentUser", "user34", 0},
} {
t.Run(c.name, func(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
contexttest.LoadUser(t, ctx, 2)
if c.userID != 0 {
contexttest.LoadUser(t, ctx, c.userID)
}
contexttest.LoadRepo(t, ctx, 1)
ctx.Req.Form.Set("collaborator", c.collaborator)
ctx.Req.Form.Set("collaborator", "user4")
owner := &user_model.User{LowerName: "user2", Type: user_model.UserTypeIndividual}
ctx.Repo = &context.Repository{Owner: owner}
if c.userID == 4 {
ctx.Repo.Repository = &repo_model.Repository{ID: 2, Owner: owner}
}
u := &user_model.User{
LowerName: "user2",
Type: user_model.UserTypeIndividual,
CollaborationPost(ctx)
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
if c.userID == 4 {
exists, err := repo_model.IsCollaborator(ctx, ctx.Repo.Repository.ID, 4)
assert.NoError(t, err)
assert.True(t, exists)
// Try adding the same collaborator again
CollaborationPost(ctx)
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
}
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
})
}
re := &repo_model.Repository{
ID: 2,
Owner: u,
}
repo := &context.Repository{
Owner: u,
Repository: re,
}
ctx.Repo = repo
CollaborationPost(ctx)
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
exists, err := repo_model.IsCollaborator(ctx, re.ID, 4)
assert.NoError(t, err)
assert.True(t, exists)
}
func TestCollaborationPost_InactiveUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
contexttest.LoadUser(t, ctx, 2)
contexttest.LoadUser(t, ctx, 9)
contexttest.LoadRepo(t, ctx, 1)
ctx.Req.Form.Set("collaborator", "user9")
repo := &context.Repository{
Owner: &user_model.User{
LowerName: "user2",
},
}
ctx.Repo = repo
CollaborationPost(ctx)
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
}
func TestCollaborationPost_AddCollaboratorTwice(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
contexttest.LoadUser(t, ctx, 2)
contexttest.LoadUser(t, ctx, 4)
contexttest.LoadRepo(t, ctx, 1)
ctx.Req.Form.Set("collaborator", "user4")
u := &user_model.User{
LowerName: "user2",
Type: user_model.UserTypeIndividual,
}
re := &repo_model.Repository{
ID: 2,
Owner: u,
}
repo := &context.Repository{
Owner: u,
Repository: re,
}
ctx.Repo = repo
CollaborationPost(ctx)
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
exists, err := repo_model.IsCollaborator(ctx, re.ID, 4)
assert.NoError(t, err)
assert.True(t, exists)
// Try adding the same collaborator again
CollaborationPost(ctx)
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
}
func TestCollaborationPost_NonExistentUser(t *testing.T) {
assert.NoError(t, unittest.PrepareTestDatabase())
ctx, _ := contexttest.MockContext(t, "user2/repo1/issues/labels")
contexttest.LoadUser(t, ctx, 2)
contexttest.LoadRepo(t, ctx, 1)
ctx.Req.Form.Set("collaborator", "user34")
repo := &context.Repository{
Owner: &user_model.User{
LowerName: "user2",
},
}
ctx.Repo = repo
CollaborationPost(ctx)
assert.Equal(t, http.StatusSeeOther, ctx.Resp.WrittenStatus())
assert.NotEmpty(t, ctx.Flash.ErrorMsg)
}
func TestAddTeamPost(t *testing.T) {
+14 -17
View File
@@ -34,6 +34,7 @@ func TestMain(m *testing.M) {
// resolves projects owned by the scope its route assigned, so an ID belonging to anyone
// else reads as not found rather than leaking across owners.
func TestFindColumn(t *testing.T) {
unittest.PrepareTestEnv(t)
for _, tc := range []struct {
name string
projectID string
@@ -48,7 +49,6 @@ func TestFindColumn(t *testing.T) {
{"owner board cannot reach another owner's project", "4", "4", 1, false, false},
} {
t.Run(tc.name, func(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx, _ := contexttest.MockContext(t, "user2/-/projects")
contexttest.LoadUser(t, ctx, tc.doerID)
if tc.repoScoped {
@@ -73,31 +73,28 @@ func TestFindColumn(t *testing.T) {
}
func TestMoveIssuesNeedsIssueRead(t *testing.T) {
stripTeamIssues := func(t *testing.T) {
_, err := db.Exec(t.Context(), "UPDATE team SET authorize = ? WHERE id = ?", perm.AccessModeNone, 2)
require.NoError(t, err)
_, err = db.DeleteByBean(t.Context(), &organization.TeamUnit{TeamID: 2, Type: unit.TypeIssues})
require.NoError(t, err)
}
archiveRepo3 := func(t *testing.T) {
require.NoError(t, repo_model.UpdateRepositoryColsNoAutoTime(t.Context(), &repo_model.Repository{ID: 3, IsArchived: true}, "is_archived"))
}
for _, tc := range []struct {
name string
doerID int64
repoBoard bool
prepare func(*testing.T)
archived bool
status int
}{
{"OwnerBoardReader", 2, false, nil, http.StatusOK},
{"OwnerBoardWithoutIssueAccess", 15, false, nil, http.StatusNotFound},
{"OwnerBoardArchivedRepo", 2, false, archiveRepo3, http.StatusLocked},
{"RepoBoardProjectsWriterWithoutIssueRead", 4, true, stripTeamIssues, http.StatusNotFound},
{"OwnerBoardReader", 2, false, false, http.StatusOK},
{"OwnerBoardWithoutIssueAccess", 15, false, false, http.StatusNotFound},
{"OwnerBoardArchivedRepo", 2, false, true, http.StatusLocked},
{"RepoBoardProjectsWriterWithoutIssueRead", 4, true, false, http.StatusNotFound},
} {
t.Run(tc.name, func(t *testing.T) {
unittest.PrepareTestEnv(t)
if tc.prepare != nil {
tc.prepare(t)
if tc.repoBoard {
_, err := db.Exec(t.Context(), "UPDATE team SET authorize = ? WHERE id = ?", perm.AccessModeNone, 2)
require.NoError(t, err)
_, err = db.DeleteByBean(t.Context(), &organization.TeamUnit{TeamID: 2, Type: unit.TypeIssues})
require.NoError(t, err)
}
if tc.archived {
require.NoError(t, repo_model.UpdateRepositoryColsNoAutoTime(t.Context(), &repo_model.Repository{ID: 3, IsArchived: true}, "is_archived"))
}
ctx, _ := contexttest.MockContext(t, "POST /org3/-/projects")
contexttest.LoadUser(t, ctx, tc.doerID)
+26 -42
View File
@@ -80,52 +80,36 @@ func TestMilestones(t *testing.T) {
setting.UI.IssuePagingNum = 1
assert.NoError(t, unittest.LoadFixtures())
ctx, _ := contexttest.MockContext(t, "milestones")
contexttest.LoadUser(t, ctx, 2)
ctx.SetPathParam("sort", "issues")
ctx.Req.Form.Set("state", "closed")
ctx.Req.Form.Set("sort", "furthestduedate")
Milestones(ctx)
assert.Equal(t, http.StatusOK, ctx.Resp.WrittenStatus())
assert.EqualValues(t, map[int64]int64{1: 1}, ctx.Data["Counts"])
assert.EqualValues(t, true, ctx.Data["IsShowClosed"])
assert.EqualValues(t, "furthestduedate", ctx.Data["SortType"])
assert.EqualValues(t, 1, ctx.Data["Total"])
assert.Len(t, ctx.Data["Milestones"], 1)
assert.Len(t, ctx.Data["Repos"], 2) // both repo 42 and 1 have milestones and both are owned by user 2
}
func TestMilestonesForSpecificRepo(t *testing.T) {
setting.UI.IssuePagingNum = 1
assert.NoError(t, unittest.LoadFixtures())
ctx, _ := contexttest.MockContext(t, "milestones")
contexttest.LoadUser(t, ctx, 2)
ctx.SetPathParam("sort", "issues")
ctx.SetPathParam("repo", "1")
ctx.Req.Form.Set("state", "closed")
ctx.Req.Form.Set("sort", "furthestduedate")
Milestones(ctx)
assert.Equal(t, http.StatusOK, ctx.Resp.WrittenStatus())
assert.EqualValues(t, map[int64]int64{1: 1}, ctx.Data["Counts"])
assert.EqualValues(t, true, ctx.Data["IsShowClosed"])
assert.EqualValues(t, "furthestduedate", ctx.Data["SortType"])
assert.EqualValues(t, 1, ctx.Data["Total"])
assert.Len(t, ctx.Data["Milestones"], 1)
assert.Len(t, ctx.Data["Repos"], 2) // both repo 42 and 1 have milestones and both are owned by user 2
for _, repoID := range []string{"", "1"} {
t.Run("repo="+repoID, func(t *testing.T) {
ctx, _ := contexttest.MockContext(t, "milestones")
contexttest.LoadUser(t, ctx, 2)
ctx.SetPathParam("sort", "issues")
if repoID != "" {
ctx.SetPathParam("repo", repoID)
}
ctx.Req.Form.Set("state", "closed")
ctx.Req.Form.Set("sort", "furthestduedate")
Milestones(ctx)
assert.Equal(t, http.StatusOK, ctx.Resp.WrittenStatus())
assert.EqualValues(t, map[int64]int64{1: 1}, ctx.Data["Counts"])
assert.EqualValues(t, true, ctx.Data["IsShowClosed"])
assert.EqualValues(t, "furthestduedate", ctx.Data["SortType"])
assert.EqualValues(t, 1, ctx.Data["Total"])
assert.Len(t, ctx.Data["Milestones"], 1)
assert.Len(t, ctx.Data["Repos"], 2) // both repo 42 and 1 have milestones and both are owned by user 2
})
}
}
func TestDashboardPagination(t *testing.T) {
ctx, _ := contexttest.MockContext(t, "/", contexttest.MockContextOption{Render: templates.PageRenderer()})
page := context.NewPagerBuilder(ctx).TotalCount(10).PerPageLimit(3).CurPage(1).NavPageNum(3).Build()
setting.AppSubURL = "/SubPath"
out, err := ctx.RenderToHTML("base/paginate", map[string]any{"Link": setting.AppSubURL, "Page": page})
assert.NoError(t, err)
assert.Contains(t, out, `<a class=" item navigation" href="/SubPath/?page=2">`)
setting.AppSubURL = ""
out, err = ctx.RenderToHTML("base/paginate", map[string]any{"Link": setting.AppSubURL, "Page": page})
assert.NoError(t, err)
assert.Contains(t, out, `<a class=" item navigation" href="/?page=2">`)
for _, subURL := range []string{"/SubPath", ""} {
setting.AppSubURL = subURL
out, err := ctx.RenderToHTML("base/paginate", map[string]any{"Link": setting.AppSubURL, "Page": page})
assert.NoError(t, err)
assert.Contains(t, out, `<a class=" item navigation" href="`+subURL+`/?page=2">`)
}
}
@@ -17,6 +17,7 @@ import (
"gitea.dev/modules/setting"
"gitea.dev/modules/test"
"gitea.dev/modules/web"
"gitea.dev/services/context"
"gitea.dev/services/contexttest"
"gitea.dev/services/forms"
@@ -101,18 +102,12 @@ func TestOpenIDAssociation(t *testing.T) {
assert.Equal(t, "Nonce already used", ctx.Flash.ErrorMsg)
}
func TestDeleteOpenIDReturnsNotFoundForOtherUsersAddress(t *testing.T) {
func TestOpenIDReturnsNotFoundForOtherUsersAddress(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx, _ := contexttest.MockContext(t, "POST /user/settings/security?id=1")
contexttest.LoadUser(t, ctx, 2)
DeleteOpenID(ctx)
assert.Equal(t, http.StatusNotFound, ctx.Resp.WrittenStatus())
}
func TestToggleOpenIDVisibilityReturnsNotFoundForOtherUsersAddress(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx, _ := contexttest.MockContext(t, "POST /user/settings/security?id=1")
contexttest.LoadUser(t, ctx, 2)
ToggleOpenIDVisibility(ctx)
assert.Equal(t, http.StatusNotFound, ctx.Resp.WrittenStatus())
for _, handler := range []func(*context.Context){DeleteOpenID, ToggleOpenIDVisibility} {
ctx, _ := contexttest.MockContext(t, "POST /user/settings/security?id=1")
contexttest.LoadUser(t, ctx, 2)
handler(ctx)
assert.Equal(t, http.StatusNotFound, ctx.Resp.WrittenStatus())
}
}