Skip to content

Commit

Permalink
improve unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
wxiaoguang committed Jun 16, 2023
1 parent 4ba6d51 commit 5c48b7c
Show file tree
Hide file tree
Showing 20 changed files with 93 additions and 135 deletions.
38 changes: 20 additions & 18 deletions modules/test/context_tests.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"

access_model "code.gitea.io/gitea/models/perm/access"
Expand All @@ -25,17 +26,24 @@ import (
"github.com/stretchr/testify/assert"
)

// MockContext mock context for unit tests
// TODO: move this function to other packages, because it depends on "models" package
func MockContext(t *testing.T, path string) *context.Context {
resp := httptest.NewRecorder()
func mockRequest(t *testing.T, reqPath string) *http.Request {
method, path, found := strings.Cut(reqPath, " ")
if !found {
method = "GET"
path = reqPath
}
requestURL, err := url.Parse(path)
assert.NoError(t, err)
req := &http.Request{
URL: requestURL,
Form: url.Values{},
}
req := &http.Request{Method: method, URL: requestURL, Form: url.Values{}}
req = req.WithContext(middleware.WithContextData(req.Context()))
return req
}

// MockContext mock context for unit tests
// TODO: move this function to other packages, because it depends on "models" package
func MockContext(t *testing.T, reqPath string) (*context.Context, *httptest.ResponseRecorder) {
resp := httptest.NewRecorder()
req := mockRequest(t, reqPath)
base, baseCleanUp := context.NewBaseContext(resp, req)
base.Data = middleware.GetContextData(req.Context())
base.Locale = &translation.MockLocale{}
Expand All @@ -48,20 +56,14 @@ func MockContext(t *testing.T, path string) *context.Context {

chiCtx := chi.NewRouteContext()
ctx.Base.AppendContextValue(chi.RouteCtxKey, chiCtx)
return ctx
return ctx, resp
}

// MockAPIContext mock context for unit tests
// TODO: move this function to other packages, because it depends on "models" package
func MockAPIContext(t *testing.T, path string) *context.APIContext {
func MockAPIContext(t *testing.T, reqPath string) (*context.APIContext, *httptest.ResponseRecorder) {
resp := httptest.NewRecorder()
requestURL, err := url.Parse(path)
assert.NoError(t, err)
req := &http.Request{
URL: requestURL,
Form: url.Values{},
}
req = req.WithContext(middleware.WithContextData(req.Context()))
req := mockRequest(t, reqPath)
base, baseCleanUp := context.NewBaseContext(resp, req)
base.Data = middleware.GetContextData(req.Context())
base.Locale = &translation.MockLocale{}
Expand All @@ -70,7 +72,7 @@ func MockAPIContext(t *testing.T, path string) *context.APIContext {

chiCtx := chi.NewRouteContext()
ctx.Base.AppendContextValue(chi.RouteCtxKey, chiCtx)
return ctx
return ctx, resp
}

// LoadRepo load a repo into a test context.
Expand Down
58 changes: 7 additions & 51 deletions routers/api/v1/misc/markup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,14 @@ import (
go_context "context"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"

"code.gitea.io/gitea/modules/context"
"code.gitea.io/gitea/modules/markup"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/modules/web/middleware"

"github.com/stretchr/testify/assert"
)
Expand All @@ -29,34 +25,16 @@ const (
AppSubURL = AppURL + Repo + "/"
)

func createAPIContext(req *http.Request) (*context.APIContext, *httptest.ResponseRecorder) {
resp := httptest.NewRecorder()
base, baseCleanUp := context.NewBaseContext(resp, req)
base.Data = middleware.ContextData{}
c := &context.APIContext{Base: base}
_ = baseCleanUp // during test, it doesn't need to do clean up. TODO: this can be improved later

return c, resp
}

func testRenderMarkup(t *testing.T, mode, filePath, text, responseBody string, responseCode int) {
setting.AppURL = AppURL

options := api.MarkupOption{
Mode: mode,
Text: "",
Text: text,
Context: Repo,
Wiki: true,
FilePath: filePath,
}
requrl, _ := url.Parse(util.URLJoin(AppURL, "api", "v1", "markup"))
req := &http.Request{
Method: "POST",
URL: requrl,
}
ctx, resp := createAPIContext(req)

options.Text = text
ctx, resp := test.MockAPIContext(t, "POST /api/v1/markup")
web.SetForm(ctx, &options)
Markup(ctx)
assert.Equal(t, responseBody, resp.Body.String())
Expand All @@ -66,21 +44,13 @@ func testRenderMarkup(t *testing.T, mode, filePath, text, responseBody string, r

func testRenderMarkdown(t *testing.T, mode, text, responseBody string, responseCode int) {
setting.AppURL = AppURL

options := api.MarkdownOption{
Mode: mode,
Text: "",
Text: text,
Context: Repo,
Wiki: true,
}
requrl, _ := url.Parse(util.URLJoin(AppURL, "api", "v1", "markdown"))
req := &http.Request{
Method: "POST",
URL: requrl,
}
ctx, resp := createAPIContext(req)

options.Text = text
ctx, resp := test.MockAPIContext(t, "POST /api/v1/markdown")
web.SetForm(ctx, &options)
Markdown(ctx)
assert.Equal(t, responseBody, resp.Body.String())
Expand Down Expand Up @@ -187,19 +157,12 @@ var simpleCases = []string{

func TestAPI_RenderSimple(t *testing.T) {
setting.AppURL = AppURL

options := api.MarkdownOption{
Mode: "markdown",
Text: "",
Context: Repo,
}
requrl, _ := url.Parse(util.URLJoin(AppURL, "api", "v1", "markdown"))
req := &http.Request{
Method: "POST",
URL: requrl,
}
ctx, resp := createAPIContext(req)

ctx, resp := test.MockAPIContext(t, "POST /api/v1/markdown")
for i := 0; i < len(simpleCases); i += 2 {
options.Text = simpleCases[i]
web.SetForm(ctx, &options)
Expand All @@ -211,14 +174,7 @@ func TestAPI_RenderSimple(t *testing.T) {

func TestAPI_RenderRaw(t *testing.T) {
setting.AppURL = AppURL

requrl, _ := url.Parse(util.URLJoin(AppURL, "api", "v1", "markdown"))
req := &http.Request{
Method: "POST",
URL: requrl,
}
ctx, resp := createAPIContext(req)

ctx, resp := test.MockAPIContext(t, "POST /api/v1/markdown")
for i := 0; i < len(simpleCases); i += 2 {
ctx.Req.Body = io.NopCloser(strings.NewReader(simpleCases[i]))
MarkdownRaw(ctx)
Expand Down
2 changes: 1 addition & 1 deletion routers/api/v1/repo/hook_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import (
func TestTestHook(t *testing.T) {
unittest.PrepareTestEnv(t)

ctx := test.MockAPIContext(t, "user2/repo1/wiki/_pages")
ctx, _ := test.MockAPIContext(t, "user2/repo1/wiki/_pages")
ctx.SetParams(":id", "1")
test.LoadRepo(t, ctx, 1)
test.LoadRepoCommit(t, ctx)
Expand Down
4 changes: 2 additions & 2 deletions routers/api/v1/repo/repo_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
func TestRepoEdit(t *testing.T) {
unittest.PrepareTestEnv(t)

ctx := test.MockAPIContext(t, "user2/repo1")
ctx, _ := test.MockAPIContext(t, "user2/repo1")
test.LoadRepo(t, ctx, 1)
test.LoadUser(t, ctx, 2)
ctx.Repo.Owner = ctx.Doer
Expand Down Expand Up @@ -65,7 +65,7 @@ func TestRepoEdit(t *testing.T) {
func TestRepoEditNameChange(t *testing.T) {
unittest.PrepareTestEnv(t)

ctx := test.MockAPIContext(t, "user2/repo1")
ctx, _ := test.MockAPIContext(t, "user2/repo1")
test.LoadRepo(t, ctx, 1)
test.LoadUser(t, ctx, 2)
ctx.Repo.Owner = ctx.Doer
Expand Down
10 changes: 5 additions & 5 deletions routers/web/admin/users_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (

func TestNewUserPost_MustChangePassword(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "admin/users/new")
ctx, _ := test.MockContext(t, "admin/users/new")

u := unittest.AssertExistsAndLoadBean(t, &user_model.User{
IsAdmin: true,
Expand Down Expand Up @@ -56,7 +56,7 @@ func TestNewUserPost_MustChangePassword(t *testing.T) {

func TestNewUserPost_MustChangePasswordFalse(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "admin/users/new")
ctx, _ := test.MockContext(t, "admin/users/new")

u := unittest.AssertExistsAndLoadBean(t, &user_model.User{
IsAdmin: true,
Expand Down Expand Up @@ -93,7 +93,7 @@ func TestNewUserPost_MustChangePasswordFalse(t *testing.T) {

func TestNewUserPost_InvalidEmail(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "admin/users/new")
ctx, _ := test.MockContext(t, "admin/users/new")

u := unittest.AssertExistsAndLoadBean(t, &user_model.User{
IsAdmin: true,
Expand Down Expand Up @@ -123,7 +123,7 @@ func TestNewUserPost_InvalidEmail(t *testing.T) {

func TestNewUserPost_VisibilityDefaultPublic(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "admin/users/new")
ctx, _ := test.MockContext(t, "admin/users/new")

u := unittest.AssertExistsAndLoadBean(t, &user_model.User{
IsAdmin: true,
Expand Down Expand Up @@ -161,7 +161,7 @@ func TestNewUserPost_VisibilityDefaultPublic(t *testing.T) {

func TestNewUserPost_VisibilityPrivate(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "admin/users/new")
ctx, _ := test.MockContext(t, "admin/users/new")

u := unittest.AssertExistsAndLoadBean(t, &user_model.User{
IsAdmin: true,
Expand Down
2 changes: 1 addition & 1 deletion routers/web/org/projects_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import (

func TestCheckProjectBoardChangePermissions(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/-/projects/4/4")
ctx, _ := test.MockContext(t, "user2/-/projects/4/4")
test.LoadUser(t, ctx, 2)
ctx.ContextUser = ctx.Doer // user2
ctx.SetParams(":id", "4")
Expand Down
4 changes: 2 additions & 2 deletions routers/web/repo/editor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func TestCleanUploadName(t *testing.T) {

func TestGetUniquePatchBranchName(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1")
ctx, _ := test.MockContext(t, "user2/repo1")
ctx.SetParams(":id", "1")
test.LoadRepo(t, ctx, 1)
test.LoadRepoCommit(t, ctx)
Expand All @@ -56,7 +56,7 @@ func TestGetUniquePatchBranchName(t *testing.T) {

func TestGetClosestParentWithFiles(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1")
ctx, _ := test.MockContext(t, "user2/repo1")
ctx.SetParams(":id", "1")
test.LoadRepo(t, ctx, 1)
test.LoadRepoCommit(t, ctx)
Expand Down
14 changes: 7 additions & 7 deletions routers/web/repo/issue_label_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ func int64SliceToCommaSeparated(a []int64) string {
func TestInitializeLabels(t *testing.T) {
unittest.PrepareTestEnv(t)
assert.NoError(t, repository.LoadRepoConfig())
ctx := test.MockContext(t, "user2/repo1/labels/initialize")
ctx, _ := test.MockContext(t, "user2/repo1/labels/initialize")
test.LoadUser(t, ctx, 2)
test.LoadRepo(t, ctx, 2)
web.SetForm(ctx, &forms.InitializeLabelsForm{TemplateName: "Default"})
Expand All @@ -57,7 +57,7 @@ func TestRetrieveLabels(t *testing.T) {
{1, "leastissues", []int64{2, 1}},
{2, "", []int64{}},
} {
ctx := test.MockContext(t, "user/repo/issues")
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)
Expand All @@ -75,7 +75,7 @@ func TestRetrieveLabels(t *testing.T) {

func TestNewLabel(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1/labels/edit")
ctx, _ := test.MockContext(t, "user2/repo1/labels/edit")
test.LoadUser(t, ctx, 2)
test.LoadRepo(t, ctx, 1)
web.SetForm(ctx, &forms.CreateLabelForm{
Expand All @@ -93,7 +93,7 @@ func TestNewLabel(t *testing.T) {

func TestUpdateLabel(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1/labels/edit")
ctx, _ := test.MockContext(t, "user2/repo1/labels/edit")
test.LoadUser(t, ctx, 2)
test.LoadRepo(t, ctx, 1)
web.SetForm(ctx, &forms.CreateLabelForm{
Expand All @@ -113,7 +113,7 @@ func TestUpdateLabel(t *testing.T) {

func TestDeleteLabel(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1/labels/delete")
ctx, _ := test.MockContext(t, "user2/repo1/labels/delete")
test.LoadUser(t, ctx, 2)
test.LoadRepo(t, ctx, 1)
ctx.Req.Form.Set("id", "2")
Expand All @@ -126,7 +126,7 @@ func TestDeleteLabel(t *testing.T) {

func TestUpdateIssueLabel_Clear(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1/issues/labels")
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")
Expand All @@ -151,7 +151,7 @@ func TestUpdateIssueLabel_Toggle(t *testing.T) {
{"toggle", []int64{1, 2}, 2, true},
} {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1/issues/labels")
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))
Expand Down
2 changes: 1 addition & 1 deletion routers/web/repo/projects_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (

func TestCheckProjectBoardChangePermissions(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo1/projects/1/2")
ctx, _ := test.MockContext(t, "user2/repo1/projects/1/2")
test.LoadUser(t, ctx, 2)
test.LoadRepo(t, ctx, 1)
ctx.SetParams(":id", "1")
Expand Down
4 changes: 2 additions & 2 deletions routers/web/repo/release_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func TestNewReleasePost(t *testing.T) {
} {
unittest.PrepareTestEnv(t)

ctx := test.MockContext(t, "user2/repo1/releases/new")
ctx, _ := test.MockContext(t, "user2/repo1/releases/new")
test.LoadUser(t, ctx, 2)
test.LoadRepo(t, ctx, 1)
test.LoadGitRepo(t, ctx)
Expand All @@ -67,7 +67,7 @@ func TestNewReleasePost(t *testing.T) {

func TestNewReleasesList(t *testing.T) {
unittest.PrepareTestEnv(t)
ctx := test.MockContext(t, "user2/repo-release/releases")
ctx, _ := test.MockContext(t, "user2/repo-release/releases")
test.LoadUser(t, ctx, 2)
test.LoadRepo(t, ctx, 57)
test.LoadGitRepo(t, ctx)
Expand Down
Loading

0 comments on commit 5c48b7c

Please sign in to comment.