Skip to content

[WIP] Write tests for issue API #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ _testmain.go
coverage.out

*.db
*.sqlite3
*.log

/gitea
Expand Down
25 changes: 13 additions & 12 deletions cmd/web.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ go get -u %[1]s`, c.ImportPath, c.Version(), c.Expected)
}

// newMacaron initializes Macaron instance.
func newMacaron() *macaron.Macaron {
func NewMacaron() *macaron.Macaron {
m := macaron.New()
if !setting.DisableRouterLog {
m.Use(macaron.Logger())
Expand Down Expand Up @@ -183,17 +183,6 @@ func newMacaron() *macaron.Macaron {
},
}))
m.Use(context.Contexter())
return m
}

func runWeb(ctx *cli.Context) error {
if ctx.IsSet("config") {
setting.CustomConf = ctx.String("config")
}
routers.GlobalInit()
checkVersion()

m := newMacaron()

reqSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: true})
ignSignIn := context.Toggle(&context.ToggleOptions{SignInRequired: setting.Service.RequireSignInView})
Expand Down Expand Up @@ -625,6 +614,18 @@ func runWeb(ctx *cli.Context) error {
// Not found handler.
m.NotFound(routers.NotFound)

return m
}

func runWeb(ctx *cli.Context) error {
if ctx.IsSet("config") {
setting.CustomConf = ctx.String("config")
}
routers.GlobalInit()
checkVersion()

m := NewMacaron()

// Flag for port number in case first time run conflict.
if ctx.IsSet("port") {
setting.AppUrl = strings.Replace(setting.AppUrl, setting.HTTPPort, ctx.String("port"), 1)
Expand Down
4 changes: 4 additions & 0 deletions models/models.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,10 @@ var (
EnableTiDB bool
)

func Database() *sql.DB {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And now we can execute SQL queries from handlers?

return x.DB().DB
}

func init() {
tables = append(tables,
new(User), new(PublicKey), new(AccessToken),
Expand Down
6 changes: 5 additions & 1 deletion models/repo.go
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,11 @@ func NewRepoContext() {
log.Fatal(4, "Fail to execute 'git config --global core.quotepath false': %s", stderr)
}

RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp"))
// FIXME: skipping this for tests by now, because Gogs is not connected to a
// database at this point while running tests, so create notice will fail.
if setting.AppRunMode != setting.RUN_MODE_TEST {
RemoveAllWithNotice("Clean up repository temporary data", filepath.Join(setting.AppDataPath, "tmp"))
}
}

// Repository represents a git repository.
Expand Down
13 changes: 11 additions & 2 deletions modules/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,17 @@ func Contexter() macaron.Handler {

ctx.Data["PageStartTime"] = time.Now()

// Get user from session if logined.
ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
// just for unit tests, find user with cookie
if setting.AppRunMode == setting.RUN_MODE_TEST {
user, err := models.GetUserByID(ctx.GetCookieInt64("user_id"))
if err == nil {
ctx.User = user
}
ctx.IsBasicAuth = false
} else {
// Get user from session if logined.
ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
}

if ctx.User != nil {
ctx.IsSigned = true
Expand Down
16 changes: 13 additions & 3 deletions modules/setting/setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ const (
HTTPS Scheme = "https"
FCGI Scheme = "fcgi"
UNIX_SOCKET Scheme = "unix"

RUN_MODE_PROD = "prod"
RUN_MODE_DEV = "dev"
RUN_MODE_TEST = "test"
)

type LandingPage string
Expand All @@ -60,6 +64,8 @@ var (
AppPath string
AppDataPath string

AppRunMode string

// Server settings
Protocol Scheme
Domain string
Expand Down Expand Up @@ -263,6 +269,10 @@ var (
HasRobotsTxt bool
)

func GiteaPath() string {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exported functions should have be commented 😄

return filepath.Join(os.Getenv("GOPATH"), "src/github.com/go-gitea/gitea")
}

// DateLang transforms standard language locale name to corresponding value in datetime plugin.
func DateLang(lang string) string {
name, ok := dateLangs[lang]
Expand Down Expand Up @@ -361,7 +371,6 @@ func NewContext() {
please consider changing to GITEA_CUSTOM`)
}
}

if len(CustomConf) == 0 {
CustomConf = CustomPath + "/conf/app.ini"
}
Expand Down Expand Up @@ -390,6 +399,7 @@ please consider changing to GITEA_CUSTOM`)
if AppUrl[len(AppUrl)-1] != '/' {
AppUrl += "/"
}
AppRunMode = Cfg.Section("").Key("RUN_MODE").In(RUN_MODE_PROD, []string{RUN_MODE_PROD, RUN_MODE_DEV, RUN_MODE_TEST})

// Check if has app suburl.
url, err := url.Parse(AppUrl)
Expand Down Expand Up @@ -498,8 +508,8 @@ please consider changing to GITEA_CUSTOM`)
}[Cfg.Section("time").Key("FORMAT").MustString("RFC1123")]

