Unit tests for routers/repo/issue_label (#3198)

This commit is contained in:
Ethan Koenig 2017-12-15 13:11:02 -08:00 committed by Lauris BH
parent bde0409433
commit befa7445d2
15 changed files with 231 additions and 42 deletions

View file

@ -303,9 +303,3 @@ func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
doc := NewHTMLParser(t, resp.Body) doc := NewHTMLParser(t, resp.Body)
return doc.GetCSRF() 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]
}

View file

@ -13,6 +13,7 @@ import (
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
"github.com/PuerkitoBio/goquery" "github.com/PuerkitoBio/goquery"
"github.com/stretchr/testify/assert" "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) resp = session.MakeRequest(t, req, http.StatusFound)
issueURL := RedirectURL(t, resp) issueURL := test.RedirectURL(resp)
req = NewRequest(t, "GET", issueURL) req = NewRequest(t, "GET", issueURL)
resp = session.MakeRequest(t, req, http.StatusOK) 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) 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) resp = session.MakeRequest(t, req, http.StatusOK)
htmlDoc = NewHTMLParser(t, resp.Body) htmlDoc = NewHTMLParser(t, resp.Body)

View file

@ -11,6 +11,7 @@ import (
"testing" "testing"
"code.gitea.io/gitea/modules/setting" "code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/test"
api "code.gitea.io/sdk/gitea" api "code.gitea.io/sdk/gitea"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -54,7 +55,7 @@ func TestRedirectsNoLogin(t *testing.T) {
for link, redirectLink := range redirects { for link, redirectLink := range redirects {
req := NewRequest(t, "GET", link) req := NewRequest(t, "GET", link)
resp := MakeRequest(t, req, http.StatusFound) 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))
} }
} }

View file

@ -11,6 +11,8 @@ import (
"strings" "strings"
"testing" "testing"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -54,7 +56,7 @@ func TestPullMerge(t *testing.T) {
resp := testPullCreate(t, session, "user1", "repo1", "master") 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]) assert.EqualValues(t, "pulls", elem[3])
testPullMerge(t, session, elem[1], elem[2], elem[4]) 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") 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]) assert.EqualValues(t, "pulls", elem[3])
testPullMerge(t, session, elem[1], elem[2], elem[4]) testPullMerge(t, session, elem[1], elem[2], elem[4])

View file

