Skip to content

Commit 1cd992d

Browse files
committed
add tests
1 parent 736ee8d commit 1cd992d

File tree

14 files changed

+99
-29
lines changed

14 files changed

+99
-29
lines changed

models/fixtures/repo_unit.yml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,3 +575,9 @@
575575
repo_id: 56
576576
type: 1
577577
created_unix: 946684810
578+
579+
-
580+
id: 85
581+
repo_id: 52
582+
type: 1
583+
created_unix: 946684810

models/fixtures/repository.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1559,6 +1559,7 @@
15591559
owner_name: user30
15601560
lower_name: empty
15611561
name: empty
1562+
default_branch: master
15621563
num_watches: 0
15631564
num_stars: 0
15641565
num_forks: 0

models/fixtures/user.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1091,11 +1091,11 @@
10911091
max_repo_creation: -1
10921092
is_active: true
10931093
is_admin: false
1094-
is_restricted: true
1094+
is_restricted: false
10951095
allow_git_hook: false
10961096
allow_import_local: false
10971097
allow_create_organization: true
1098-
prohibit_login: true
1098+
prohibit_login: false
10991099
avatar: avatar29
11001100
avatar_email: [email protected]
11011101
use_custom_avatar: false

modules/context/repo.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -691,7 +691,7 @@ func RepoAssignment(ctx *Context) (cancel context.CancelFunc) {
691691
ctx.Data["BranchesCount"] = len(brs)
692692

693693
// If not branch selected, try default one.
694-
// If default branch doesn't exists, fall back to some other branch.
694+
// If default branch doesn't exist, fall back to some other branch.
695695
if len(ctx.Repo.BranchName) == 0 {
696696
if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) {
697697
ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch

modules/indexer/code/indexer.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,9 @@ func Init() {
154154
log.Trace("IndexerData Process Repo: %d", indexerData.RepoID)
155155

156156
if err := index(ctx, indexer, indexerData.RepoID); err != nil {
157-
log.Error("index: %v", err)
157+
if !setting.IsInTesting {
158+
log.Error("indexer index error for repo %v: %v", indexerData.RepoID, err)
159+
}
158160
if indexer.Ping() {
159161
continue
160162
}

modules/indexer/stats/db.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import (
1111
"code.gitea.io/gitea/modules/graceful"
1212
"code.gitea.io/gitea/modules/log"
1313
"code.gitea.io/gitea/modules/process"
14+
"code.gitea.io/gitea/modules/setting"
1415
)
1516

1617
// DBIndexer implements Indexer interface to use database's like search
@@ -46,7 +47,7 @@ func (db *DBIndexer) Index(id int64) error {
4647
// Get latest commit for default branch
4748
commitID, err := gitRepo.GetBranchCommitID(repo.DefaultBranch)
4849
if err != nil {
49-
if git.IsErrBranchNotExist(err) || git.IsErrNotExist(err) {
50+
if git.IsErrBranchNotExist(err) || git.IsErrNotExist(err) || setting.IsInTesting {
5051
log.Debug("Unable to get commit ID for default branch %s in %s ... skipping this repository", repo.DefaultBranch, repo.RepoPath())
5152
return nil
5253
}
@@ -62,7 +63,9 @@ func (db *DBIndexer) Index(id int64) error {
6263
// Calculate and save language statistics to database
6364
stats, err := gitRepo.GetLanguageStats(commitID)
6465
if err != nil {
65-
log.Error("Unable to get language stats for ID %s for default branch %s in %s. Error: %v", commitID, repo.DefaultBranch, repo.RepoPath(), err)
66+
if !setting.IsInTesting {
67+
log.Error("Unable to get language stats for ID %s for default branch %s in %s. Error: %v", commitID, repo.DefaultBranch, repo.RepoPath(), err)
68+
}
6669
return err
6770
}
6871
err = repo_model.UpdateLanguageStats(repo, commitID, stats)

modules/indexer/stats/queue.go

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"code.gitea.io/gitea/modules/graceful"
1111
"code.gitea.io/gitea/modules/log"
1212
"code.gitea.io/gitea/modules/queue"
13+
"code.gitea.io/gitea/modules/setting"
1314
)
1415

1516
// statsQueue represents a queue to handle repository stats updates
@@ -20,7 +21,9 @@ func handle(data ...queue.Data) []queue.Data {
2021
for _, datum := range data {
2122
opts := datum.(int64)
2223
if err := indexer.Index(opts); err != nil {
23-
log.Error("stats queue indexer.Index(%d) failed: %v", opts, err)
24+
if !setting.IsInTesting {
25+
log.Error("stats queue indexer.Index(%d) failed: %v", opts, err)
26+
}
2427
}
2528
}
2629
return nil

modules/setting/setting.go

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ import (
2727
var (
2828
// AppVer is the version of the current build of Gitea. It is set in main.go from main.Version.
2929
AppVer string
30-
// AppBuiltWith represents a human readable version go runtime build version and build tags. (See main.go formatBuiltWith().)
30+
// AppBuiltWith represents a human-readable version go runtime build version and build tags. (See main.go formatBuiltWith().)
3131
AppBuiltWith string
3232
// AppStartTime store time gitea has started
3333
AppStartTime time.Time
@@ -40,14 +40,19 @@ var (
4040
// AppWorkPath is used as the base path for several other paths.
4141
AppWorkPath string
4242

43-
// Global setting objects
43+
// Other global setting objects
44+
4445
CfgProvider ConfigProvider
4546
CustomPath string // Custom directory path
4647
CustomConf string
4748
RunMode string
4849
RunUser string
4950
IsProd bool
5051
IsWindows bool
52+
53+
// IsInTesting indicates whether the testing is running. A lot of unreliable code causes a lot of nonsense error logs during testing
54+
// TODO: this is only a temporary solution, we should make the test code more reliable
55+
IsInTesting = false
5156
)
5257

5358
func getAppPath() (string, error) {
@@ -117,6 +122,7 @@ func init() {
117122
log.Fatal("Failed to get app path: %v", err)
118123
}
119124
AppWorkPath = getWorkPath(AppPath)
125+
AppVer = "dev"
120126
}
121127

122128
func forcePathSeparator(path string) {

routers/init.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,14 +108,14 @@ func GlobalInitInstalled(ctx context.Context) {
108108
}
109109

110110
mustInitCtx(ctx, git.InitFull)
111+
log.Info("Gitea Version: %s%s", setting.AppVer, setting.AppBuiltWith)
111112
log.Info("Git Version: %s (home: %s)", git.VersionInfo(), git.HomeDir())
112113
log.Info("AppPath: %s", setting.AppPath)
113114
log.Info("AppWorkPath: %s", setting.AppWorkPath)
114115
log.Info("Custom path: %s", setting.CustomPath)
115116
log.Info("Log path: %s", setting.Log.RootPath)
116117
log.Info("Configuration file: %s", setting.CustomConf)
117118
log.Info("Run Mode: %s", util.ToTitleCase(setting.RunMode))
118-
log.Info("Gitea v%s%s", setting.AppVer, setting.AppBuiltWith)
119119

120120
// Setup i18n
121121
translation.InitLocales(ctx)

routers/web/repo/editor.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,10 @@ func editFilePost(ctx *context.Context, form forms.EditRepoFileForm, isNewFile b
327327
}
328328
}
329329

330+
if ctx.Repo.Repository.IsEmpty {
331+
_ = repo_model.UpdateRepositoryCols(ctx, &repo_model.Repository{ID: ctx.Repo.Repository.ID, IsEmpty: false}, "is_empty")
332+
}
333+
330334
if form.CommitChoice == frmCommitChoiceNewBranch && ctx.Repo.Repository.UnitEnabled(ctx, unit.TypePullRequests) {
331335
ctx.Redirect(ctx.Repo.RepoLink + "/compare/" + util.PathEscapeSegments(ctx.Repo.BranchName) + "..." + util.PathEscapeSegments(form.NewBranchName))
332336
} else {

services/auth/source/db/authenticate.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ func Authenticate(user *user_model.User, login, password string) (*user_model.Us
3232
}
3333

3434
// WARN: DON'T check user.IsActive, that will be checked on reqSign so that
35-
// user could be hint to resend confirm email.
35+
// user could be hinted to resend confirm email.
3636
if user.ProhibitLogin {
3737
return nil, user_model.ErrUserProhibitLogin{
3838
UID: user.ID,

tests/integration/empty_repo_test.go

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,14 +10,16 @@ import (
1010
repo_model "code.gitea.io/gitea/models/repo"
1111
"code.gitea.io/gitea/models/unittest"
1212
user_model "code.gitea.io/gitea/models/user"
13+
"code.gitea.io/gitea/modules/setting"
14+
"code.gitea.io/gitea/modules/test"
1315
"code.gitea.io/gitea/tests"
1416

1517
"github.com/stretchr/testify/assert"
1618
)
1719

1820
func TestEmptyRepo(t *testing.T) {
1921
defer tests.PrepareTestEnv(t)()
20-
subpaths := []string{
22+
subPaths := []string{
2123
"commits/master",
2224
"raw/foo",
2325
"commit/1ae57b34ccf7e18373",
@@ -26,8 +28,31 @@ func TestEmptyRepo(t *testing.T) {
2628
emptyRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 5})
2729
assert.True(t, emptyRepo.IsEmpty)
2830
owner := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: emptyRepo.OwnerID})
29-
for _, subpath := range subpaths {
30-
req := NewRequestf(t, "GET", "/%s/%s/%s", owner.Name, emptyRepo.Name, subpath)
31+
for _, subPath := range subPaths {
32+
req := NewRequestf(t, "GET", "/%s/%s/%s", owner.Name, emptyRepo.Name, subPath)
3133
MakeRequest(t, req, http.StatusNotFound)
3234
}
3335
}
36+
37+
func TestEmptyRepoAddFile(t *testing.T) {
38+
defer tests.PrepareTestEnv(t)()
39+
session := loginUser(t, "user30")
40+
req := NewRequest(t, "GET", "/user30/empty/_new/"+setting.Repository.DefaultBranch)
41+
resp := session.MakeRequest(t, req, http.StatusOK)
42+
doc := NewHTMLParser(t, resp.Body).Find(`input[name="commit_choice"]`)
43+
assert.Equal(t, "", doc.AttrOr("checked", "_no_"))
44+
req = NewRequestWithValues(t, "POST", "/user30/empty/_new/"+setting.Repository.DefaultBranch, map[string]string{
45+
"_csrf": GetCSRF(t, session, "/user/settings"),
46+
"commit_choice": "direct",
47+
"tree_path": "test-file.md",
48+
"content": "newly-added-test-file",
49+
})
50+
51+
resp = session.MakeRequest(t, req, http.StatusSeeOther)
52+
redirect := test.RedirectURL(resp)
53+
assert.Equal(t, "/user30/empty/src/branch/"+setting.Repository.DefaultBranch+"/test-file.md", redirect)
54+
55+
req = NewRequest(t, "GET", redirect)
56+
resp = session.MakeRequest(t, req, http.StatusOK)
57+
assert.Contains(t, resp.Body.String(), "newly-added-test-file")
58+
}

tests/integration/integration_test.go

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -124,6 +124,9 @@ func TestMain(m *testing.M) {
124124
fmt.Printf("Error initializing test database: %v\n", err)
125125
os.Exit(1)
126126
}
127+
128+
// FIXME: the console logger is deleted by mistake, so if there is any `log.Fatal`, developers won't see any error message.
129+
// Instead, "No tests were found", last nonsense log is "According to the configuration, subsequent logs will not be printed to the console"
127130
exitCode := m.Run()
128131

129132
tests.WriterCloser.Reset()
@@ -366,10 +369,12 @@ const NoExpectedStatus = -1
366369
func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
367370
t.Helper()
368371
recorder := httptest.NewRecorder()
372+
if req.RemoteAddr == "" {
373+
req.RemoteAddr = "test-mock:12345"
374+
}
369375
c.ServeHTTP(recorder, req)
370376
if expectedStatus != NoExpectedStatus {
371-
if !assert.EqualValues(t, expectedStatus, recorder.Code,
372-
"Request: %s %s", req.Method, req.URL.String()) {
377+
if !assert.EqualValues(t, expectedStatus, recorder.Code, "Request: %s %s", req.Method, req.URL.String()) {
373378
logUnexpectedResponse(t, recorder)
374379
}
375380
}
@@ -410,8 +415,10 @@ func logUnexpectedResponse(t testing.TB, recorder *httptest.ResponseRecorder) {
410415
return
411416
} else if len(respBytes) < 500 {
412417
// if body is short, just log the whole thing
413-
t.Log("Response:", string(respBytes))
418+
t.Log("Response: ", string(respBytes))
414419
return
420+
} else {
421+
t.Log("Response length: ", len(respBytes))
415422
}
416423

417424
// log the "flash" error message, if one exists

tests/test_utils.go

Lines changed: 25 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import (
1010
"os"
1111
"path"
1212
"path/filepath"
13-
"runtime"
1413
"testing"
1514

1615
"code.gitea.io/gitea/models/db"
@@ -30,29 +29,44 @@ import (
3029
"github.com/stretchr/testify/assert"
3130
)
3231

32+
func exitf(format string, args ...interface{}) {
33+
fmt.Printf(format+"\n", args...)
34+
os.Exit(1)
35+
}
36+
3337
func InitTest(requireGitea bool) {
3438
giteaRoot := base.SetupGiteaRoot()
3539
if giteaRoot == "" {
36-
fmt.Println("Environment variable $GITEA_ROOT not set")
37-
os.Exit(1)
40+
exitf("Environment variable $GITEA_ROOT not set")
3841
}
42+
setting.AppWorkPath = giteaRoot
3943
if requireGitea {
4044
giteaBinary := "gitea"
41-
if runtime.GOOS == "windows" {
45+
if setting.IsWindows {
4246
giteaBinary += ".exe"
4347
}
4448
setting.AppPath = path.Join(giteaRoot, giteaBinary)
4549
if _, err := os.Stat(setting.AppPath); err != nil {
46-
fmt.Printf("Could not find gitea binary at %s\n", setting.AppPath)
47-
os.Exit(1)
50+
exitf("Could not find gitea binary at %s", setting.AppPath)
4851
}
4952
}
5053

5154
giteaConf := os.Getenv("GITEA_CONF")
5255
if giteaConf == "" {
53-
fmt.Println("Environment variable $GITEA_CONF not set")
54-
os.Exit(1)
55-
} else if !path.IsAbs(giteaConf) {
56+
// By default, use sqlite.ini for testing, then IDE like GoLand can start the test process with debugger.
57+
// It's easier for developers to debug bugs step by step with a debugger.
58+
// Notice: when doing "ssh push", Gitea executes sub processes, debugger won't work for the sub processes.
59+
giteaConf = "tests/sqlite.ini"
60+
_ = os.Setenv("GITEA_CONF", giteaConf)
61+
fmt.Printf("Environment variable $GITEA_CONF not set, use default: %s\n", giteaConf)
62+
if !setting.EnableSQLite3 {
63+
exitf(`Need to enable SQLite3 for sqlite.ini testing, please set: -tags "sqlite,sqlite_unlock_notify"`)
64+
}
65+
}
66+
67+
setting.IsInTesting = true
68+
69+
if !path.IsAbs(giteaConf) {
5670
setting.CustomConf = path.Join(giteaRoot, giteaConf)
5771
} else {
5872
setting.CustomConf = giteaConf
@@ -69,8 +83,7 @@ func InitTest(requireGitea bool) {
6983

7084
setting.LoadDBSetting()
7185
if err := storage.Init(); err != nil {
72-
fmt.Printf("Init storage failed: %v", err)
73-
os.Exit(1)
86+
exitf("Init storage failed: %v", err)
7487
}
7588

7689
switch {
@@ -221,7 +234,7 @@ func PrepareTestEnv(t testing.TB, skip ...int) func() {
221234
return deferFn
222235
}
223236

224-
// resetFixtures flushes queues, reloads fixtures and resets test repositories within a single test.
237+
// ResetFixtures flushes queues, reloads fixtures and resets test repositories within a single test.
225238
// Most tests should call defer tests.PrepareTestEnv(t)() (or have onGiteaRun do that for them) but sometimes
226239
// within a single test this is required
227240
func ResetFixtures(t *testing.T) {

0 commit comments

Comments
 (0)