RunUser = Cfg.Section("").Key("RUN_USER").String()
// Does not check run user when the install lock is off.
if InstallLock {
// Does not check run user when the install lock is off or is running tests
if InstallLock && AppRunMode != RUN_MODE_TEST {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change code for testing is a bad practice

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree. This is a WIP, we should abstract things using interfaces. I am open for suggestions on how to do it right.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok, thank you. It's very important to write testable code 👍

currentUser, match := IsRunUserMatchCurrentUser(RunUser)
if !match {
log.Fatal(4, "Expect user '%s' but current user is: %s", RunUser, currentUser)
Expand Down
75 changes: 75 additions & 0 deletions routers/api/v1/repo/issue_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
package repo_test

import (
"encoding/json"
"net/http"
"os"
"testing"

"github.com/go-gitea/gitea/models"
"github.com/go-gitea/gitea/testutil"
api "github.com/go-gitea/go-sdk/gitea"

"github.com/stretchr/testify/assert"
)

func TestMain(m *testing.M) {
testutil.TestGlobalInit()

os.Exit(m.Run())
}

func TestIssueIndex(t *testing.T) {
testutil.PrepareTestDatabase()

w, r := testutil.NewTestContext("GET", "/api/v1/repos/user1/foo/issues", "", nil, "1")
testutil.ServeHTTP(w, r)
assert.Equal(t, http.StatusOK, w.Code)
}

func TestIssueShow(t *testing.T) {
testutil.PrepareTestDatabase()

w, r := testutil.NewTestContext("GET", "/api/v1/repos/user1/foo/issues/1", "", nil, "1")
testutil.ServeHTTP(w, r)
assert.Equal(t, http.StatusOK, w.Code)

issue := new(api.Issue)
err := json.Unmarshal(w.Body.Bytes(), &issue)
assert.NoError(t, err)
assert.Equal(t, "Title", issue.Title)
assert.Equal(t, "Content", issue.Body)
assert.Equal(t, "user1", issue.Poster.UserName)
}

func TestCreate(t *testing.T) {
testutil.PrepareTestDatabase()

bytes, _ := json.Marshal(api.Issue{
Title: "A issue title",
Body: "Please fix",
})
count := testutil.TableCount("issue")
w, r := testutil.NewTestContext("POST", "/api/v1/repos/user1/foo/issues", testutil.CONTENT_TYPE_JSON, bytes, "1")
testutil.ServeHTTP(w, r)
assert.Equal(t, http.StatusCreated, w.Code)
assert.Equal(t, count+1, testutil.TableCount("issue"))
issue, _ := models.GetIssueByID(testutil.LastId("issue"))
assert.Equal(t, "A issue title", issue.Title)
assert.Equal(t, "Please fix", issue.Content)
}

func TestEdit(t *testing.T) {
testutil.PrepareTestDatabase()

bytes, _ := json.Marshal(api.Issue{
Title: "Edited title",
Body: "Edited content",
})
w, r := testutil.NewTestContext("PATCH", "/api/v1/repos/user1/foo/issues/1", testutil.CONTENT_TYPE_JSON, bytes, "1")
testutil.ServeHTTP(w, r)
assert.Equal(t, http.StatusCreated, w.Code)
issue, _ := models.GetIssueByID(1)
assert.Equal(t, "Edited title", issue.Title)
assert.Equal(t, "Edited content", issue.Content)
}
31 changes: 31 additions & 0 deletions testdata/app_test.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# THIS FILE EXISTS TO BE USED TO UNIT TESTS
# DON'T CHANGE IT. THIS IS NOT THE FILE GOGS WILL USE IN PRODUCTION
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GOGS ? :trollface:


APP_NAME = Gogs: Go Git Service
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as above

RUN_MODE = test

[database]
DB_TYPE = sqlite3
PATH = testdata/gitea_test.sqlite3

[repository]
ROOT = testdata/gitea-test-repositories

[mailer]
ENABLED = false

[service]

[picture]
DISABLE_GRAVATAR = true

[session]
PROVIDER = memory

[log]
MODE = file
LEVEL = Info

[security]
INSTALL_LOCK = true
SECRET_KEY = foobar
19 changes: 19 additions & 0 deletions testdata/fixtures/issue.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-
id: 1
repo_id: 1
index: 1
name: Title
poster_id: 1
content: Content
is_pull: false
is_closed: false

-
id: 2
repo_id: 1
index: 2
name: Title
poster_id: 1
content: Content
is_pull: false
is_closed: false
24 changes: 24 additions & 0 deletions testdata/fixtures/repository.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
-
id: 1
owner_id: 1
lower_name: foo
name: foo
num_issues: 2

-
id: 2
owner_id: 2
lower_name: bar
name: bar

-
id: 3
owner_id: 3
lower_name: foo
name: foo

-
id: 4
owner_id: 4
lower_name: bar
name: bar
19 changes: 19 additions & 0 deletions testdata/fixtures/user.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-
id: 1
lower_name: user1
name: user1
full_name: User 1
email: [email protected]
passwd: ""
avatar: ""
avatar_email: ""

-
id: 2
lower_name: user2
name: user2
full_name: User 2
email: [email protected]
passwd: ""
avatar: ""
avatar_email: ""
Loading