@ -9,6 +9,8 @@ import (
"net/http" "net/http"
"testing" "testing"
"code.gitea.io/gitea/modules/test"
"github.com/Unknwon/i18n" "github.com/Unknwon/i18n"
"github.com/stretchr/testify/assert" "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) 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) { func checkLatestReleaseAndCount(t *testing.T, session *TestSession, repoURL, version, label string, count int) {

View file

@ -9,6 +9,8 @@ import (
"strings" "strings"
"testing" "testing"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -20,7 +22,7 @@ func TestRepoActivity(t *testing.T) {
testRepoFork(t, session, "user2", "repo1", "user1", "repo1") testRepoFork(t, session, "user2", "repo1", "user1", "repo1")
testEditFile(t, session, "user1", "repo1", "master", "README.md", "Hello, World (Edited)\n") testEditFile(t, session, "user1", "repo1", "master", "README.md", "Hello, World (Edited)\n")
resp := testPullCreate(t, session, "user1", "repo1", "master") 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]) assert.EqualValues(t, "pulls", elem[3])
testPullMerge(t, session, elem[1], elem[2], elem[4]) testPullMerge(t, session, elem[1], elem[2], elem[4])

View file

@ -10,6 +10,8 @@ import (
"strings" "strings"
"testing" "testing"
"code.gitea.io/gitea/modules/test"
"github.com/Unknwon/i18n" "github.com/Unknwon/i18n"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -29,7 +31,7 @@ func testCreateBranch(t *testing.T, session *TestSession, user, repo, oldRefSubU
if expectedStatus != http.StatusFound { if expectedStatus != http.StatusFound {
return "" return ""
} }
return RedirectURL(t, resp) return test.RedirectURL(resp)
} }
func TestCreateBranch(t *testing.T) { func TestCreateBranch(t *testing.T) {

View file

@ -10,6 +10,8 @@ import (
"testing" "testing"
"time" "time"
"code.gitea.io/gitea/modules/test"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -47,7 +49,7 @@ func testViewTimetrackingControls(t *testing.T, session *TestSession, user, repo
if canTrackTime { if canTrackTime {
resp = session.MakeRequest(t, req, http.StatusSeeOther) 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) resp = session.MakeRequest(t, req, http.StatusOK)
htmlDoc = NewHTMLParser(t, resp.Body) 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) 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) resp = session.MakeRequest(t, req, http.StatusOK)
htmlDoc = NewHTMLParser(t, resp.Body) htmlDoc = NewHTMLParser(t, resp.Body)

View file

@ -9,6 +9,7 @@ import (
"testing" "testing"
"code.gitea.io/gitea/models" "code.gitea.io/gitea/models"
"code.gitea.io/gitea/modules/test"
"github.com/Unknwon/i18n" "github.com/Unknwon/i18n"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
@ -86,7 +87,7 @@ func TestRenameReservedUsername(t *testing.T) {
}) })
resp := session.MakeRequest(t, req, http.StatusFound) 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) resp = session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body) htmlDoc := NewHTMLParser(t, resp.Body)
assert.Contains(t, assert.Contains(t,

View file

@ -17,6 +17,7 @@ import (
"github.com/go-xorm/xorm" "github.com/go-xorm/xorm"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"gopkg.in/testfixtures.v2" "gopkg.in/testfixtures.v2"
"net/url"
) )
// NonexistentID an ID that will never exist // 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 // MainTest a reusable TestMain(..) function for unit tests that need to use a
// test database. Creates the test database, and sets necessary settings. // test database. Creates the test database, and sets necessary settings.
func MainTest(m *testing.M, pathToGiteaRoot string) { func MainTest(m *testing.M, pathToGiteaRoot string) {
var err error
giteaRoot = pathToGiteaRoot giteaRoot = pathToGiteaRoot
fixturesDir := filepath.Join(pathToGiteaRoot, "models", "fixtures") 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) fmt.Fprintf(os.Stderr, "Error creating test engine: %v\n", err)
os.Exit(1) os.Exit(1)
} }
@ -41,6 +43,13 @@ func MainTest(m *testing.M, pathToGiteaRoot string) {
setting.SSH.Domain = "try.gitea.io" setting.SSH.Domain = "try.gitea.io"
setting.RepoRootPath = filepath.Join(os.TempDir(), "repos") setting.RepoRootPath = filepath.Join(os.TempDir(), "repos")
setting.AppDataPath = filepath.Join(os.TempDir(), "appdata") 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()) os.Exit(m.Run())
} }
@ -140,6 +149,14 @@ func AssertNotExistsBean(t *testing.T, bean interface{}, conditions ...interface
assert.False(t, exists) 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 // AssertSuccessfulInsert assert that beans is successfully inserted
func AssertSuccessfulInsert(t *testing.T, beans ...interface{}) { func AssertSuccessfulInsert(t *testing.T, beans ...interface{}) {
_, err := x.Insert(beans...) _, err := x.Insert(beans...)

View file

@ -16,6 +16,7 @@ import (
"github.com/go-macaron/session" "github.com/go-macaron/session"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"gopkg.in/macaron.v1" "gopkg.in/macaron.v1"
"net/http/httptest"
) )
// MockContext mock context for unit tests // 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) { func LoadRepo(t *testing.T, ctx *context.Context, repoID int64) {
ctx.Repo = &context.Repository{} ctx.Repo = &context.Repository{}
ctx.Repo.Repository = models.AssertExistsAndLoadBean(t, &models.Repository{ID: repoID}).(*models.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. // LoadUser load a user into a test context.
@ -71,32 +73,21 @@ func (l mockLocale) Tr(s string, _ ...interface{}) string {
} }
type mockResponseWriter struct { type mockResponseWriter struct {
status int httptest.ResponseRecorder
size int size int
}
func (rw *mockResponseWriter) Header() http.Header {
return map[string][]string{}
} }
func (rw *mockResponseWriter) Write(b []byte) (int, error) { func (rw *mockResponseWriter) Write(b []byte) (int, error) {
rw.size += len(b) rw.size += len(b)
return len(b), nil return rw.ResponseRecorder.Write(b)
}
func (rw *mockResponseWriter) WriteHeader(status int) {
rw.status = status
}
func (rw *mockResponseWriter) Flush() {
} }
func (rw *mockResponseWriter) Status() int { func (rw *mockResponseWriter) Status() int {
return rw.status return rw.ResponseRecorder.Code
} }
func (rw *mockResponseWriter) Written() bool { func (rw *mockResponseWriter) Written() bool {
return rw.status > 0 return rw.ResponseRecorder.Code > 0
} }
func (rw *mockResponseWriter) Size() int { func (rw *mockResponseWriter) Size() int {

14
modules/test/utils.go Normal file
View file

@ -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")
}

View file

@ -776,7 +776,7 @@ func getActionIssues(ctx *context.Context) []*models.Issue {
return nil return nil
} }
if err = issue.LoadAttributes(); err != nil { if err = issue.LoadAttributes(); err != nil {
ctx.Handle(500, "LoadAttributes", nil) ctx.Handle(500, "LoadAttributes", err)
return nil return nil
} }
} }

View file

@ -155,18 +155,14 @@ func UpdateIssueLabel(ctx *context.Context) {
} }
if action == "toggle" { if action == "toggle" {
anyHaveLabel := false // detach if any issues already have label, otherwise attach
action = "attach"
for _, issue := range issues { for _, issue := range issues {
if issue.HasLabel(label.ID) { if issue.HasLabel(label.ID) {
anyHaveLabel = true action = "detach"
break break
} }
} }
if anyHaveLabel {
action = "detach"
} else {
action = "attach"
}
} }
if action == "attach" { if action == "attach" {

View file

@ -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{})
}
}