From befa7445d254cc88662015222c85ccd4c96b9a10 Mon Sep 17 00:00:00 2001 From: Ethan Koenig Date: Fri, 15 Dec 2017 13:11:02 -0800 Subject: [PATCH] Unit tests for routers/repo/issue_label (#3198) --- integrations/integration_test.go | 6 -- integrations/issue_test.go | 5 +- integrations/links_test.go | 3 +- integrations/pull_merge_test.go | 6 +- integrations/release_test.go | 4 +- integrations/repo_activity_test.go | 4 +- integrations/repo_branch_test.go | 4 +- integrations/timetracking_test.go | 6 +- integrations/user_test.go | 3 +- models/unit_tests.go | 19 +++- modules/test/context_tests.go | 23 ++-- modules/test/utils.go | 14 +++ routers/repo/issue.go | 2 +- routers/repo/issue_label.go | 10 +- routers/repo/issue_label_test.go | 164 +++++++++++++++++++++++++++++ 15 files changed, 231 insertions(+), 42 deletions(-) create mode 100644 modules/test/utils.go create mode 100644 routers/repo/issue_label_test.go diff --git a/integrations/integration_test.go b/integrations/integration_test.go index d8e97395f..f3dc98219 100644 --- a/integrations/integration_test.go +++ b/integrations/integration_test.go @@ -303,9 +303,3 @@ func GetCSRF(t testing.TB, session *TestSession, urlStr string) string { doc := NewHTMLParser(t, resp.Body) return doc.GetCSRF() } - -func RedirectURL(t testing.TB, resp *httptest.ResponseRecorder) string { - urlSlice := resp.HeaderMap["Location"] - assert.NotEmpty(t, urlSlice, "No redirect URL founds") - return urlSlice[0] -} diff --git a/integrations/issue_test.go b/integrations/issue_test.go index d6fd712c9..10084000d 100644 --- a/integrations/issue_test.go +++ b/integrations/issue_test.go @@ -13,6 +13,7 @@ import ( "code.gitea.io/gitea/models" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/test" "github.com/PuerkitoBio/goquery" "github.com/stretchr/testify/assert" @@ -122,7 +123,7 @@ func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content }) resp = session.MakeRequest(t, req, http.StatusFound) - issueURL := RedirectURL(t, resp) + issueURL := test.RedirectURL(resp) req = NewRequest(t, "GET", issueURL) resp = session.MakeRequest(t, req, http.StatusOK) @@ -153,7 +154,7 @@ func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content, }) resp = session.MakeRequest(t, req, http.StatusFound) - req = NewRequest(t, "GET", RedirectURL(t, resp)) + req = NewRequest(t, "GET", test.RedirectURL(resp)) resp = session.MakeRequest(t, req, http.StatusOK) htmlDoc = NewHTMLParser(t, resp.Body) diff --git a/integrations/links_test.go b/integrations/links_test.go index bc87ca707..b0abbd708 100644 --- a/integrations/links_test.go +++ b/integrations/links_test.go @@ -11,6 +11,7 @@ import ( "testing" "code.gitea.io/gitea/modules/setting" + "code.gitea.io/gitea/modules/test" api "code.gitea.io/sdk/gitea" "github.com/stretchr/testify/assert" @@ -54,7 +55,7 @@ func TestRedirectsNoLogin(t *testing.T) { for link, redirectLink := range redirects { req := NewRequest(t, "GET", link) resp := MakeRequest(t, req, http.StatusFound) - assert.EqualValues(t, path.Join(setting.AppSubURL, redirectLink), RedirectURL(t, resp)) + assert.EqualValues(t, path.Join(setting.AppSubURL, redirectLink), test.RedirectURL(resp)) } } diff --git a/integrations/pull_merge_test.go b/integrations/pull_merge_test.go index d6413be54..65ccc93f9 100644 --- a/integrations/pull_merge_test.go +++ b/integrations/pull_merge_test.go @@ -11,6 +11,8 @@ import ( "strings" "testing" + "code.gitea.io/gitea/modules/test" + "github.com/stretchr/testify/assert" ) @@ -54,7 +56,7 @@ func TestPullMerge(t *testing.T) { resp := testPullCreate(t, session, "user1", "repo1", "master") - elem := strings.Split(RedirectURL(t, resp), "/") + elem := strings.Split(test.RedirectURL(resp), "/") assert.EqualValues(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4]) } @@ -67,7 +69,7 @@ func TestPullCleanUpAfterMerge(t *testing.T) { resp := testPullCreate(t, session, "user1", "repo1", "feature/test") - elem := strings.Split(RedirectURL(t, resp), "/") + elem := strings.Split(test.RedirectURL(resp), "/") assert.EqualValues(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4]) diff --git a/integrations/release_test.go b/integrations/release_test.go index bce1c88fd..461d3306d 100644 --- a/integrations/release_test.go +++ b/integrations/release_test.go @@ -9,6 +9,8 @@ import ( "net/http" "testing" + "code.gitea.io/gitea/modules/test" + "github.com/Unknwon/i18n" "github.com/stretchr/testify/assert" ) @@ -38,7 +40,7 @@ func createNewRelease(t *testing.T, session *TestSession, repoURL, tag, title st resp = session.MakeRequest(t, req, http.StatusFound) - RedirectURL(t, resp) // check that redirect URL exists + test.RedirectURL(resp) // check that redirect URL exists } func checkLatestReleaseAndCount(t *testing.T, session *TestSession, repoURL, version, label string, count int) { diff --git a/integrations/repo_activity_test.go b/integrations/repo_activity_test.go index 49d07e7c4..d3d2de4a2 100644 --- a/integrations/repo_activity_test.go +++ b/integrations/repo_activity_test.go @@ -9,6 +9,8 @@ import ( "strings" "testing" + "code.gitea.io/gitea/modules/test" + "github.com/stretchr/testify/assert" ) @@ -20,7 +22,7 @@ func TestRepoActivity(t *testing.T) { testRepoFork(t, session, "user2", "repo1", "user1", "repo1") testEditFile(t, session, "user1", "repo1", "master", "README.md", "Hello, World (Edited)\n") resp := testPullCreate(t, session, "user1", "repo1", "master") - elem := strings.Split(RedirectURL(t, resp), "/") + elem := strings.Split(test.RedirectURL(resp), "/") assert.EqualValues(t, "pulls", elem[3]) testPullMerge(t, session, elem[1], elem[2], elem[4]) diff --git a/integrations/repo_branch_test.go b/integrations/repo_branch_test.go index df7f97bd2..c20fd6192 100644 --- a/integrations/repo_branch_test.go +++ b/integrations/repo_branch_test.go @@ -10,6 +10,8 @@ import ( "strings" "testing" + "code.gitea.io/gitea/modules/test" + "github.com/Unknwon/i18n" "github.com/stretchr/testify/assert" ) @@ -29,7 +31,7 @@ func testCreateBranch(t *testing.T, session *TestSession, user, repo, oldRefSubU if expectedStatus != http.StatusFound { return "" } - return RedirectURL(t, resp) + return test.RedirectURL(resp) } func TestCreateBranch(t *testing.T) { diff --git a/integrations/timetracking_test.go b/integrations/timetracking_test.go index 534bb4d61..890f12b30 100644 --- a/integrations/timetracking_test.go +++ b/integrations/timetracking_test.go @@ -10,6 +10,8 @@ import ( "testing" "time" + "code.gitea.io/gitea/modules/test" + "github.com/stretchr/testify/assert" ) @@ -47,7 +49,7 @@ func testViewTimetrackingControls(t *testing.T, session *TestSession, user, repo if canTrackTime { resp = session.MakeRequest(t, req, http.StatusSeeOther) - req = NewRequest(t, "GET", RedirectURL(t, resp)) + req = NewRequest(t, "GET", test.RedirectURL(resp)) resp = session.MakeRequest(t, req, http.StatusOK) htmlDoc = NewHTMLParser(t, resp.Body) @@ -65,7 +67,7 @@ func testViewTimetrackingControls(t *testing.T, session *TestSession, user, repo }) resp = session.MakeRequest(t, req, http.StatusSeeOther) - req = NewRequest(t, "GET", RedirectURL(t, resp)) + req = NewRequest(t, "GET", test.RedirectURL(resp)) resp = session.MakeRequest(t, req, http.StatusOK) htmlDoc = NewHTMLParser(t, resp.Body) diff --git a/integrations/user_test.go b/integrations/user_test.go index ddb46da31..da39234c3 100644 --- a/integrations/user_test.go +++ b/integrations/user_test.go @@ -9,6 +9,7 @@ import ( "testing" "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/test" "github.com/Unknwon/i18n" "github.com/stretchr/testify/assert" @@ -86,7 +87,7 @@ func TestRenameReservedUsername(t *testing.T) { }) resp := session.MakeRequest(t, req, http.StatusFound) - req = NewRequest(t, "GET", RedirectURL(t, resp)) + req = NewRequest(t, "GET", test.RedirectURL(resp)) resp = session.MakeRequest(t, req, http.StatusOK) htmlDoc := NewHTMLParser(t, resp.Body) assert.Contains(t, diff --git a/models/unit_tests.go b/models/unit_tests.go index ff7a87da3..25808a948 100644 --- a/models/unit_tests.go +++ b/models/unit_tests.go @@ -17,6 +17,7 @@ import ( "github.com/go-xorm/xorm" "github.com/stretchr/testify/assert" "gopkg.in/testfixtures.v2" + "net/url" ) // NonexistentID an ID that will never exist @@ -28,9 +29,10 @@ var giteaRoot string // MainTest a reusable TestMain(..) function for unit tests that need to use a // test database. Creates the test database, and sets necessary settings. func MainTest(m *testing.M, pathToGiteaRoot string) { + var err error giteaRoot = pathToGiteaRoot fixturesDir := filepath.Join(pathToGiteaRoot, "models", "fixtures") - if err := createTestEngine(fixturesDir); err != nil { + if err = createTestEngine(fixturesDir); err != nil { fmt.Fprintf(os.Stderr, "Error creating test engine: %v\n", err) os.Exit(1) } @@ -41,6 +43,13 @@ func MainTest(m *testing.M, pathToGiteaRoot string) { setting.SSH.Domain = "try.gitea.io" setting.RepoRootPath = filepath.Join(os.TempDir(), "repos") setting.AppDataPath = filepath.Join(os.TempDir(), "appdata") + setting.AppWorkPath = pathToGiteaRoot + setting.StaticRootPath = pathToGiteaRoot + setting.GravatarSourceURL, err = url.Parse("https://secure.gravatar.com/avatar/") + if err != nil { + fmt.Fprintf(os.Stderr, "Error url.Parse: %v\n", err) + os.Exit(1) + } os.Exit(m.Run()) } @@ -140,6 +149,14 @@ func AssertNotExistsBean(t *testing.T, bean interface{}, conditions ...interface assert.False(t, exists) } +// AssertExistsIf asserts that a bean exists or does not exist, depending on +// what is expected. +func AssertExistsIf(t *testing.T, expected bool, bean interface{}, conditions ...interface{}) { + exists, err := loadBeanIfExists(bean, conditions...) + assert.NoError(t, err) + assert.Equal(t, expected, exists) +} + // AssertSuccessfulInsert assert that beans is successfully inserted func AssertSuccessfulInsert(t *testing.T, beans ...interface{}) { _, err := x.Insert(beans...) diff --git a/modules/test/context_tests.go b/modules/test/context_tests.go index 11f3d83b8..bd5ea3fd3 100644 --- a/modules/test/context_tests.go +++ b/modules/test/context_tests.go @@ -16,6 +16,7 @@ import ( "github.com/go-macaron/session" "github.com/stretchr/testify/assert" "gopkg.in/macaron.v1" + "net/http/httptest" ) // MockContext mock context for unit tests @@ -44,6 +45,7 @@ func MockContext(t *testing.T, path string) *context.Context { func LoadRepo(t *testing.T, ctx *context.Context, repoID int64) { ctx.Repo = &context.Repository{} ctx.Repo.Repository = models.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.Repository) + ctx.Repo.RepoLink = ctx.Repo.Repository.Link() } // LoadUser load a user into a test context. @@ -71,32 +73,21 @@ func (l mockLocale) Tr(s string, _ ...interface{}) string { } type mockResponseWriter struct { - status int - size int -} - -func (rw *mockResponseWriter) Header() http.Header { - return map[string][]string{} + httptest.ResponseRecorder + size int } func (rw *mockResponseWriter) Write(b []byte) (int, error) { rw.size += len(b) - return len(b), nil -} - -func (rw *mockResponseWriter) WriteHeader(status int) { - rw.status = status -} - -func (rw *mockResponseWriter) Flush() { + return rw.ResponseRecorder.Write(b) } func (rw *mockResponseWriter) Status() int { - return rw.status + return rw.ResponseRecorder.Code } func (rw *mockResponseWriter) Written() bool { - return rw.status > 0 + return rw.ResponseRecorder.Code > 0 } func (rw *mockResponseWriter) Size() int { diff --git a/modules/test/utils.go b/modules/test/utils.go new file mode 100644 index 000000000..ed1628ab4 --- /dev/null +++ b/modules/test/utils.go @@ -0,0 +1,14 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package test + +import ( + "net/http" +) + +// RedirectURL returns the redirect URL of a http response. +func RedirectURL(resp http.ResponseWriter) string { + return resp.Header().Get("Location") +} diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 7664d074e..ec8fda8f7 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -776,7 +776,7 @@ func getActionIssues(ctx *context.Context) []*models.Issue { return nil } if err = issue.LoadAttributes(); err != nil { - ctx.Handle(500, "LoadAttributes", nil) + ctx.Handle(500, "LoadAttributes", err) return nil } } diff --git a/routers/repo/issue_label.go b/routers/repo/issue_label.go index 9b4da4b50..f8a955ba6 100644 --- a/routers/repo/issue_label.go +++ b/routers/repo/issue_label.go @@ -155,18 +155,14 @@ func UpdateIssueLabel(ctx *context.Context) { } if action == "toggle" { - anyHaveLabel := false + // detach if any issues already have label, otherwise attach + action = "attach" for _, issue := range issues { if issue.HasLabel(label.ID) { - anyHaveLabel = true + action = "detach" break } } - if anyHaveLabel { - action = "detach" - } else { - action = "attach" - } } if action == "attach" { diff --git a/routers/repo/issue_label_test.go b/routers/repo/issue_label_test.go new file mode 100644 index 000000000..9052a65d2 --- /dev/null +++ b/routers/repo/issue_label_test.go @@ -0,0 +1,164 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package repo + +import ( + "net/http" + "strconv" + "testing" + + "code.gitea.io/gitea/models" + "code.gitea.io/gitea/modules/auth" + "code.gitea.io/gitea/modules/test" + + "github.com/stretchr/testify/assert" +) + +func int64SliceToCommaSeparated(a []int64) string { + s := "" + for i, n := range a { + if i > 0 { + s += "," + } + s += strconv.Itoa(int(n)) + } + return s +} + +func TestInitializeLabels(t *testing.T) { + models.PrepareTestEnv(t) + ctx := test.MockContext(t, "user2/repo1/labels/initialize") + test.LoadUser(t, ctx, 2) + test.LoadRepo(t, ctx, 2) + InitializeLabels(ctx, auth.InitializeLabelsForm{"Default"}) + assert.EqualValues(t, http.StatusFound, ctx.Resp.Status()) + models.AssertExistsAndLoadBean(t, &models.Label{ + RepoID: 2, + Name: "enhancement", + Color: "#84b6eb", + }) + assert.Equal(t, "/user2/repo2/labels", test.RedirectURL(ctx.Resp)) +} + +func TestRetrieveLabels(t *testing.T) { + models.PrepareTestEnv(t) + for _, testCase := range []struct { + RepoID int64 + Sort string + ExpectedLabelIDs []int64 + }{ + {1, "", []int64{1, 2}}, + {1, "leastissues", []int64{2, 1}}, + {2, "", []int64{}}, + } { + ctx := test.MockContext(t, "user/repo/issues") + test.LoadUser(t, ctx, 2) + test.LoadRepo(t, ctx, testCase.RepoID) + ctx.Req.Form.Set("sort", testCase.Sort) + RetrieveLabels(ctx) + assert.False(t, ctx.Written()) + labels, ok := ctx.Data["Labels"].([]*models.Label) + assert.True(t, ok) + if assert.Len(t, labels, len(testCase.ExpectedLabelIDs)) { + for i, label := range labels { + assert.EqualValues(t, testCase.ExpectedLabelIDs[i], label.ID) + } + } + } +} + +func TestNewLabel(t *testing.T) { + models.PrepareTestEnv(t) + ctx := test.MockContext(t, "user2/repo1/labels/edit") + test.LoadUser(t, ctx, 2) + test.LoadRepo(t, ctx, 1) + NewLabel(ctx, auth.CreateLabelForm{ + Title: "newlabel", + Color: "#abcdef", + }) + assert.EqualValues(t, http.StatusFound, ctx.Resp.Status()) + models.AssertExistsAndLoadBean(t, &models.Label{ + Name: "newlabel", + Color: "#abcdef", + }) + assert.Equal(t, "/user2/repo1/labels", test.RedirectURL(ctx.Resp)) +} + +func TestUpdateLabel(t *testing.T) { + models.PrepareTestEnv(t) + ctx := test.MockContext(t, "user2/repo1/labels/edit") + test.LoadUser(t, ctx, 2) + test.LoadRepo(t, ctx, 1) + UpdateLabel(ctx, auth.CreateLabelForm{ + ID: 2, + Title: "newnameforlabel", + Color: "#abcdef", + }) + assert.EqualValues(t, http.StatusFound, ctx.Resp.Status()) + models.AssertExistsAndLoadBean(t, &models.Label{ + ID: 2, + Name: "newnameforlabel", + Color: "#abcdef", + }) + assert.Equal(t, "/user2/repo1/labels", test.RedirectURL(ctx.Resp)) +} + +func TestDeleteLabel(t *testing.T) { + models.PrepareTestEnv(t) + ctx := test.MockContext(t, "user2/repo1/labels/delete") + test.LoadUser(t, ctx, 2) + test.LoadRepo(t, ctx, 1) + ctx.Req.Form.Set("id", "2") + DeleteLabel(ctx) + assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) + models.AssertNotExistsBean(t, &models.Label{ID: 2}) + models.AssertNotExistsBean(t, &models.IssueLabel{LabelID: 2}) + assert.Equal(t, ctx.Tr("repo.issues.label_deletion_success"), ctx.Flash.SuccessMsg) +} + +func TestUpdateIssueLabel_Clear(t *testing.T) { + models.PrepareTestEnv(t) + ctx := test.MockContext(t, "user2/repo1/issues/labels") + test.LoadUser(t, ctx, 2) + test.LoadRepo(t, ctx, 1) + ctx.Req.Form.Set("issue_ids", "1,3") + ctx.Req.Form.Set("action", "clear") + UpdateIssueLabel(ctx) + assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) + models.AssertNotExistsBean(t, &models.IssueLabel{IssueID: 1}) + models.AssertNotExistsBean(t, &models.IssueLabel{IssueID: 3}) + models.CheckConsistencyFor(t, &models.Label{}) +} + +func TestUpdateIssueLabel_Toggle(t *testing.T) { + for _, testCase := range []struct { + Action string + IssueIDs []int64 + LabelID int64 + ExpectedAdd bool // whether we expect the label to be added to the issues + }{ + {"attach", []int64{1, 3}, 1, true}, + {"detach", []int64{1, 3}, 1, false}, + {"toggle", []int64{1, 3}, 1, false}, + {"toggle", []int64{1, 2}, 2, true}, + } { + models.PrepareTestEnv(t) + ctx := test.MockContext(t, "user2/repo1/issues/labels") + test.LoadUser(t, ctx, 2) + test.LoadRepo(t, ctx, 1) + ctx.Req.Form.Set("issue_ids", int64SliceToCommaSeparated(testCase.IssueIDs)) + ctx.Req.Form.Set("action", testCase.Action) + ctx.Req.Form.Set("id", strconv.Itoa(int(testCase.LabelID))) + UpdateIssueLabel(ctx) + assert.EqualValues(t, http.StatusOK, ctx.Resp.Status()) + for _, issueID := range testCase.IssueIDs { + models.AssertExistsIf(t, testCase.ExpectedAdd, &models.IssueLabel{ + IssueID: issueID, + LabelID: testCase.LabelID, + }) + } + models.CheckConsistencyFor(t, &models.Label{}) + } +}