Merge remote-tracking branch 'upstream/main' into limit-repo-size

This commit is contained in:
DmitryFrolovTri committed 2026-01-21 20:09:27 +00:00
commit 374989abcf
595 files changed
+81564 -114143

No files matched your search

+1 -4
View File
@@ -127,10 +127,7 @@ jobs:
)
// user2 approves all runs
req = NewRequestWithValues(t, "POST", dataURL,
map[string]string{
"_csrf": GetUserCSRFToken(t, user2Session),
})
req = NewRequest(t, "POST", dataURL)
user2Session.MakeRequest(t, req, http.StatusOK)
// check runs
+36 -74
View File
@@ -51,7 +51,7 @@ func TestWorkflowConcurrency(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -65,7 +65,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -79,7 +79,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
@@ -159,7 +159,7 @@ func TestWorkflowConcurrencyShort(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -172,7 +172,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -185,7 +185,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
@@ -264,7 +264,7 @@ func TestWorkflowConcurrencyShortJson(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -281,7 +281,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -298,7 +298,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
@@ -454,11 +454,7 @@ jobs:
runner.fetchNoTask(t)
// user2 approves the run
pr2Run1 := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{RepoID: baseRepo.ID, TriggerUserID: user4.ID})
req = NewRequestWithValues(t, "POST",
fmt.Sprintf("/%s/%s/actions/runs/%d/approve", baseRepo.OwnerName, baseRepo.Name, pr2Run1.Index),
map[string]string{
"_csrf": GetUserCSRFToken(t, user2Session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/approve", baseRepo.OwnerName, baseRepo.Name, pr2Run1.Index))
user2Session.MakeRequest(t, req, http.StatusOK)
// fetch the task and the previous task has been cancelled
pr2Task1 := runner.fetchTask(t)
@@ -532,7 +528,7 @@ func TestJobConcurrency(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -546,7 +542,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -554,7 +550,7 @@ jobs:
wf2-job1:
runs-on: runner2
outputs:
version: ${{ steps.version_step.outputs.app_version }}
version: ${{ steps.version_step.outputs.app_version }}
steps:
- id: version_step
run: echo "app_version=v1.23.0" >> "$GITHUB_OUTPUT"
@@ -568,7 +564,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
@@ -624,9 +620,7 @@ jobs:
assert.Equal(t, actions_model.StatusCancelled, wf2Job2ActionJob.Status)
// rerun wf2
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, wf2Run.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, wf2Run.Index))
_ = session.MakeRequest(t, req, http.StatusOK)
// (rerun1) cannot fetch wf2-job2
@@ -650,9 +644,7 @@ jobs:
assert.Equal(t, "job-main-v1.24.0", wf2Job2Rerun1Job.ConcurrencyGroup)
// rerun wf2-job2
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, wf2Run.Index, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, wf2Run.Index, 1))
_ = session.MakeRequest(t, req, http.StatusOK)
// (rerun2) fetch and exec wf2-job2
wf2Job2Rerun2Task := runner1.fetchTask(t)
@@ -684,7 +676,7 @@ func TestMatrixConcurrency(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -702,7 +694,7 @@ jobs:
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -806,7 +798,6 @@ jobs:
// run the workflow with appVersion=v1.21 and cancel=false
urlStr := fmt.Sprintf("/%s/%s/actions/run?workflow=%s", user2.Name, repo.Name, "workflow-dispatch-concurrency.yml")
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.21",
})
@@ -817,7 +808,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=false
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -828,7 +818,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=false again
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -837,7 +826,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=true
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
"cancel": "on",
@@ -900,7 +888,6 @@ jobs:
// run the workflow with appVersion=v1.21 and cancel=false
urlStr := fmt.Sprintf("/%s/%s/actions/run?workflow=%s", user2.Name, repo.Name, "workflow-dispatch-concurrency.yml")
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.21",
})
@@ -910,7 +897,6 @@ jobs:
assert.Equal(t, "workflow-dispatch-v1.21", run1.ConcurrencyGroup)
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -921,7 +907,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=false again
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -931,7 +916,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=true
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
"cancel": "on",
@@ -950,14 +934,10 @@ jobs:
// rerun cancel true scenario
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index))
_ = session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run4.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run4.Index))
_ = session.MakeRequest(t, req, http.StatusOK)
task5 := runner.fetchTask(t)
@@ -973,17 +953,13 @@ jobs:
// rerun cancel false scenario
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index))
_ = session.MakeRequest(t, req, http.StatusOK)
run2_2 := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: run2.ID})
assert.Equal(t, actions_model.StatusWaiting, run2_2.Status)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index+1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, apiRepo.Name, run2.Index+1))
_ = session.MakeRequest(t, req, http.StatusOK)
task6 := runner.fetchTask(t)
@@ -1044,7 +1020,6 @@ jobs:
// run the workflow with appVersion=v1.21 and cancel=false
urlStr := fmt.Sprintf("/%s/%s/actions/run?workflow=%s", user2.Name, repo.Name, "workflow-dispatch-concurrency.yml")
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.21",
})
@@ -1054,7 +1029,6 @@ jobs:
assert.Equal(t, "workflow-dispatch-v1.21", run1.ConcurrencyGroup)
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -1065,7 +1039,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=false again
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
})
@@ -1075,7 +1048,6 @@ jobs:
// run the workflow with appVersion=v1.22 and cancel=true
req = NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"appVersion": "v1.22",
"cancel": "on",
@@ -1094,14 +1066,10 @@ jobs:
// rerun cancel true scenario
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index, 1))
_ = session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run4.Index, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run4.Index, 1))
_ = session.MakeRequest(t, req, http.StatusOK)
task5 := runner.fetchTask(t)
@@ -1117,17 +1085,13 @@ jobs:
// rerun cancel false scenario
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index, 1))
_ = session.MakeRequest(t, req, http.StatusOK)
run2_2 := unittest.AssertExistsAndLoadBean(t, &actions_model.ActionRun{ID: run2.ID})
assert.Equal(t, actions_model.StatusWaiting, run2_2.Status)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index+1, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, apiRepo.Name, run2.Index+1, 1))
_ = session.MakeRequest(t, req, http.StatusOK)
task6 := runner.fetchTask(t)
@@ -1259,7 +1223,7 @@ func TestWorkflowAndJobConcurrency(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -1281,7 +1245,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -1303,7 +1267,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
@@ -1320,7 +1284,7 @@ jobs:
wf4TreePath := ".gitea/workflows/concurrent-workflow-4.yml"
wf4FileContent := `name: concurrent-workflow-4
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-4.yml'
@@ -1491,9 +1455,7 @@ jobs:
runner.fetchNoTask(t)
// cancel the first run
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/cancel", user2.Name, repo.Name, run1.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, user2Session),
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/cancel", user2.Name, repo.Name, run1.Index))
user2Session.MakeRequest(t, req, http.StatusOK)
// the first run has been cancelled
@@ -1525,7 +1487,7 @@ func TestAbandonConcurrentRun(t *testing.T) {
wf1TreePath := ".gitea/workflows/workflow-1.yml"
wf1FileContent := `name: Workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/workflow-1.yml'
@@ -1544,7 +1506,7 @@ jobs:
wf2TreePath := ".gitea/workflows/workflow-2.yml"
wf2FileContent := `name: Workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/workflow-2.yml'
@@ -1624,7 +1586,7 @@ func TestRunAndJobWithSameConcurrencyGroup(t *testing.T) {
wf1TreePath := ".gitea/workflows/concurrent-workflow-1.yml"
wf1FileContent := `name: concurrent-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-1.yml'
@@ -1638,7 +1600,7 @@ jobs:
`
wf2TreePath := ".gitea/workflows/concurrent-workflow-2.yml"
wf2FileContent := `name: concurrent-workflow-2
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-2.yml'
@@ -1652,7 +1614,7 @@ jobs:
`
wf3TreePath := ".gitea/workflows/concurrent-workflow-3.yml"
wf3FileContent := `name: concurrent-workflow-3
on:
on:
push:
paths:
- '.gitea/workflows/concurrent-workflow-3.yml'
+6 -18
View File
@@ -133,9 +133,7 @@ jobs:
}
for i := 0; i < len(testCase.outcomes); i++ {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/jobs/%d", user2.Name, apiRepo.Name, runIndex, i), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/jobs/%d", user2.Name, apiRepo.Name, runIndex, i))
resp := session.MakeRequest(t, req, http.StatusOK)
var listResp actions.ViewResponse
err := json.Unmarshal(resp.Body.Bytes(), &listResp)
@@ -147,30 +145,20 @@ jobs:
MakeRequest(t, req, http.StatusOK)
}
req := NewRequestWithValues(t, "GET", fmt.Sprintf("/%s/%s/actions/runs/%s", user2.Name, apiRepo.Name, runIndex), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/actions/runs/%s", user2.Name, apiRepo.Name, runIndex))
session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/delete", user2.Name, apiRepo.Name, runIndex), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/delete", user2.Name, apiRepo.Name, runIndex))
session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/delete", user2.Name, apiRepo.Name, runIndex), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/delete", user2.Name, apiRepo.Name, runIndex))
session.MakeRequest(t, req, http.StatusNotFound)
req = NewRequestWithValues(t, "GET", fmt.Sprintf("/%s/%s/actions/runs/%s", user2.Name, apiRepo.Name, runIndex), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s/actions/runs/%s", user2.Name, apiRepo.Name, runIndex))
session.MakeRequest(t, req, http.StatusNotFound)
for i := 0; i < len(testCase.outcomes); i++ {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/jobs/%d", user2.Name, apiRepo.Name, runIndex, i), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%s/jobs/%d", user2.Name, apiRepo.Name, runIndex, i))
session.MakeRequest(t, req, http.StatusNotFound)
req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s/actions/runs/%s/jobs/%d/logs", user2.Name, apiRepo.Name, runIndex, i)).
+2 -3
View File
@@ -62,9 +62,8 @@ jobs:
// run the workflow with os=windows
urlStr := fmt.Sprintf("/%s/%s/actions/run?workflow=%s", user2.Name, repo.Name, "test-inputs-context.yml")
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"ref": "refs/heads/main",
"os": "windows",
"ref": "refs/heads/main",
"os": "windows",
})
session.MakeRequest(t, req, http.StatusSeeOther)
+5 -13
View File
@@ -33,7 +33,7 @@ func TestActionsRerun(t *testing.T) {
wfTreePath := ".gitea/workflows/actions-rerun-workflow-1.yml"
wfFileContent := `name: actions-rerun-workflow-1
on:
on:
push:
paths:
- '.gitea/workflows/actions-rerun-workflow-1.yml'
@@ -59,9 +59,7 @@ jobs:
result: runnerv1.Result_RESULT_SUCCESS,
})
// RERUN-FAILURE: the run is not done
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, run.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, run.Index))
session.MakeRequest(t, req, http.StatusBadRequest)
// fetch and exec job2
job2Task := runner.fetchTask(t)
@@ -70,9 +68,7 @@ jobs:
})
// RERUN-1: rerun the run
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, run.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/rerun", user2.Name, repo.Name, run.Index))
session.MakeRequest(t, req, http.StatusOK)
// fetch and exec job1
job1TaskR1 := runner.fetchTask(t)
@@ -86,9 +82,7 @@ jobs:
})
// RERUN-2: rerun job1
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, run.Index, 0), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, run.Index, 0))
session.MakeRequest(t, req, http.StatusOK)
// job2 needs job1, so rerunning job1 will also rerun job2
// fetch and exec job1
@@ -103,9 +97,7 @@ jobs:
})
// RERUN-3: rerun job2
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, run.Index, 1), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/actions/runs/%d/jobs/%d/rerun", user2.Name, repo.Name, run.Index, 1))
session.MakeRequest(t, req, http.StatusOK)
// only job2 will rerun
// fetch and exec job2
@@ -50,16 +50,13 @@ func TestActionsRunnerModify(t *testing.T) {
doUpdate := func(t *testing.T, sess *TestSession, baseURL string, id int64, description string, expectedStatus int) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("%s/%d", baseURL, id), map[string]string{
"_csrf": GetUserCSRFToken(t, sess),
"description": description,
})
sess.MakeRequest(t, req, expectedStatus)
}
doDelete := func(t *testing.T, sess *TestSession, baseURL string, id int64, expectedStatus int) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("%s/%d/delete", baseURL, id), map[string]string{
"_csrf": GetUserCSRFToken(t, sess),
})
req := NewRequest(t, "POST", fmt.Sprintf("%s/%d/delete", baseURL, id))
sess.MakeRequest(t, req, expectedStatus)
}
+1 -4
View File
@@ -42,7 +42,6 @@ func TestActionsCollaborativeOwner(t *testing.T) {
// add user10 to the list of collaborative owners
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/actions/general/collaborative_owner/add", repo.Owner.UserName, repo.Name), map[string]string{
"_csrf": GetUserCSRFToken(t, user2Session),
"collaborative_owner": user10.Name,
})
user2Session.MakeRequest(t, req, http.StatusOK)
@@ -51,9 +50,7 @@ func TestActionsCollaborativeOwner(t *testing.T) {
doGitClone(dstPath, u)(t)
// remove user10 from the list of collaborative owners
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/actions/general/collaborative_owner/delete?id=%d", repo.Owner.UserName, repo.Name, user10.ID), map[string]string{
"_csrf": GetUserCSRFToken(t, user2Session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/settings/actions/general/collaborative_owner/delete?id=%d", repo.Owner.UserName, repo.Name, user10.ID))
user2Session.MakeRequest(t, req, http.StatusOK)
// the git clone will fail
+5 -7
View File
@@ -1614,7 +1614,7 @@ func TestPullRequestWithPathsRebase(t *testing.T) {
testCreateFile(t, session, "user2", repoName, repo.DefaultBranch, "", "dir1/dir1.txt", "1")
testCreateFile(t, session, "user2", repoName, repo.DefaultBranch, "", "dir2/dir2.txt", "2")
wfFileContent := `name: ci
on:
on:
pull_request:
paths:
- 'dir1/**'
@@ -1639,12 +1639,10 @@ jobs:
apiPull, err := doAPICreatePullRequest(apiCtx, "user2", repoName, repo.DefaultBranch, "update-dir2")(t)
runner.fetchNoTask(t)
assert.NoError(t, err)
testEditFile(t, session, "user2", repoName, repo.DefaultBranch, "dir1/dir1.txt", "11") // change the file in "dir1"
req := NewRequestWithValues(t, "POST",
fmt.Sprintf("/%s/%s/pulls/%d/update?style=rebase", "user2", repoName, apiPull.Index), // update by rebase
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
// change the file in "dir1"
testEditFile(t, session, "user2", repoName, repo.DefaultBranch, "dir1/dir1.txt", "11")
// update by rebase
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/pulls/%d/update?style=rebase", "user2", repoName, apiPull.Index))
session.MakeRequest(t, req, http.StatusSeeOther)
runner.fetchNoTask(t)
})
+3 -6
View File
@@ -50,17 +50,14 @@ func TestActionsVariables(t *testing.T) {
doUpdate := func(t *testing.T, sess *TestSession, baseURL string, id int64, data string, expectedStatus int) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("%s/%d/edit", baseURL, id), map[string]string{
"_csrf": GetUserCSRFToken(t, sess),
"name": "VAR",
"data": data,
"name": "VAR",
"data": data,
})
sess.MakeRequest(t, req, expectedStatus)
}
doDelete := func(t *testing.T, sess *TestSession, baseURL string, id int64, expectedStatus int) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("%s/%d/delete", baseURL, id), map[string]string{
"_csrf": GetUserCSRFToken(t, sess),
})
req := NewRequest(t, "POST", fmt.Sprintf("%s/%d/delete", baseURL, id))
sess.MakeRequest(t, req, expectedStatus)
}
+1 -6
View File
@@ -52,9 +52,7 @@ func testSuccessfullEdit(t *testing.T, formData user_model.User) {
func makeRequest(t *testing.T, formData user_model.User, headerCode int) {
session := loginUser(t, "user1")
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", "/-/admin/users/"+strconv.Itoa(int(formData.ID))+"/edit", map[string]string{
"_csrf": csrf,
"user_name": formData.Name,
"login_name": formData.LoginName,
"login_type": "0-0",
@@ -96,10 +94,7 @@ func TestAdminDeleteUser(t *testing.T) {
query = "?purge=true"
}
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/-/admin/users/%d/delete%s", entry.userID, query), map[string]string{
"_csrf": csrf,
})
req := NewRequest(t, "POST", fmt.Sprintf("/-/admin/users/%d/delete%s", entry.userID, query))
session.MakeRequest(t, req, http.StatusSeeOther)
assertUserDeleted(t, entry.userID)
-2
View File
@@ -95,9 +95,7 @@ func TestHTTPSigCert(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", "/user/settings/keys", map[string]string{
"_csrf": csrf,
"content": "user1",
"title": "principal",
"type": "principal",
+3 -3
View File
@@ -19,6 +19,7 @@ import (
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/modules/setting"
api "code.gitea.io/gitea/modules/structs"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
@@ -264,9 +265,8 @@ func TestAPIEditIssue(t *testing.T) {
func TestAPISearchIssues(t *testing.T) {
defer tests.PrepareTestEnv(t)()
// as this API was used in the frontend, it uses UI page size
expectedIssueCount := min(20, setting.UI.IssuePagingNum) // 20 is from the fixtures
defer test.MockVariableValue(&setting.API.DefaultPagingNum, 20)()
expectedIssueCount := 20 // 20 is from the fixtures
link, _ := url.Parse("/api/v1/repos/issues/search")
token := getUserToken(t, "user1", auth_model.AccessTokenScopeReadIssue)
+5 -32
View File
@@ -16,6 +16,7 @@ import (
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
arch_module "code.gitea.io/gitea/modules/packages/arch"
"code.gitea.io/gitea/modules/test"
arch_service "code.gitea.io/gitea/services/packages/arch"
"code.gitea.io/gitea/tests"
@@ -78,34 +79,6 @@ license = MIT`)
return buf.Bytes()
}
readIndexContent := func(r io.Reader) (map[string]string, error) {
gzr, err := gzip.NewReader(r)
if err != nil {
return nil, err
}
content := make(map[string]string)
tr := tar.NewReader(gzr)
for {
hd, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
buf, err := io.ReadAll(tr)
if err != nil {
return nil, err
}
content[hd.Name] = string(buf)
}
return content, nil
}
compressions := []string{"gz", "xz", "zst"}
repositories := []string{"main", "testing", "with/slash", ""}
@@ -204,7 +177,7 @@ license = MIT`)
req := NewRequest(t, "GET", fmt.Sprintf("%s/%s/aarch64/%s", rootURL, repository, arch_service.IndexArchiveFilename))
resp := MakeRequest(t, req, http.StatusOK)
content, err := readIndexContent(resp.Body)
content, err := test.ReadAllTarGzContent(resp.Body)
assert.NoError(t, err)
desc, has := content[fmt.Sprintf("%s-%s/desc", packageName, packageVersion)]
@@ -256,7 +229,7 @@ license = MIT`)
req = NewRequest(t, "GET", fmt.Sprintf("%s/%s/aarch64/%s", rootURL, repository, arch_service.IndexArchiveFilename))
resp := MakeRequest(t, req, http.StatusOK)
content, err := readIndexContent(resp.Body)
content, err := test.ReadAllTarGzContent(resp.Body)
assert.NoError(t, err)
desc, has := content[fmt.Sprintf("%s-%s/desc", packageName, packageVersion)]
@@ -311,7 +284,7 @@ license = MIT`)
req = NewRequest(t, "GET", fmt.Sprintf("%s/aarch64/%s", rootURL, arch_service.IndexArchiveFilename))
resp := MakeRequest(t, req, http.StatusOK)
content, err := readIndexContent(resp.Body)
content, err := test.ReadAllTarGzContent(resp.Body)
assert.NoError(t, err)
assert.Len(t, content, 2)
@@ -326,7 +299,7 @@ license = MIT`)
req = NewRequest(t, "GET", fmt.Sprintf("%s/aarch64/%s", rootURL, arch_service.IndexArchiveFilename))
resp = MakeRequest(t, req, http.StatusOK)
content, err = readIndexContent(resp.Body)
content, err = test.ReadAllTarGzContent(resp.Body)
assert.NoError(t, err)
assert.Len(t, content, 2)
_, has = content["gitea-test-1.0.0/desc"]
@@ -826,7 +826,6 @@ func TestPackageContainer(t *testing.T) {
newOwnerName := "newUsername"
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": newOwnerName,
"email": "user2@example.com",
"language": "en-US",
@@ -836,7 +835,6 @@ func TestPackageContainer(t *testing.T) {
t.Run(fmt.Sprintf("Catalog[%s]", newOwnerName), checkCatalog(newOwnerName))
req = NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": user.Name,
"email": "user2@example.com",
"language": "en-US",
+17 -2
View File
@@ -270,13 +270,20 @@ func TestAPICreatePullSuccess(t *testing.T) {
owner11 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: repo11.OwnerID})
session := loginUser(t, owner11.Name)
prTitle := "test pull request title " + time.Now().String()
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), &api.CreatePullRequestOption{
Head: owner11.Name + ":master",
Base: "master",
Title: "create a failure pr",
Title: prTitle,
}).AddTokenAuth(token)
MakeRequest(t, req, http.StatusCreated)
// Also test that AllowMaintainerEdit is false by default
prIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: prTitle})
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{IssueID: prIssue.ID})
assert.False(t, pr.AllowMaintainerEdit)
MakeRequest(t, req, http.StatusUnprocessableEntity) // second request should fail
}
@@ -290,11 +297,14 @@ func TestAPICreatePullBasePermission(t *testing.T) {
user4 := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 4})
session := loginUser(t, user4.Name)
prTitle := "test pull request title " + time.Now().String()
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
opts := &api.CreatePullRequestOption{
Head: repo11.OwnerName + ":master",
Base: "master",
Title: "create a failure pr",
Title: prTitle,
AllowMaintainerEdit: util.ToPointer(true),
}
req := NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), &opts).AddTokenAuth(token)
MakeRequest(t, req, http.StatusForbidden)
@@ -306,6 +316,11 @@ func TestAPICreatePullBasePermission(t *testing.T) {
// create again
req = NewRequestWithJSON(t, http.MethodPost, fmt.Sprintf("/api/v1/repos/%s/%s/pulls", owner10.Name, repo10.Name), &opts).AddTokenAuth(token)
MakeRequest(t, req, http.StatusCreated)
// Also test that AllowMaintainerEdit is set to true
prIssue := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{Title: prTitle})
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{IssueID: prIssue.ID})
assert.True(t, pr.AllowMaintainerEdit)
}
func TestAPICreatePullHeadPermission(t *testing.T) {
@@ -28,7 +28,6 @@ func TestRepoLanguages(t *testing.T) {
// Save new file to master branch
req = NewRequestWithValues(t, "POST", "/user2/repo1/_new/master/", map[string]string{
"_csrf": doc.GetCSRF(),
"last_commit": lastCommit,
"tree_path": "test.go",
"content": "package main",
+1
View File
@@ -317,6 +317,7 @@ func TestAPILFSBatch(t *testing.T) {
ul := br.Objects[0].Actions["upload"]
assert.NotNil(t, ul)
assert.NotEmpty(t, ul.Href)
assert.Equal(t, "chunked", ul.Header["Transfer-Encoding"], "git-lfs client needs Transfer-Encoding to do chunked transfer")
assert.Contains(t, br.Objects[0].Actions, "verify")
vl := br.Objects[0].Actions["verify"]
assert.NotNil(t, vl)
@@ -43,7 +43,6 @@ func TestAPIRepoLicense(t *testing.T) {
// Save new file to master branch
req = NewRequestWithValues(t, "POST", "/user2/repo1/_new/master/", map[string]string{
"_csrf": doc.GetCSRF(),
"last_commit": lastCommit,
"tree_path": "LICENSE",
"content": testLicenseContent,
+49 -7
View File
@@ -33,7 +33,15 @@ func testGeneratePngBytes() []byte {
return buff.Bytes()
}
func testCreateIssueAttachment(t *testing.T, session *TestSession, csrf, repoURL, filename string, content []byte, expectedStatus int) string {
func testCreateIssueAttachment(t *testing.T, session *TestSession, repoURL, filename string, content []byte, expectedStatus int) string {
return testCreateAttachment(t, session, repoURL, "issues", filename, content, expectedStatus)
}
func testCreateReleaseAttachment(t *testing.T, session *TestSession, repoURL, filename string, content []byte, expectedStatus int) string {
return testCreateAttachment(t, session, repoURL, "releases", filename, content, expectedStatus)
}
func testCreateAttachment(t *testing.T, session *TestSession, repoURL, issueOrRelease, filename string, content []byte, expectedStatus int) string {
body := &bytes.Buffer{}
// Setup multi-part
@@ -45,8 +53,7 @@ func testCreateIssueAttachment(t *testing.T, session *TestSession, csrf, repoURL
err = writer.Close()
assert.NoError(t, err)
req := NewRequestWithBody(t, "POST", repoURL+"/issues/attachments", body)
req.Header.Add("X-Csrf-Token", csrf)
req := NewRequestWithBody(t, "POST", repoURL+"/"+issueOrRelease+"/attachments", body)
req.Header.Add("Content-Type", writer.FormDataContentType())
resp := session.MakeRequest(t, req, expectedStatus)
@@ -58,12 +65,23 @@ func testCreateIssueAttachment(t *testing.T, session *TestSession, csrf, repoURL
return obj["uuid"]
}
func testDeleteIssueAttachment(t *testing.T, session *TestSession, repoURL, uuid string, expectedStatus int) {
req := NewRequestWithValues(t, "POST", repoURL+"/issues/attachments/remove", map[string]string{"file": uuid})
session.MakeRequest(t, req, expectedStatus)
}
func testDeleteReleaseAttachment(t *testing.T, session *TestSession, repoURL, uuid string, expectedStatus int) {
req := NewRequestWithValues(t, "POST", repoURL+"/releases/attachments/remove", map[string]string{"file": uuid})
session.MakeRequest(t, req, expectedStatus)
}
func TestAttachments(t *testing.T) {
defer tests.PrepareTestEnv(t)()
t.Run("CreateAnonymousAttachment", testCreateAnonymousAttachment)
t.Run("CreateUser2IssueAttachment", testCreateUser2IssueAttachment)
t.Run("UploadAttachmentDeleteTemp", testUploadAttachmentDeleteTemp)
t.Run("GetAttachment", testGetAttachment)
t.Run("DeleteAttachmentPermissions", testDeleteAttachmentPermissions)
}
func testUploadAttachmentDeleteTemp(t *testing.T) {
@@ -79,20 +97,20 @@ func testUploadAttachmentDeleteTemp(t *testing.T) {
defer web.RouteMock(route_web.RouterMockPointBeforeWebRoutes, func(resp http.ResponseWriter, req *http.Request) {
tmpFileCountDuringUpload = countTmpFile()
})()
_ = testCreateIssueAttachment(t, session, GetUserCSRFToken(t, session), "user2/repo1", "image.png", testGeneratePngBytes(), http.StatusOK)
_ = testCreateIssueAttachment(t, session, "user2/repo1", "image.png", testGeneratePngBytes(), http.StatusOK)
assert.Equal(t, 1, tmpFileCountDuringUpload, "the temp file should exist when uploaded size exceeds the parse form's max memory")
assert.Equal(t, 0, countTmpFile(), "the temp file should be deleted after upload")
}
func testCreateAnonymousAttachment(t *testing.T) {
session := emptyTestSession(t)
testCreateIssueAttachment(t, session, GetAnonymousCSRFToken(t, session), "user2/repo1", "image.png", testGeneratePngBytes(), http.StatusSeeOther)
testCreateIssueAttachment(t, session, "user2/repo1", "image.png", testGeneratePngBytes(), http.StatusSeeOther)
}
func testCreateUser2IssueAttachment(t *testing.T) {
const repoURL = "user2/repo1"
session := loginUser(t, "user2")
uuid := testCreateIssueAttachment(t, session, GetUserCSRFToken(t, session), repoURL, "image.png", testGeneratePngBytes(), http.StatusOK)
uuid := testCreateIssueAttachment(t, session, repoURL, "image.png", testGeneratePngBytes(), http.StatusOK)
req := NewRequest(t, "GET", repoURL+"/issues/new")
resp := session.MakeRequest(t, req, http.StatusOK)
@@ -102,7 +120,6 @@ func testCreateUser2IssueAttachment(t *testing.T) {
assert.True(t, exists, "The template has changed")
postData := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": "New Issue With Attachment",
"content": "some content",
"files": uuid,
@@ -159,3 +176,28 @@ func testGetAttachment(t *testing.T) {
})
}
}
func testDeleteAttachmentPermissions(t *testing.T) {
const repoURL = "user2/repo1"
ownerSession := loginUser(t, "user2")
readonlySession := loginUser(t, "user5")
issueFromOwner := testCreateIssueAttachment(t, ownerSession, repoURL, "owner-issue.png", testGeneratePngBytes(), http.StatusOK)
testDeleteIssueAttachment(t, readonlySession, repoURL, issueFromOwner, http.StatusForbidden)
issueFromReader := testCreateIssueAttachment(t, readonlySession, repoURL, "reader-issue.png", testGeneratePngBytes(), http.StatusOK)
testDeleteIssueAttachment(t, ownerSession, repoURL, issueFromReader, http.StatusOK)
testCreateReleaseAttachment(t, readonlySession, repoURL, "reader-release.png", testGeneratePngBytes(), http.StatusNotFound)
crossRepoUUID := testCreateIssueAttachment(t, ownerSession, repoURL, "cross-repo.png", testGeneratePngBytes(), http.StatusOK)
testDeleteIssueAttachment(t, ownerSession, "user2/repo2", crossRepoUUID, http.StatusBadRequest)
testDeleteIssueAttachment(t, ownerSession, repoURL, crossRepoUUID, http.StatusOK)
releaseUUID := testCreateReleaseAttachment(t, ownerSession, repoURL, "reader-release.png", testGeneratePngBytes(), http.StatusOK)
testDeleteReleaseAttachment(t, ownerSession, repoURL, releaseUUID, http.StatusOK)
// test deleting release attachment from another repo
testDeleteReleaseAttachment(t, ownerSession, "user2/repo2", crossRepoUUID, http.StatusBadRequest)
}
+5 -11
View File
@@ -125,7 +125,7 @@ type ldapAuthOptions struct {
groupTeamMapRemoval string
}
func (te *ldapTestEnv) buildAuthSourcePayload(csrf string, opts ...ldapAuthOptions) map[string]string {
func (te *ldapTestEnv) buildAuthSourcePayload(opts ...ldapAuthOptions) map[string]string {
opt := util.OptionalArg(opts)
// Modify user filter to test group filter explicitly
userFilter := "(&(objectClass=inetOrgPerson)(memberOf=cn=git,ou=people,dc=planetexpress,dc=com)(uid=%s))"
@@ -134,7 +134,6 @@ func (te *ldapTestEnv) buildAuthSourcePayload(csrf string, opts ...ldapAuthOptio
}
return map[string]string{
"_csrf": csrf,
"type": "2",
"name": "ldap",
"host": te.serverHost,
@@ -164,8 +163,7 @@ func (te *ldapTestEnv) buildAuthSourcePayload(csrf string, opts ...ldapAuthOptio
func (te *ldapTestEnv) addAuthSource(t *testing.T, opts ...ldapAuthOptions) {
session := loginUser(t, "user1")
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", te.buildAuthSourcePayload(csrf, opts...))
req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", te.buildAuthSourcePayload(opts...))
session.MakeRequest(t, req, http.StatusSeeOther)
}
@@ -212,13 +210,12 @@ func TestLDAPAuthChange(t *testing.T) {
req = NewRequest(t, "GET", href)
resp = session.MakeRequest(t, req, http.StatusOK)
doc = NewHTMLParser(t, resp.Body)
csrf := doc.GetCSRF()
host, _ := doc.Find(`input[name="host"]`).Attr("value")
assert.Equal(t, te.serverHost, host)
binddn, _ := doc.Find(`input[name="bind_dn"]`).Attr("value")
assert.Equal(t, "uid=gitea,ou=service,dc=planetexpress,dc=com", binddn)
req = NewRequestWithValues(t, "POST", href, te.buildAuthSourcePayload(csrf, ldapAuthOptions{groupTeamMapRemoval: "off"}))
req = NewRequestWithValues(t, "POST", href, te.buildAuthSourcePayload(ldapAuthOptions{groupTeamMapRemoval: "off"}))
session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", href)
@@ -267,8 +264,7 @@ func TestLDAPUserSyncWithEmptyUsernameAttribute(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
csrf := GetUserCSRFToken(t, session)
payload := te.buildAuthSourcePayload(csrf)
payload := te.buildAuthSourcePayload()
payload["attribute_username"] = ""
req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", payload)
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -285,7 +281,6 @@ func TestLDAPUserSyncWithEmptyUsernameAttribute(t *testing.T) {
for _, u := range te.gitLDAPUsers {
req := NewRequestWithValues(t, "POST", "/user/login", map[string]string{
"_csrf": csrf,
"user_name": u.UserName,
"password": u.Password,
})
@@ -512,8 +507,7 @@ func TestLDAPPreventInvalidGroupTeamMap(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user1")
csrf := GetUserCSRFToken(t, session)
payload := te.buildAuthSourcePayload(csrf, ldapAuthOptions{groupTeamMap: `{"NOT_A_VALID_JSON"["MISSING_DOUBLE_POINT"]}`, groupTeamMapRemoval: "off"})
payload := te.buildAuthSourcePayload(ldapAuthOptions{groupTeamMap: `{"NOT_A_VALID_JSON"["MISSING_DOUBLE_POINT"]}`, groupTeamMapRemoval: "off"})
req := NewRequestWithValues(t, "POST", "/-/admin/auths/new", payload)
session.MakeRequest(t, req, http.StatusOK) // StatusOK = failed, StatusSeeOther = ok
}
+1 -3
View File
@@ -61,9 +61,7 @@ func branchAction(t *testing.T, button string) (*HTMLDoc, string) {
t.Skip()
}
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
})
req = NewRequest(t, "POST", link)
session.MakeRequest(t, req, http.StatusOK)
url, err := url.Parse(link)
@@ -26,17 +26,13 @@ func TestChangeDefaultBranch(t *testing.T) {
session := loginUser(t, owner.Name)
branchesURL := fmt.Sprintf("/%s/%s/settings/branches", owner.Name, repo.Name)
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", branchesURL, map[string]string{
"_csrf": csrf,
"action": "default_branch",
"branch": "DefaultBranch",
})
session.MakeRequest(t, req, http.StatusSeeOther)
csrf = GetUserCSRFToken(t, session)
req = NewRequestWithValues(t, "POST", branchesURL, map[string]string{
"_csrf": csrf,
"action": "default_branch",
"branch": "does_not_exist",
})
@@ -110,9 +106,7 @@ func TestChangeDefaultBranchDivergence(t *testing.T) {
// switch default branch
newDefaultBranch := "good-sign-not-yet-validated"
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", settingsBranchesURL, map[string]string{
"_csrf": csrf,
"action": "default_branch",
"branch": newDefaultBranch,
})
@@ -97,9 +97,7 @@ func TestSessionFileCreation(t *testing.T) {
// We're not logged in so there should be no session
assert.False(t, sessionFileExist(t, tmpDir, sessionID))
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
"_csrf": doc.GetCSRF(),
"user_name": "user2",
"password": userPassword,
})
-34
View File
@@ -1,34 +0,0 @@
// Copyright 2017 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package integration
import (
"net/http"
"testing"
"code.gitea.io/gitea/models/unittest"
user_model "code.gitea.io/gitea/models/user"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
)
func TestCsrfProtection(t *testing.T) {
defer tests.PrepareTestEnv(t)()
// test web form csrf via form
user := unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
session := loginUser(t, user.Name)
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": "fake_csrf",
})
resp := session.MakeRequest(t, req, http.StatusBadRequest)
assert.Contains(t, resp.Body.String(), "Invalid CSRF token")
// test web form csrf via header. TODO: should use an UI api to test
req = NewRequest(t, "POST", "/user/settings")
req.Header.Add("X-Csrf-Token", "fake_csrf")
resp = session.MakeRequest(t, req, http.StatusBadRequest)
assert.Contains(t, resp.Body.String(), "Invalid CSRF token")
}
+2 -8
View File
@@ -32,11 +32,8 @@ func TestUserDeleteAccount(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user8")
csrf := GetUserCSRFToken(t, session)
urlStr := "/user/settings/account/delete?password=" + userPassword
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": csrf,
})
req := NewRequest(t, "POST", urlStr)
session.MakeRequest(t, req, http.StatusSeeOther)
assertUserDeleted(t, 8)
@@ -47,11 +44,8 @@ func TestUserDeleteAccountStillOwnRepos(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user2")
csrf := GetUserCSRFToken(t, session)
urlStr := "/user/settings/account/delete?password=" + userPassword
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{
"_csrf": csrf,
})
req := NewRequest(t, "POST", urlStr)
session.MakeRequest(t, req, http.StatusSeeOther)
// user should not have been deleted, because the user still owns repos
+1 -9
View File
@@ -87,7 +87,6 @@ func testEditorProtectedBranch(t *testing.T) {
session := loginUser(t, "user2")
// Change the "master" branch to "protected"
req := NewRequestWithValues(t, "POST", "/user2/repo1/settings/branches/edit", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"rule_name": "master",
"enable_push": "true",
})
@@ -106,7 +105,6 @@ func testEditorActionPostRequest(t *testing.T, session *TestSession, requestPath
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
form := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"last_commit": htmlDoc.GetInputValueByName("last_commit"),
}
maps.Copy(form, params)
@@ -150,7 +148,6 @@ func testEditFileToNewBranch(t *testing.T, session *TestSession, user, repo, bra
func testEditorDiffPreview(t *testing.T) {
session := loginUser(t, "user2")
req := NewRequestWithValues(t, "POST", "/user2/repo1/_preview/master/README.md", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "Hello, World (Edited)\n",
})
resp := session.MakeRequest(t, req, http.StatusOK)
@@ -200,7 +197,6 @@ func testEditorWebGitCommitEmail(t *testing.T) {
makeReq := func(t *testing.T, link string, params map[string]string, expectedUserName, expectedEmail string) *httptest.ResponseRecorder {
lastCommit := getLastCommit(t)
params["_csrf"] = GetUserCSRFToken(t, session)
params["last_commit"] = lastCommit.ID.String()
params["commit_choice"] = "direct"
req := NewRequestWithValues(t, "POST", link, params)
@@ -225,7 +221,6 @@ func testEditorWebGitCommitEmail(t *testing.T) {
uploadForm := multipart.NewWriter(body)
file, _ := uploadForm.CreateFormFile("file", name)
_, _ = io.Copy(file, strings.NewReader(content))
_ = uploadForm.WriteField("_csrf", GetUserCSRFToken(t, session))
_ = uploadForm.Close()
req := NewRequestWithBody(t, "POST", "/user2/repo1/upload-file", body)
@@ -347,7 +342,7 @@ func testForkToEditFile(t *testing.T, session *TestSession, user, owner, repo, b
assert.Contains(t, resp.Body.String(), "Fork Repository to Propose Changes")
// fork the repository
req = NewRequestWithValues(t, "POST", path.Join(owner, repo, "_fork", branch), map[string]string{"_csrf": GetUserCSRFToken(t, session)})
req = NewRequest(t, "POST", path.Join(owner, repo, "_fork", branch))
resp = session.MakeRequest(t, req, http.StatusOK)
assert.JSONEq(t, `{"redirect":""}`, resp.Body.String())
}
@@ -359,7 +354,6 @@ func testForkToEditFile(t *testing.T, session *TestSession, user, owner, repo, b
// Archive the repository
req := NewRequestWithValues(t, "POST", path.Join(user, repo, "settings"),
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"repo_name": repo,
"action": "archive",
},
@@ -374,7 +368,6 @@ func testForkToEditFile(t *testing.T, session *TestSession, user, owner, repo, b
// Unfork the repository
req = NewRequestWithValues(t, "POST", path.Join(user, repo, "settings"),
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"repo_name": repo,
"action": "convert_fork",
},
@@ -410,7 +403,6 @@ func testForkToEditFile(t *testing.T, session *TestSession, user, owner, repo, b
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
editRequestForm := map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"last_commit": htmlDoc.GetInputValueByName("last_commit"),
"tree_path": filePath,
"content": "new content in fork",
-4
View File
@@ -32,7 +32,6 @@ import (
func testAPINewFile(t *testing.T, session *TestSession, user, repo, branch, treePath, content string) {
url := fmt.Sprintf("/%s/%s/_new/%s", user, repo, branch)
req := NewRequestWithValues(t, "POST", url, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"commit_choice": "direct",
"tree_path": treePath,
"content": content,
@@ -86,7 +85,6 @@ func TestEmptyRepoAddFile(t *testing.T) {
doc := NewHTMLParser(t, resp.Body).Find(`input[name="commit_choice"]`)
assert.Empty(t, doc.AttrOr("checked", "_no_"))
req = NewRequestWithValues(t, "POST", "/user30/empty/_new/"+setting.Repository.DefaultBranch, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"commit_choice": "direct",
"tree_path": "test-file.md",
"content": "newly-added-test-file",
@@ -142,7 +140,6 @@ func TestEmptyRepoUploadFile(t *testing.T) {
body := &bytes.Buffer{}
mpForm := multipart.NewWriter(body)
_ = mpForm.WriteField("_csrf", GetUserCSRFToken(t, session))
file, _ := mpForm.CreateFormFile("file", "uploaded-file.txt")
_, _ = io.Copy(file, strings.NewReader("newly-uploaded-test-file"))
_ = mpForm.Close()
@@ -154,7 +151,6 @@ func TestEmptyRepoUploadFile(t *testing.T) {
assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), &respMap))
req = NewRequestWithValues(t, "POST", "/user30/empty/_upload/"+setting.Repository.DefaultBranch, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"commit_choice": "direct",
"files": respMap["uuid"],
"tree_path": "",
+61 -56
View File
@@ -218,45 +218,40 @@ func ensureAnonymousClone(t *testing.T, u *url.URL) {
}
func standardCommitAndPushTest(t *testing.T, dstPath string, sizes ...int) (pushedFiles []string) {
t.Run("CommitAndPushStandard", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
pushedFiles = commitAndPushTest(t, dstPath, "data-file-", sizes...)
})
return pushedFiles
defer tests.PrintCurrentTest(t)()
return commitAndPushTest(t, dstPath, "data-file-", sizes...)
}
func lfsCommitAndPushTest(t *testing.T, dstPath string, sizes ...int) (pushedFiles []string) {
t.Run("CommitAndPushLFS", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
prefix := "lfs-data-file-"
err := gitcmd.NewCommand("lfs").AddArguments("install").WithDir(dstPath).Run(t.Context())
assert.NoError(t, err)
_, _, err = gitcmd.NewCommand("lfs").AddArguments("track").AddDynamicArguments(prefix + "*").
WithDir(dstPath).RunStdString(t.Context())
assert.NoError(t, err)
err = git.AddChanges(t.Context(), dstPath, false, ".gitattributes")
assert.NoError(t, err)
err = git.CommitChanges(t.Context(), dstPath, git.CommitChangesOptions{
Committer: &git.Signature{
Email: "user2@example.com",
Name: "User Two",
When: time.Now(),
},
Author: &git.Signature{
Email: "user2@example.com",
Name: "User Two",
When: time.Now(),
},
Message: "Add LFS Tracking",
})
assert.NoError(t, err)
pushedFiles = commitAndPushTest(t, dstPath, prefix, sizes...)
t.Run("Locks", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
prefix := "lfs-data-file-"
err := gitcmd.NewCommand("lfs").AddArguments("install").WithDir(dstPath).Run(t.Context())
assert.NoError(t, err)
_, _, err = gitcmd.NewCommand("lfs").AddArguments("track").AddDynamicArguments(prefix + "*").
WithDir(dstPath).RunStdString(t.Context())
assert.NoError(t, err)
err = git.AddChanges(t.Context(), dstPath, false, ".gitattributes")
assert.NoError(t, err)
err = git.CommitChanges(t.Context(), dstPath, git.CommitChangesOptions{
Committer: &git.Signature{
Email: "user2@example.com",
Name: "User Two",
When: time.Now(),
},
Author: &git.Signature{
Email: "user2@example.com",
Name: "User Two",
When: time.Now(),
},
Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
})
assert.NoError(t, err)
pushedFiles = commitAndPushTest(t, dstPath, prefix, sizes...)
t.Run("Locks", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
lockTest(t, dstPath)
})
lockTest(t, dstPath)
})
return pushedFiles
}
@@ -594,10 +589,7 @@ type doProtectBranchOptions struct {
func doProtectBranchExt(ctx APITestContext, ruleName string, opts doProtectBranchOptions) func(t *testing.T) {
// We are going to just use the owner to set the protection.
return func(t *testing.T) {
csrf := GetUserCSRFToken(t, ctx.Session)
formData := map[string]string{
"_csrf": csrf,
"rule_name": ruleName,
"unprotected_file_patterns": opts.UnprotectedFilePatterns,
"protected_file_patterns": opts.ProtectedFilePatterns,
@@ -781,11 +773,7 @@ func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) {
func doBranchDelete(ctx APITestContext, owner, repo, branch string) func(*testing.T) {
return func(t *testing.T) {
csrf := GetUserCSRFToken(t, ctx.Session)
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/branches/delete?name=%s", url.PathEscape(owner), url.PathEscape(repo), url.QueryEscape(branch)), map[string]string{
"_csrf": csrf,
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/branches/delete?name=%s", url.PathEscape(owner), url.PathEscape(repo), url.QueryEscape(branch)))
ctx.Session.MakeRequest(t, req, http.StatusOK)
}
}
@@ -795,6 +783,11 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame, auth_model.AccessTokenScopeWriteRepository)
collaboratorCtx := NewAPITestContext(t, "user5", baseCtx.Reponame, auth_model.AccessTokenScopeWriteRepository)
readOnlyCtx := NewAPITestContext(t, "user4", baseCtx.Reponame, auth_model.AccessTokenScopeWriteRepository)
t.Run("AddAutoMergeCollaborator", doAPIAddCollaborator(*baseCtx, collaboratorCtx.Username, perm.AccessModeWrite))
t.Run("AddReadOnlyAutoMergeCollaborator", doAPIAddCollaborator(*baseCtx, readOnlyCtx.Username, perm.AccessModeRead))
// automerge will merge immediately if the PR is mergeable and there is no "status check" because no status check also means "all checks passed"
// so we must set up a status check to test the auto merge feature
@@ -826,17 +819,8 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
commitID := path.Base(commitURL)
addCommitStatus := func(status commitstatus.CommitStatusState) func(*testing.T) {
return doAPICreateCommitStatus(ctx, commitID, api.CreateStatusOption{
State: status,
TargetURL: "http://test.ci/",
Description: "",
Context: "testci",
})
}
// Call API to add Pending status for commit
t.Run("CreateStatus", addCommitStatus(commitstatus.CommitStatusPending))
t.Run("CreateStatus", doAPICreateCommitStatusTest(ctx, commitID, commitstatus.CommitStatusPending, "testci"))
// Cancel not existing auto merge
ctx.ExpectedCode = http.StatusNotFound
@@ -850,10 +834,32 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
ctx.ExpectedCode = http.StatusConflict
t.Run("AutoMergePRTwice", doAPIAutoMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index))
// Read-only collaborator still cannot cancel
readOnlyCtx.ExpectedCode = http.StatusForbidden
t.Run("CancelAutoMergePRByReadOnlyCollaboratorForbidden", doAPICancelAutoMergePullRequest(readOnlyCtx, baseCtx.Username, baseCtx.Reponame, pr.Index))
readOnlyCtx.ExpectedCode = 0
// Collaborators with merge permissions can cancel a schedule made by someone else
collaboratorCtx.ExpectedCode = http.StatusNoContent
t.Run("CancelAutoMergePRByCollaborator", doAPICancelAutoMergePullRequest(collaboratorCtx, baseCtx.Username, baseCtx.Reponame, pr.Index))
collaboratorCtx.ExpectedCode = 0
// Re-add auto merge request so the repo owner can cancel it as well
ctx.ExpectedCode = http.StatusCreated
t.Run("AutoMergePRAfterCollaboratorCancel", doAPIAutoMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index))
// Cancel auto merge request
ctx.ExpectedCode = http.StatusNoContent
t.Run("CancelAutoMergePR", doAPICancelAutoMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index))
// Collaborator can schedule but admins should still be able to cancel their schedule
collaboratorCtx.ExpectedCode = http.StatusCreated
t.Run("AutoMergePRByCollaborator", doAPIAutoMergePullRequest(collaboratorCtx, baseCtx.Username, baseCtx.Reponame, pr.Index))
collaboratorCtx.ExpectedCode = 0
ctx.ExpectedCode = http.StatusNoContent
t.Run("CancelAutoMergePRByAdmin", doAPICancelAutoMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index))
// Add auto merge request
ctx.ExpectedCode = http.StatusCreated
t.Run("AutoMergePR", doAPIAutoMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index))
@@ -865,7 +871,7 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
assert.False(t, pr.HasMerged)
// Call API to add Failure status for commit
t.Run("CreateStatus", addCommitStatus(commitstatus.CommitStatusFailure))
t.Run("CreateStatus", doAPICreateCommitStatusTest(ctx, commitID, commitstatus.CommitStatusFailure, "testci"))
// Check pr status
pr, err = doAPIGetPullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index)(t)
@@ -873,8 +879,7 @@ func doAutoPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
assert.False(t, pr.HasMerged)
// Call API to add Success status for commit
t.Run("CreateStatus", addCommitStatus(commitstatus.CommitStatusSuccess))
t.Run("CreateStatus", doAPICreateCommitStatusTest(ctx, commitID, commitstatus.CommitStatusSuccess, "testci"))
// wait to let gitea merge stuff
time.Sleep(time.Second)
@@ -229,3 +229,15 @@ func doGitPull(dstPath string, args ...string) func(*testing.T) {
assert.NoError(t, err)
}
}
// doGitRemoteArchive runs a git archive command requesting an archive from remote
// and verifies that the command did not error out and returned only normal output
func doGitRemoteArchive(remote string, args ...string) func(*testing.T) {
return func(t *testing.T) {
stdout, stderr, err := gitcmd.NewCommand("archive").AddOptionValues("--remote", remote).AddArguments(gitcmd.ToTrustedCmdArgs(args)...).
RunStdString(t.Context())
require.NoError(t, err)
assert.Empty(t, stderr)
assert.NotEmpty(t, stdout)
}
}
+8
View File
@@ -21,6 +21,7 @@ func TestGitSmartHTTP(t *testing.T) {
onGiteaRun(t, func(t *testing.T, u *url.URL) {
testGitSmartHTTP(t, u)
testRenamedRepoRedirect(t)
testGitArchiveRemote(t, u)
})
}
@@ -96,3 +97,10 @@ func testRenamedRepoRedirect(t *testing.T) {
resp = MakeRequest(t, req, http.StatusOK)
assert.Contains(t, resp.Body.String(), "65f1bf27bc3bf70f64657658635e66094edbcb4d\trefs/tags/v1.1")
}
func testGitArchiveRemote(t *testing.T, u *url.URL) {
u = u.JoinPath("user27/repo49.git")
t.Run("Fetch HEAD archive", doGitRemoteArchive(u.String(), "HEAD"))
t.Run("Fetch HEAD archive subpath", doGitRemoteArchive(u.String(), "HEAD", "test"))
t.Run("list compression options", doGitRemoteArchive(u.String(), "--list"))
}
-5
View File
@@ -37,11 +37,6 @@ func (doc *HTMLDoc) Find(selector string) *goquery.Selection {
return doc.doc.Find(selector)
}
// GetCSRF for getting CSRF token value from input
func (doc *HTMLDoc) GetCSRF() string {
return doc.GetInputValueByName("_csrf")
}
// AssertHTMLElement check if the element by selector exists or does not exist depending on checkExists
func AssertHTMLElement[T int | bool](t testing.TB, doc *HTMLDoc, selector string, checkExists T) {
sel := doc.doc.Find(selector)
+3 -26
View File
@@ -225,16 +225,11 @@ func loginUser(t testing.TB, userName string) *TestSession {
func loginUserWithPassword(t testing.TB, userName, password string) *TestSession {
t.Helper()
req := NewRequest(t, "GET", "/user/login")
resp := MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
"_csrf": doc.GetCSRF(),
req := NewRequestWithValues(t, "POST", "/user/login", map[string]string{
"user_name": userName,
"password": password,
})
resp = MakeRequest(t, req, http.StatusSeeOther)
resp := MakeRequest(t, req, http.StatusSeeOther)
ch := http.Header{}
ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
@@ -256,7 +251,6 @@ var tokenCounter int64
func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...auth.AccessTokenScope) string {
t.Helper()
urlValues := url.Values{}
urlValues.Add("_csrf", GetUserCSRFToken(t, session))
urlValues.Add("name", fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1)))
for _, scope := range scopes {
urlValues.Add("scope-dummy", string(scope)) // it only needs to start with "scope-" to be accepted
@@ -338,7 +332,7 @@ func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *Re
return &RequestWrapper{req}
}
const NoExpectedStatus = -1
const NoExpectedStatus = 0
func MakeRequest(t testing.TB, rw *RequestWrapper, expectedStatus int) *httptest.ResponseRecorder {
t.Helper()
@@ -436,20 +430,3 @@ func VerifyJSONSchema(t testing.TB, resp *httptest.ResponseRecorder, schemaFile
assert.Empty(t, result.Errors())
assert.True(t, result.Valid())
}
// GetUserCSRFToken returns CSRF token for current user
func GetUserCSRFToken(t testing.TB, session *TestSession) string {
t.Helper()
cookie := session.GetSiteCookie("_csrf")
require.NotEmpty(t, cookie)
return cookie
}
// GetUserCSRFToken returns CSRF token for anonymous user (not logged in)
func GetAnonymousCSRFToken(t testing.TB, session *TestSession) string {
t.Helper()
resp := session.MakeRequest(t, NewRequest(t, "GET", "/user/login"), http.StatusOK)
csrfToken := NewHTMLParser(t, resp.Body).GetCSRF()
require.NotEmpty(t, csrfToken)
return csrfToken
}
+8 -39
View File
@@ -130,7 +130,6 @@ func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content
link, exists := htmlDoc.doc.Find("form.ui.form").Attr("action")
assert.True(t, exists, "The template has changed")
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": title,
"content": content,
})
@@ -150,15 +149,12 @@ func testNewIssue(t *testing.T, session *TestSession, user, repo, title, content
}
func testIssueDelete(t *testing.T, session *TestSession, issueURL string) {
req := NewRequestWithValues(t, "POST", path.Join(issueURL, "delete"), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", path.Join(issueURL, "delete"))
session.MakeRequest(t, req, http.StatusSeeOther)
}
func testIssueAssign(t *testing.T, session *TestSession, repoLink string, issueID, assigneeID int64) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf(repoLink+"/issues/assignee?issue_ids=%d", issueID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"id": strconv.FormatInt(assigneeID, 10),
"action": "", // empty action means assign
})
@@ -176,7 +172,6 @@ func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content,
commentCount := htmlDoc.doc.Find(".comment-list .comment .render-content").Length()
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"content": content,
"status": status,
})
@@ -200,8 +195,7 @@ func testIssueAddComment(t *testing.T, session *TestSession, issueURL, content,
func testIssueChangeMilestone(t *testing.T, session *TestSession, repoLink string, issueID, milestoneID int64) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf(repoLink+"/issues/milestone?issue_ids=%d", issueID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"id": strconv.FormatInt(milestoneID, 10),
"id": strconv.FormatInt(milestoneID, 10),
})
resp := session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, `{"ok":true}`, strings.TrimSpace(resp.Body.String()))
@@ -219,21 +213,18 @@ func TestEditIssue(t *testing.T) {
issueURL := testNewIssue(t, session, "user2", "repo1", "Title", "Description")
req := NewRequestWithValues(t, "POST", issueURL+"/content", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "modified content",
"context": fmt.Sprintf("/%s/%s", "user2", "repo1"),
})
session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", issueURL+"/content", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "modified content",
"context": fmt.Sprintf("/%s/%s", "user2", "repo1"),
})
session.MakeRequest(t, req, http.StatusBadRequest)
req = NewRequestWithValues(t, "POST", issueURL+"/content", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": "modified content",
"content_version": "1",
"context": fmt.Sprintf("/%s/%s", "user2", "repo1"),
@@ -267,13 +258,9 @@ func TestIssueCommentDelete(t *testing.T) {
assert.Equal(t, comment1, comment.Content)
// Using the ID of a comment that does not belong to the repository must fail
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d/delete", "user5", "repo4", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", fmt.Sprintf("/%s/%s/comments/%d/delete", "user5", "repo4", commentID))
session.MakeRequest(t, req, http.StatusNotFound)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d/delete", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", fmt.Sprintf("/%s/%s/comments/%d/delete", "user2", "repo1", commentID))
session.MakeRequest(t, req, http.StatusOK)
unittest.AssertNotExistsBean(t, &issues_model.Comment{ID: commentID})
}
@@ -292,13 +279,11 @@ func TestIssueCommentUpdate(t *testing.T) {
// Using the ID of a comment that does not belong to the repository must fail
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user5", "repo4", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
})
session.MakeRequest(t, req, http.StatusNotFound)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
})
session.MakeRequest(t, req, http.StatusOK)
@@ -320,7 +305,6 @@ func TestIssueCommentUpdateSimultaneously(t *testing.T) {
modifiedContent := comment.Content + "MODIFIED"
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
})
session.MakeRequest(t, req, http.StatusOK)
@@ -328,13 +312,11 @@ func TestIssueCommentUpdateSimultaneously(t *testing.T) {
modifiedContent = comment.Content + "2"
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
})
session.MakeRequest(t, req, http.StatusBadRequest)
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
"content_version": "1",
})
@@ -350,22 +332,15 @@ func TestIssueReaction(t *testing.T) {
session := loginUser(t, "user2")
issueURL := testNewIssue(t, session, "user2", "repo1", "Title", "Description")
req := NewRequest(t, "GET", issueURL)
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", path.Join(issueURL, "/reactions/react"), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
req := NewRequestWithValues(t, "POST", path.Join(issueURL, "/reactions/react"), map[string]string{
"content": "8ball",
})
session.MakeRequest(t, req, http.StatusInternalServerError)
req = NewRequestWithValues(t, "POST", path.Join(issueURL, "/reactions/react"), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"content": "eyes",
})
session.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithValues(t, "POST", path.Join(issueURL, "/reactions/unreact"), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"content": "eyes",
})
session.MakeRequest(t, req, http.StatusOK)
@@ -459,14 +434,8 @@ func testIssueWithBean(t *testing.T, user string, repoID int64, title, content s
func testIssueChangeInfo(t *testing.T, user, issueURL, info, value string) {
session := loginUser(t, user)
req := NewRequest(t, "GET", issueURL)
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", path.Join(issueURL, info), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
info: value,
req := NewRequestWithValues(t, "POST", path.Join(issueURL, info), map[string]string{
info: value,
})
_ = session.MakeRequest(t, req, http.StatusOK)
}
@@ -700,7 +669,7 @@ func TestUpdateIssueDeadline(t *testing.T) {
assert.Equal(t, api.StateOpen, issueBefore.State())
session := loginUser(t, owner.Name)
urlStr := fmt.Sprintf("%s/%s/issues/%d/deadline?_csrf=%s", owner.Name, repoBefore.Name, issueBefore.Index, GetUserCSRFToken(t, session))
urlStr := fmt.Sprintf("%s/%s/issues/%d/deadline", owner.Name, repoBefore.Name, issueBefore.Index)
req := NewRequestWithValues(t, "POST", urlStr, map[string]string{"deadline": "2022-04-06"})
session.MakeRequest(t, req, http.StatusOK)
-1
View File
@@ -95,7 +95,6 @@ func TestMigrateGiteaForm(t *testing.T) {
// Step 4: submit the migration to only migrate issues
migratedRepoName := "otherrepo"
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"service": fmt.Sprintf("%d", structs.GiteaService),
"clone_addr": fmt.Sprintf("%s%s/%s", u, ownerName, repoName),
"auth_token": token,
-3
View File
@@ -79,7 +79,6 @@ func testMirrorPush(t *testing.T, u *url.URL) {
func testCreatePushMirror(t *testing.T, session *TestSession, owner, repo, address, username, password, interval string) {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings", url.PathEscape(owner), url.PathEscape(repo)), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"action": "push-mirror-add",
"push_mirror_address": address,
"push_mirror_username": username,
@@ -94,7 +93,6 @@ func testCreatePushMirror(t *testing.T, session *TestSession, owner, repo, addre
func doRemovePushMirror(t *testing.T, session *TestSession, owner, repo string, pushMirrorID int64) bool {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings", url.PathEscape(owner), url.PathEscape(repo)), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"action": "push-mirror-remove",
"push_mirror_id": strconv.FormatInt(pushMirrorID, 10),
})
@@ -105,7 +103,6 @@ func doRemovePushMirror(t *testing.T, session *TestSession, owner, repo string,
func doUpdatePushMirror(t *testing.T, session *TestSession, owner, repo string, pushMirrorID int64, interval string) bool {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings", owner, repo), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"action": "push-mirror-update",
"push_mirror_id": strconv.FormatInt(pushMirrorID, 10),
"push_mirror_interval": interval,
@@ -17,9 +17,7 @@ import (
func setDefaultBranch(t *testing.T, session *TestSession, user, repo, branch string) {
location := path.Join("/", user, repo, "settings/branches")
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", location, map[string]string{
"_csrf": csrf,
"action": "default_branch",
"branch": branch,
})
-1
View File
@@ -92,7 +92,6 @@ func TestAuthorizeShow(t *testing.T) {
htmlDoc := NewHTMLParser(t, resp.Body)
AssertHTMLElement(t, htmlDoc, "#authorize-app", true)
htmlDoc.GetCSRF()
}
func TestAuthorizeRedirectWithExistingGrant(t *testing.T) {
-2
View File
@@ -34,7 +34,6 @@ func TestOrgProjectAccess(t *testing.T) {
// change the org's visibility to private
session := loginUser(t, "user2")
req = NewRequestWithValues(t, "POST", "/org/org3/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": "org3",
"visibility": "2",
})
@@ -48,7 +47,6 @@ func TestOrgProjectAccess(t *testing.T) {
// disable team1's project unit
session = loginUser(t, "user2")
req = NewRequestWithValues(t, "POST", "/org/org3/teams/team1/edit", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"team_name": "team1",
"repo_access": "specific",
"permission": "read",
+5 -26
View File
@@ -39,9 +39,7 @@ func TestOrgTeamEmailInvite(t *testing.T) {
session := loginUser(t, "user1")
teamURL := fmt.Sprintf("/org/%s/teams/%s", org.Name, team.Name)
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", teamURL+"/action/add", map[string]string{
"_csrf": csrf,
"uid": "1",
"uname": user.Email,
})
@@ -58,10 +56,7 @@ func TestOrgTeamEmailInvite(t *testing.T) {
// join the team
inviteURL := "/org/invite/" + invites[0].Token
csrf = GetUserCSRFToken(t, session)
req = NewRequestWithValues(t, "POST", inviteURL, map[string]string{
"_csrf": csrf,
})
req = NewRequest(t, "POST", inviteURL)
resp = session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", test.RedirectURL(resp))
session.MakeRequest(t, req, http.StatusOK)
@@ -93,7 +88,6 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) {
teamURL := fmt.Sprintf("/org/%s/teams/%s", org.Name, team.Name)
req := NewRequestWithValues(t, "POST", teamURL+"/action/add", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"uid": "1",
"uname": user.Email,
})
@@ -111,9 +105,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) {
req = NewRequest(t, "GET", "/user/login?redirect_to="+url.QueryEscape(inviteURL))
resp = MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
"_csrf": doc.GetCSRF(),
"user_name": "user5",
"password": "password",
})
@@ -135,9 +127,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUser(t *testing.T) {
session.jar.SetCookies(baseURL, cr.Cookies())
// make the request
req = NewRequestWithValues(t, "POST", test.RedirectURL(resp), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", test.RedirectURL(resp))
resp = session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", test.RedirectURL(resp))
session.MakeRequest(t, req, http.StatusOK)
@@ -164,7 +154,6 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) {
teamURL := fmt.Sprintf("/org/%s/teams/%s", org.Name, team.Name)
req := NewRequestWithValues(t, "POST", teamURL+"/action/add", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"uid": "1",
"uname": "doesnotexist@example.com",
})
@@ -182,9 +171,7 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) {
req = NewRequest(t, "GET", "/user/sign_up?redirect_to="+url.QueryEscape(inviteURL))
resp = MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/sign_up", map[string]string{
"_csrf": doc.GetCSRF(),
"user_name": "doesnotexist",
"email": "doesnotexist@example.com",
"password": "examplePassword!1",
@@ -208,9 +195,7 @@ func TestOrgTeamEmailInviteRedirectsNewUser(t *testing.T) {
session.jar.SetCookies(baseURL, cr.Cookies())
// make the redirected request
req = NewRequestWithValues(t, "POST", test.RedirectURL(resp), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", test.RedirectURL(resp))
resp = session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", test.RedirectURL(resp))
session.MakeRequest(t, req, http.StatusOK)
@@ -243,7 +228,6 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {
teamURL := fmt.Sprintf("/org/%s/teams/%s", org.Name, team.Name)
req := NewRequestWithValues(t, "POST", teamURL+"/action/add", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"uid": "1",
"uname": "doesnotexist@example.com",
})
@@ -283,9 +267,7 @@ func TestOrgTeamEmailInviteRedirectsNewUserWithActivation(t *testing.T) {
// should be redirected to accept the invite
assert.Equal(t, inviteURL, test.RedirectURL(resp))
req = NewRequestWithValues(t, "POST", test.RedirectURL(resp), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", test.RedirectURL(resp))
resp = session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", test.RedirectURL(resp))
session.MakeRequest(t, req, http.StatusOK)
@@ -319,7 +301,6 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) {
teamURL := fmt.Sprintf("/org/%s/teams/%s", org.Name, team.Name)
req := NewRequestWithValues(t, "POST", teamURL+"/action/add", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"uid": "1",
"uname": user.Email,
})
@@ -342,9 +323,7 @@ func TestOrgTeamEmailInviteRedirectsExistingUserWithLogin(t *testing.T) {
assert.Equal(t, inviteURL, test.RedirectURL(resp))
// make the request
req = NewRequestWithValues(t, "POST", test.RedirectURL(resp), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", test.RedirectURL(resp))
resp = session.MakeRequest(t, req, http.StatusSeeOther)
req = NewRequest(t, "GET", test.RedirectURL(resp))
session.MakeRequest(t, req, http.StatusOK)
@@ -48,7 +48,6 @@ func testPrivateActivityDoSomethingForActionEntries(t *testing.T) {
func testPrivateActivityHelperEnablePrivateActivity(t *testing.T) {
session := loginUser(t, privateActivityTestUser)
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": privateActivityTestUser,
"email": privateActivityTestUser + "@example.com",
"language": "en-US",
+2 -3
View File
@@ -63,10 +63,9 @@ func TestMoveRepoProjectColumns(t *testing.T) {
sess := loginUser(t, "user1")
req := NewRequest(t, "GET", fmt.Sprintf("/%s/projects/%d", repo2.FullName(), project1.ID))
resp := sess.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
sess.MakeRequest(t, req, http.StatusOK)
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s/projects/%d/move?_csrf="+htmlDoc.GetCSRF(), repo2.FullName(), project1.ID), map[string]any{
req = NewRequestWithJSON(t, "POST", fmt.Sprintf("/%s/projects/%d/move", repo2.FullName(), project1.ID), map[string]any{
"columns": []map[string]any{
{"columnID": columns[1].ID, "sorting": 0},
{"columnID": columns[2].ID, "sorting": 1},
-1
View File
@@ -89,7 +89,6 @@ func testPullCommentRetarget(t *testing.T, u *url.URL, session *TestSession) {
// do retarget
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/user2/repo1/pull/%d/target_branch", prIssue.PullRequest.Index), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"target_branch": "test-branch/retarget-no-conflict",
})
session.MakeRequest(t, req, http.StatusOK)
-2
View File
@@ -133,7 +133,6 @@ func TestPullCompare_EnableAllowEditsFromMaintainer(t *testing.T) {
dataURL, exists := htmlDoc.doc.Find("#allow-edits-from-maintainers").Attr("data-url")
assert.True(t, exists)
req := NewRequestWithValues(t, "POST", dataURL+"/set_allow_maintainer_edit", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"allow_maintainer_edit": "true",
})
user4Session.MakeRequest(t, req, http.StatusOK)
@@ -159,7 +158,6 @@ func TestPullCompare_EnableAllowEditsFromMaintainer(t *testing.T) {
lastCommit := htmlDoc.GetInputValueByName("last_commit")
assert.NotEmpty(t, lastCommit)
req := NewRequestWithValues(t, "POST", editFileLink, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"last_commit": lastCommit,
"tree_path": "README.md",
"content": "File is edited by the maintainer user2",
+3 -18
View File
@@ -59,7 +59,6 @@ func testPullCreate(t *testing.T, session *TestSession, user, repo string, toSel
link, exists = htmlDoc.doc.Find("form.ui.form").Attr("action")
assert.True(t, exists, "The template has changed")
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": title,
})
resp = session.MakeRequest(t, req, http.StatusOK)
@@ -103,7 +102,6 @@ func testPullCreateDirectly(t *testing.T, session *TestSession, opts createPullR
link, exists := htmlDoc.doc.Find("form.ui.form").Attr("action")
assert.True(t, exists, "The template has changed")
params := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": opts.Title,
}
if opts.ReviewerIDs != "" {
@@ -131,7 +129,6 @@ func testPullCreateFailure(t *testing.T, session *TestSession, baseRepoOwner, ba
link, exists := htmlDoc.doc.Find("form.ui.form").Attr("action")
assert.True(t, exists, "The template has changed")
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": title,
})
resp = session.MakeRequest(t, req, http.StatusBadRequest)
@@ -159,7 +156,6 @@ func TestPullCreate(t *testing.T) {
// test create the pull request again and it should fail now
link := "/user2/repo1/compare/master...user1/repo1:master"
req := NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"title": "This is a pull title",
})
session.MakeRequest(t, req, http.StatusBadRequest)
@@ -200,7 +196,6 @@ func TestPullCreate_TitleEscape(t *testing.T) {
assert.True(t, exists, "The template has changed")
req = NewRequestWithValues(t, "POST", editTestTitleURL, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"title": "<u>XSS PR</u>",
})
session.MakeRequest(t, req, http.StatusOK)
@@ -219,25 +214,15 @@ func TestPullCreate_TitleEscape(t *testing.T) {
func testUIDeleteBranch(t *testing.T, session *TestSession, ownerName, repoName, branchName string) {
relURL := "/" + path.Join(ownerName, repoName, "branches")
req := NewRequest(t, "GET", relURL)
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", relURL+"/delete", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"name": branchName,
req := NewRequestWithValues(t, "POST", relURL+"/delete", map[string]string{
"name": branchName,
})
session.MakeRequest(t, req, http.StatusOK)
}
func testDeleteRepository(t *testing.T, session *TestSession, ownerName, repoName string) {
relURL := "/" + path.Join(ownerName, repoName, "settings")
req := NewRequest(t, "GET", relURL)
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", relURL+"?action=delete", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
req := NewRequestWithValues(t, "POST", relURL+"?action=delete", map[string]string{
"repo_name": repoName,
})
session.MakeRequest(t, req, http.StatusSeeOther)
+20 -56
View File
@@ -51,38 +51,27 @@ type MergeOptions struct {
DeleteBranch bool
}
func testPullMerge(t *testing.T, session *TestSession, user, repo, pullnum string, mergeOptions MergeOptions) *httptest.ResponseRecorder {
req := NewRequest(t, "GET", path.Join(user, repo, "pulls", pullnum))
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
link := path.Join(user, repo, "pulls", pullnum, "merge")
func testPullMerge(t *testing.T, session *TestSession, user, repo, pullNum string, mergeOptions MergeOptions) *httptest.ResponseRecorder {
options := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"do": string(mergeOptions.Style),
"head_commit_id": mergeOptions.HeadCommitID,
"do": string(mergeOptions.Style),
"head_commit_id": mergeOptions.HeadCommitID,
"delete_branch_after_merge": util.Iif(mergeOptions.DeleteBranch, "on", ""),
}
var resp *httptest.ResponseRecorder
require.Eventually(t, func() bool {
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/pulls/%s/merge", user, repo, pullNum), options)
resp = session.MakeRequest(t, req, NoExpectedStatus)
return resp.Code == http.StatusOK
}, 5*time.Second, 50*time.Millisecond, "Timed out waiting for pull merge to succeed")
if mergeOptions.DeleteBranch {
options["delete_branch_after_merge"] = "on"
}
redirect := test.RedirectURL(resp)
assert.Equal(t, fmt.Sprintf("/%s/%s/pulls/%s", user, repo, pullNum), redirect)
req = NewRequestWithValues(t, "POST", link, options)
resp = session.MakeRequest(t, req, http.StatusOK)
respJSON := struct {
Redirect string
}{}
DecodeJSON(t, resp, &respJSON)
assert.Equal(t, fmt.Sprintf("/%s/%s/pulls/%s", user, repo, pullnum), respJSON.Redirect)
pullnumInt, err := strconv.ParseInt(pullnum, 10, 64)
pullNumInt, err := strconv.ParseInt(pullNum, 10, 64)
assert.NoError(t, err)
repository, err := repo_model.GetRepositoryByOwnerAndName(t.Context(), user, repo)
assert.NoError(t, err)
pull, err := issues_model.GetPullRequestByIndex(t.Context(), repository.ID, pullnumInt)
pull, err := issues_model.GetPullRequestByIndex(t.Context(), repository.ID, pullNumInt)
assert.NoError(t, err)
assert.True(t, pull.HasMerged)
@@ -97,9 +86,7 @@ func testPullCleanUp(t *testing.T, session *TestSession, user, repo, pullnum str
htmlDoc := NewHTMLParser(t, resp.Body)
link, exists := htmlDoc.doc.Find(".timeline-item .delete-branch-after-merge").Attr("data-url")
assert.True(t, exists, "The template has changed, can not find delete button url")
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
})
req = NewRequest(t, "POST", link)
resp = session.MakeRequest(t, req, http.StatusOK)
return resp
@@ -844,11 +831,8 @@ func TestPullAutoMergeAfterCommitStatusSucceed(t *testing.T) {
HeadBranch: "master",
})
// add protected branch for commit status
csrf := GetUserCSRFToken(t, session)
// Change the "master" branch to "protected"
req := NewRequestWithValues(t, "POST", "/user2/repo1/settings/branches/edit", map[string]string{
"_csrf": csrf,
"rule_name": "master",
"enable_push": "true",
"enable_status_check": "true",
@@ -937,11 +921,8 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApproval(t *testing.T) {
HeadBranch: "master",
})
// add protected branch for commit status
csrf := GetUserCSRFToken(t, session)
// Change master branch to protected
req := NewRequestWithValues(t, "POST", "/user2/repo1/settings/branches/edit", map[string]string{
"_csrf": csrf,
"rule_name": "master",
"enable_push": "true",
"enable_status_check": "true",
@@ -993,10 +974,7 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApproval(t *testing.T) {
// approve the PR from non-author
approveSession := loginUser(t, "user2")
req = NewRequest(t, "GET", fmt.Sprintf("/user2/repo1/pulls/%d", pr.Index))
resp := approveSession.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
testSubmitReview(t, approveSession, htmlDoc.GetCSRF(), "user2", "repo1", strconv.Itoa(int(pr.Index)), sha, "approve", http.StatusOK)
testSubmitReview(t, approveSession, "user2", "repo1", strconv.Itoa(int(pr.Index)), sha, "approve", http.StatusOK)
time.Sleep(2 * time.Second)
@@ -1042,20 +1020,16 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing.
})
assert.NoError(t, err)
stderrBuf := &bytes.Buffer{}
err = gitcmd.NewCommand("push", "origin", "HEAD:refs/for/master", "-o").
_, stderr, err := gitcmd.NewCommand("push", "origin", "HEAD:refs/for/master", "-o").
AddDynamicArguments(`topic=test/head2`).
AddArguments("-o").
AddDynamicArguments(`title="create a test pull request with agit"`).
AddArguments("-o").
AddDynamicArguments(`description="This PR is a test pull request which created with agit"`).
WithDir(dstPath).
WithStderr(stderrBuf).
Run(t.Context())
RunStdString(t.Context())
assert.NoError(t, err)
assert.Contains(t, stderrBuf.String(), setting.AppURL+"user2/repo1/pulls/6")
assert.Contains(t, stderr, setting.AppURL+"user2/repo1/pulls/6")
baseRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{OwnerName: "user2", Name: "repo1"})
pr := unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{
@@ -1067,11 +1041,8 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing.
})
session := loginUser(t, "user1")
// add protected branch for commit status
csrf := GetUserCSRFToken(t, session)
// Change master branch to protected
req := NewRequestWithValues(t, "POST", "/user2/repo1/settings/branches/edit", map[string]string{
"_csrf": csrf,
"rule_name": "master",
"enable_push": "true",
"enable_status_check": "true",
@@ -1122,10 +1093,7 @@ func TestPullAutoMergeAfterCommitStatusSucceedAndApprovalForAgitFlow(t *testing.
// approve the PR from non-author
approveSession := loginUser(t, "user1")
req = NewRequest(t, "GET", fmt.Sprintf("/user2/repo1/pulls/%d", pr.Index))
resp := approveSession.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
testSubmitReview(t, approveSession, htmlDoc.GetCSRF(), "user2", "repo1", strconv.Itoa(int(pr.Index)), sha, "approve", http.StatusOK)
testSubmitReview(t, approveSession, "user2", "repo1", strconv.Itoa(int(pr.Index)), sha, "approve", http.StatusOK)
// reload pr again
pr = unittest.AssertExistsAndLoadBean(t, &issues_model.PullRequest{ID: pr.ID})
@@ -1156,11 +1124,8 @@ func TestPullNonMergeForAdminWithBranchProtection(t *testing.T) {
HeadBranch: "master",
})
// add protected branch for commit status
csrf := GetUserCSRFToken(t, session)
// Change master branch to protected
pbCreateReq := NewRequestWithValues(t, "POST", "/user2/repo1/settings/branches/edit", map[string]string{
"_csrf": csrf,
"rule_name": "master",
"enable_push": "true",
"enable_status_check": "true",
@@ -1172,7 +1137,6 @@ func TestPullNonMergeForAdminWithBranchProtection(t *testing.T) {
token := getTokenForLoggedInUser(t, session, auth_model.AccessTokenScopeWriteRepository)
mergeReq := NewRequestWithValues(t, "POST", "/api/v1/repos/user2/repo1/pulls/6/merge", map[string]string{
"_csrf": csrf,
"head_commit_id": "",
"merge_when_checks_succeed": "false",
"force_merge": "true",
+6 -22
View File
@@ -233,16 +233,11 @@ func TestPullView_GivenApproveOrRejectReviewOnClosedPR(t *testing.T) {
DeleteBranch: false,
})
// Grab the CSRF token.
req := NewRequest(t, "GET", path.Join(elem[1], elem[2], "pulls", elem[4]))
resp = user2Session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
// Submit an approve review on the PR.
testSubmitReview(t, user2Session, htmlDoc.GetCSRF(), "user2", "repo1", elem[4], "", "approve", http.StatusUnprocessableEntity)
testSubmitReview(t, user2Session, "user2", "repo1", elem[4], "", "approve", http.StatusUnprocessableEntity)
// Submit a reject review on the PR.
testSubmitReview(t, user2Session, htmlDoc.GetCSRF(), "user2", "repo1", elem[4], "", "reject", http.StatusUnprocessableEntity)
testSubmitReview(t, user2Session, "user2", "repo1", elem[4], "", "reject", http.StatusUnprocessableEntity)
})
t.Run("Submit approve/reject review on closed PR", func(t *testing.T) {
@@ -253,23 +248,17 @@ func TestPullView_GivenApproveOrRejectReviewOnClosedPR(t *testing.T) {
assert.Equal(t, "pulls", elem[3])
testIssueClose(t, user1Session, elem[1], elem[2], elem[4])
// Grab the CSRF token.
req := NewRequest(t, "GET", path.Join(elem[1], elem[2], "pulls", elem[4]))
resp = user2Session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
// Submit an approve review on the PR.
testSubmitReview(t, user2Session, htmlDoc.GetCSRF(), "user2", "repo1", elem[4], "", "approve", http.StatusUnprocessableEntity)
testSubmitReview(t, user2Session, "user2", "repo1", elem[4], "", "approve", http.StatusUnprocessableEntity)
// Submit a reject review on the PR.
testSubmitReview(t, user2Session, htmlDoc.GetCSRF(), "user2", "repo1", elem[4], "", "reject", http.StatusUnprocessableEntity)
testSubmitReview(t, user2Session, "user2", "repo1", elem[4], "", "reject", http.StatusUnprocessableEntity)
})
})
}
func testSubmitReview(t *testing.T, session *TestSession, csrf, owner, repo, pullNumber, commitID, reviewType string, expectedSubmitStatus int) *httptest.ResponseRecorder {
func testSubmitReview(t *testing.T, session *TestSession, owner, repo, pullNumber, commitID, reviewType string, expectedSubmitStatus int) *httptest.ResponseRecorder {
options := map[string]string{
"_csrf": csrf,
"commit_id": commitID,
"content": "test",
"type": reviewType,
@@ -281,17 +270,12 @@ func testSubmitReview(t *testing.T, session *TestSession, csrf, owner, repo, pul
}
func testIssueClose(t *testing.T, session *TestSession, owner, repo, issueNumber string) *httptest.ResponseRecorder {
req := NewRequest(t, "GET", path.Join(owner, repo, "pulls", issueNumber))
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
closeURL := path.Join(owner, repo, "issues", issueNumber, "comments")
options := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"status": "close",
}
req = NewRequestWithValues(t, "POST", closeURL, options)
req := NewRequestWithValues(t, "POST", closeURL, options)
return session.MakeRequest(t, req, http.StatusOK)
}
+9 -21
View File
@@ -34,7 +34,6 @@ func TestPullCreate_CommitStatus(t *testing.T) {
url := path.Join("user1", "repo1", "compare", "master...status1")
req := NewRequestWithValues(t, "POST", url,
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"title": "pull request from status1",
},
)
@@ -77,12 +76,7 @@ func TestPullCreate_CommitStatus(t *testing.T) {
// Update commit status, and check if icon is updated as well
for _, status := range statusList {
// Call API to add status for commit
t.Run("CreateStatus", doAPICreateCommitStatus(testCtx, commitID, api.CreateStatusOption{
State: status,
TargetURL: "http://test.ci/",
Description: "",
Context: "testci",
}))
t.Run("CreateStatus", doAPICreateCommitStatusTest(testCtx, commitID, status, "testci"))
req = NewRequest(t, "GET", "/user1/repo1/pulls/1/commits")
resp = session.MakeRequest(t, req, http.StatusOK)
@@ -104,19 +98,15 @@ func TestPullCreate_CommitStatus(t *testing.T) {
})
}
func doAPICreateCommitStatus(ctx APITestContext, commitID string, data api.CreateStatusOption) func(*testing.T) {
func doAPICreateCommitStatusTest(ctx APITestContext, ref string, state commitstatus.CommitStatusState, statusContext string) func(*testing.T) {
return func(t *testing.T) {
req := NewRequestWithJSON(
t,
http.MethodPost,
fmt.Sprintf("/api/v1/repos/%s/%s/statuses/%s", ctx.Username, ctx.Reponame, commitID),
data,
).AddTokenAuth(ctx.Token)
if ctx.ExpectedCode != 0 {
ctx.Session.MakeRequest(t, req, ctx.ExpectedCode)
return
}
ctx.Session.MakeRequest(t, req, http.StatusCreated)
link := fmt.Sprintf("/api/v1/repos/%s/%s/statuses/%s", ctx.Username, ctx.Reponame, url.PathEscape(ref))
req := NewRequestWithJSON(t, http.MethodPost, link, api.CreateStatusOption{
State: state,
TargetURL: "http://test.ci/",
Context: statusContext,
}).AddTokenAuth(ctx.Token)
ctx.Session.MakeRequest(t, req, ctx.ExpectedCode)
}
}
@@ -134,7 +124,6 @@ func TestPullCreate_EmptyChangesWithDifferentCommits(t *testing.T) {
url := path.Join("user1", "repo1", "compare", "master...status1")
req := NewRequestWithValues(t, "POST", url,
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"title": "pull request from status1",
},
)
@@ -157,7 +146,6 @@ func TestPullCreate_EmptyChangesWithSameCommits(t *testing.T) {
url := path.Join("user1", "repo1", "compare", "master...status1")
req := NewRequestWithValues(t, "POST", url,
map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"title": "pull request from status1",
},
)
-1
View File
@@ -28,7 +28,6 @@ func createNewRelease(t *testing.T, session *TestSession, repoURL, tag, title st
assert.True(t, exists, "The template has changed")
postData := map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"tag_name": tag,
"tag_target": "master",
"title": title,
+9 -21
View File
@@ -27,14 +27,9 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// get branch setting page
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user2/repo1/branches")
resp := session.MakeRequest(t, req, http.StatusOK)
htmlDoc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/rename", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"from": "master",
"to": "main",
req := NewRequestWithValues(t, "POST", "/user2/repo1/branches/rename", map[string]string{
"from": "master",
"to": "main",
})
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -44,7 +39,7 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// check old branch link
req = NewRequestWithValues(t, "GET", "/user2/repo1/src/branch/master/README.md", nil)
resp = session.MakeRequest(t, req, http.StatusSeeOther)
resp := session.MakeRequest(t, req, http.StatusSeeOther)
location := resp.Header().Get("Location")
assert.Equal(t, "/user2/repo1/src/branch/main/README.md", location)
@@ -53,10 +48,7 @@ func testRenameBranch(t *testing.T, u *url.URL) {
assert.Equal(t, "main", repo1.DefaultBranch)
// create branch1
csrf := GetUserCSRFToken(t, session)
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/_new/branch/main", map[string]string{
"_csrf": csrf,
"new_branch_name": "branch1",
})
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -66,7 +58,6 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// create branch2
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/_new/branch/main", map[string]string{
"_csrf": csrf,
"new_branch_name": "branch2",
})
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -76,9 +67,8 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// rename branch2 to branch1
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/rename", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"from": "branch2",
"to": "branch1",
"from": "branch2",
"to": "branch1",
})
session.MakeRequest(t, req, http.StatusSeeOther)
flashMsg := session.GetCookieFlashMessage()
@@ -91,8 +81,7 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// delete branch1
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/delete", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"name": "branch1",
"name": "branch1",
})
session.MakeRequest(t, req, http.StatusOK)
branch2 = unittest.AssertExistsAndLoadBean(t, &git_model.Branch{RepoID: repo1.ID, Name: "branch2"})
@@ -102,9 +91,8 @@ func testRenameBranch(t *testing.T, u *url.URL) {
// rename branch2 to branch1 again
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/rename", map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"from": "branch2",
"to": "branch1",
"from": "branch2",
"to": "branch1",
})
session.MakeRequest(t, req, http.StatusSeeOther)
+32 -7
View File
@@ -15,6 +15,7 @@ import (
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRepoDownloadArchive(t *testing.T) {
@@ -23,11 +24,35 @@ func TestRepoDownloadArchive(t *testing.T) {
defer test.MockVariableValue(&web.GzipMinSize, 10)()
defer test.MockVariableValue(&testWebRoutes, routers.NormalRoutes())()
req := NewRequest(t, "GET", "/user2/repo1/archive/master.zip")
req.Header.Set("Accept-Encoding", "gzip")
resp := MakeRequest(t, req, http.StatusOK)
bs, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Empty(t, resp.Header().Get("Content-Encoding"))
assert.Len(t, bs, 320)
t.Run("NoDuplicateCompression", func(t *testing.T) {
req := NewRequest(t, "GET", "/user2/repo1/archive/master.zip")
req.Header.Set("Accept-Encoding", "gzip")
resp := MakeRequest(t, req, http.StatusOK)
bs, err := io.ReadAll(resp.Body)
assert.NoError(t, err)
assert.Empty(t, resp.Header().Get("Content-Encoding"))
assert.Len(t, bs, 320)
})
t.Run("SubPath", func(t *testing.T) {
// When using "archiving and caching" approach, archiving with paths will always use streaming and never be cached
defer test.MockVariableValue(&setting.Repository.StreamArchives, false) // this can be removed if there is always streaming mode
req := NewRequest(t, "GET", "/user2/glob/archive/master.tar.gz?path=aaa.doc&path=x/y")
resp := MakeRequest(t, req, http.StatusOK)
content, err := test.ReadAllTarGzContent(resp.Body)
require.NoError(t, err)
assert.Empty(t, content["glob/a.txt"])
assert.NotEmpty(t, content["glob/aaa.doc"])
assert.Empty(t, content["glob/x/b.txt"])
assert.NotEmpty(t, content["glob/x/y/a.txt"])
req = NewRequest(t, "GET", "/user2/glob/archive/master.tar.gz")
resp = MakeRequest(t, req, http.StatusOK)
content, err = test.ReadAllTarGzContent(resp.Body)
require.NoError(t, err)
assert.NotEmpty(t, content["glob/a.txt"])
assert.NotEmpty(t, content["glob/aaa.doc"])
assert.NotEmpty(t, content["glob/x/b.txt"])
assert.NotEmpty(t, content["glob/x/y/a.txt"])
})
}
-14
View File
@@ -15,16 +15,13 @@ import (
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/test"
"code.gitea.io/gitea/modules/translation"
"code.gitea.io/gitea/tests"
"github.com/PuerkitoBio/goquery"
"github.com/stretchr/testify/assert"
)
func testCreateBranch(t testing.TB, session *TestSession, user, repo, oldRefSubURL, newBranchName string, expectedStatus int) string {
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", path.Join(user, repo, "branches/_new", oldRefSubURL), map[string]string{
"_csrf": csrf,
"new_branch_name": newBranchName,
})
resp := session.MakeRequest(t, req, expectedStatus)
@@ -126,17 +123,6 @@ func testCreateBranches(t *testing.T, giteaURL *url.URL) {
}
}
func TestCreateBranchInvalidCSRF(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user2")
req := NewRequestWithValues(t, "POST", "user2/repo1/branches/_new/branch/master", map[string]string{
"_csrf": "fake_csrf",
"new_branch_name": "test",
})
resp := session.MakeRequest(t, req, http.StatusBadRequest)
assert.Contains(t, resp.Body.String(), "Invalid CSRF token")
}
func prepareRecentlyPushedBranchTest(t *testing.T, headSession *TestSession, baseRepo, headRepo *repo_model.Repository) {
refSubURL := "branch/" + headRepo.DefaultBranch
baseRepoPath := baseRepo.OwnerName + "/" + baseRepo.Name
+72 -99
View File
@@ -6,12 +6,13 @@ package integration
import (
"fmt"
"net/http"
"net/http/httptest"
"path"
"sync"
"testing"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
git_model "code.gitea.io/gitea/models/git"
"code.gitea.io/gitea/modules/commitstatus"
"code.gitea.io/gitea/modules/json"
"code.gitea.io/gitea/modules/setting"
@@ -20,6 +21,7 @@ import (
"github.com/PuerkitoBio/goquery"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestRepoCommits(t *testing.T) {
@@ -79,98 +81,87 @@ func TestRepoCommits(t *testing.T) {
})
}
func doTestRepoCommitWithStatus(t *testing.T, state string, classes ...string) {
func TestRepoCommitsWithStatus(t *testing.T) {
defer tests.PrepareTestEnv(t)()
session := loginUser(t, "user2")
// Request repository commits page
req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
// Get first commit URL
commitURL, exists := doc.doc.Find("#commits-table .commit-id-short").Attr("href")
assert.True(t, exists)
assert.NotEmpty(t, commitURL)
// Call API to add status for commit
ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository)
t.Run("CreateStatus", doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CreateStatusOption{
State: commitstatus.CommitStatusState(state),
TargetURL: "http://test.ci/",
Description: "",
Context: "testci",
}))
req = NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
resp = session.MakeRequest(t, req, http.StatusOK)
doc = NewHTMLParser(t, resp.Body)
// Check if commit status is displayed in message column (.tippy-target to ignore the tippy trigger)
sel := doc.doc.Find("#commits-table .message .tippy-target .commit-status")
assert.Equal(t, 1, sel.Length())
for _, class := range classes {
assert.True(t, sel.HasClass(class))
requestCommitStatuses := func(t *testing.T, linkList, linkCombined string) (statuses []*api.CommitStatus, status api.CombinedStatus) {
assert.NoError(t, json.Unmarshal(session.MakeRequest(t, NewRequest(t, "GET", linkList), http.StatusOK).Body.Bytes(), &statuses))
assert.NoError(t, json.Unmarshal(session.MakeRequest(t, NewRequest(t, "GET", linkCombined), http.StatusOK).Body.Bytes(), &status))
return statuses, status
}
// By SHA
req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/statuses")
reqOne := NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)+"/status")
testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
testRefMaster := func(t *testing.T, state commitstatus.CommitStatusState, classes ...string) {
_ = db.TruncateBeans(t.Context(), &git_model.CommitStatus{})
// By short SHA
req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)[:10]+"/statuses")
reqOne = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/"+path.Base(commitURL)[:10]+"/status")
testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
// Request repository commits page
req := NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
resp := session.MakeRequest(t, req, http.StatusOK)
// By Ref
req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/statuses")
reqOne = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/master/status")
testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
req = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/v1.1/statuses")
reqOne = NewRequest(t, "GET", "/api/v1/repos/user2/repo1/commits/v1.1/status")
testRepoCommitsWithStatus(t, session.MakeRequest(t, req, http.StatusOK), session.MakeRequest(t, reqOne, http.StatusOK), state)
}
doc := NewHTMLParser(t, resp.Body)
// Get first commit URL
commitURL, _ := doc.doc.Find("#commits-table .commit-id-short").Attr("href")
require.NotEmpty(t, commitURL)
commitID := path.Base(commitURL)
func testRepoCommitsWithStatus(t *testing.T, resp, respOne *httptest.ResponseRecorder, state string) {
var statuses []*api.CommitStatus
assert.NoError(t, json.Unmarshal(resp.Body.Bytes(), &statuses))
var status api.CombinedStatus
assert.NoError(t, json.Unmarshal(respOne.Body.Bytes(), &status))
assert.NotNil(t, status)
// Call API to add status for commit
doAPICreateCommitStatusTest(ctx, path.Base(commitURL), state, "testci")(t)
if assert.Len(t, statuses, 1) {
assert.Equal(t, commitstatus.CommitStatusState(state), statuses[0].State)
assert.Equal(t, setting.AppURL+"api/v1/repos/user2/repo1/statuses/65f1bf27bc3bf70f64657658635e66094edbcb4d", statuses[0].URL)
assert.Equal(t, "http://test.ci/", statuses[0].TargetURL)
assert.Empty(t, statuses[0].Description)
assert.Equal(t, "testci", statuses[0].Context)
req = NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
resp = session.MakeRequest(t, req, http.StatusOK)
assert.Len(t, status.Statuses, 1)
assert.Equal(t, statuses[0], status.Statuses[0])
assert.Equal(t, "65f1bf27bc3bf70f64657658635e66094edbcb4d", status.SHA)
doc = NewHTMLParser(t, resp.Body)
// Check if commit status is displayed in message column (.tippy-target to ignore the tippy trigger)
sel := doc.doc.Find("#commits-table .message .tippy-target .commit-status")
assert.Equal(t, 1, sel.Length())
for _, class := range classes {
assert.True(t, sel.HasClass(class))
}
testRepoCommitsWithStatus := func(t *testing.T, linkList, linkCombined string, state commitstatus.CommitStatusState) {
statuses, status := requestCommitStatuses(t, linkList, linkCombined)
require.Len(t, statuses, 1)
require.NotNil(t, status)
assert.Equal(t, state, statuses[0].State)
assert.Equal(t, setting.AppURL+"api/v1/repos/user2/repo1/statuses/"+commitID, statuses[0].URL)
assert.Equal(t, "http://test.ci/", statuses[0].TargetURL)
assert.Empty(t, statuses[0].Description)
assert.Equal(t, "testci", statuses[0].Context)
assert.Len(t, status.Statuses, 1)
assert.Equal(t, statuses[0], status.Statuses[0])
assert.Equal(t, commitID, status.SHA)
}
// By SHA
testRepoCommitsWithStatus(t, "/api/v1/repos/user2/repo1/commits/"+commitID+"/statuses", "/api/v1/repos/user2/repo1/commits/"+commitID+"/status", state)
// By short SHA
testRepoCommitsWithStatus(t, "/api/v1/repos/user2/repo1/commits/"+commitID[:7]+"/statuses", "/api/v1/repos/user2/repo1/commits/"+commitID[:7]+"/status", state)
// By Ref
testRepoCommitsWithStatus(t, "/api/v1/repos/user2/repo1/commits/master/statuses", "/api/v1/repos/user2/repo1/commits/master/status", state)
// Tag "v1.1" points to master
testRepoCommitsWithStatus(t, "/api/v1/repos/user2/repo1/commits/v1.1/statuses", "/api/v1/repos/user2/repo1/commits/v1.1/status", state)
}
}
func TestRepoCommitsWithStatusPending(t *testing.T) {
doTestRepoCommitWithStatus(t, "pending", "octicon-dot-fill", "yellow")
}
t.Run("pending", func(t *testing.T) { testRefMaster(t, "pending", "octicon-dot-fill", "yellow") })
t.Run("success", func(t *testing.T) { testRefMaster(t, "success", "octicon-check", "green") })
t.Run("error", func(t *testing.T) { testRefMaster(t, "error", "gitea-exclamation", "red") })
t.Run("failure", func(t *testing.T) { testRefMaster(t, "failure", "octicon-x", "red") })
t.Run("warning", func(t *testing.T) { testRefMaster(t, "warning", "gitea-exclamation", "yellow") })
t.Run("BranchWithSlash", func(t *testing.T) {
_ = db.TruncateBeans(t.Context(), &git_model.CommitStatus{})
func TestRepoCommitsWithStatusSuccess(t *testing.T) {
doTestRepoCommitWithStatus(t, "success", "octicon-check", "green")
}
func TestRepoCommitsWithStatusError(t *testing.T) {
doTestRepoCommitWithStatus(t, "error", "gitea-exclamation", "red")
}
func TestRepoCommitsWithStatusFailure(t *testing.T) {
doTestRepoCommitWithStatus(t, "failure", "octicon-x", "red")
}
func TestRepoCommitsWithStatusWarning(t *testing.T) {
doTestRepoCommitWithStatus(t, "warning", "gitea-exclamation", "yellow")
linkList, linkCombined := "/api/v1/repos/user2/repo1/commits/feature%2F1/statuses", "/api/v1/repos/user2/repo1/commits/feature/1/status"
statuses, status := requestCommitStatuses(t, linkList, linkCombined)
assert.Empty(t, statuses)
assert.Empty(t, status.Statuses)
doAPICreateCommitStatusTest(ctx, "feature/1", commitstatus.CommitStatusSuccess, "testci")(t)
statuses, status = requestCommitStatuses(t, linkList, linkCombined)
assert.NotEmpty(t, statuses)
assert.NotEmpty(t, status.Statuses)
})
}
func TestRepoCommitsStatusParallel(t *testing.T) {
@@ -194,13 +185,7 @@ func TestRepoCommitsStatusParallel(t *testing.T) {
go func(parentT *testing.T, i int) {
parentT.Run(fmt.Sprintf("ParallelCreateStatus_%d", i), func(t *testing.T) {
ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository)
runBody := doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CreateStatusOption{
State: commitstatus.CommitStatusPending,
TargetURL: "http://test.ci/",
Description: "",
Context: "testci",
})
runBody(t)
doAPICreateCommitStatusTest(ctx, path.Base(commitURL), commitstatus.CommitStatusPending, "testci")(t)
wg.Done()
})
}(t, i)
@@ -225,20 +210,8 @@ func TestRepoCommitsStatusMultiple(t *testing.T) {
// Call API to add status for commit
ctx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeWriteRepository)
t.Run("CreateStatus", doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CreateStatusOption{
State: commitstatus.CommitStatusSuccess,
TargetURL: "http://test.ci/",
Description: "",
Context: "testci",
}))
t.Run("CreateStatus", doAPICreateCommitStatus(ctx, path.Base(commitURL), api.CreateStatusOption{
State: commitstatus.CommitStatusSuccess,
TargetURL: "http://test.ci/",
Description: "",
Context: "other_context",
}))
t.Run("CreateStatus", doAPICreateCommitStatusTest(ctx, path.Base(commitURL), commitstatus.CommitStatusSuccess, "testci"))
t.Run("CreateStatus", doAPICreateCommitStatusTest(ctx, path.Base(commitURL), commitstatus.CommitStatusSuccess, "other_context"))
req = NewRequest(t, "GET", "/user2/repo1/commits/branch/master")
resp = session.MakeRequest(t, req, http.StatusOK)
-1
View File
@@ -46,7 +46,6 @@ func testRepoFork(t *testing.T, session *TestSession, ownerName, repoName, forkO
_, exists = htmlDoc.doc.Find(fmt.Sprintf(".owner.dropdown .item[data-value=\"%d\"]", forkOwner.ID)).Attr("data-value")
assert.True(t, exists, "Fork owner '%s' is not present in select box", forkOwnerName)
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"uid": strconv.FormatInt(forkOwner.ID, 10),
"repo_name": forkRepoName,
"fork_single_branch": forkBranch,
-1
View File
@@ -44,7 +44,6 @@ func testRepoGenerate(t *testing.T, session *TestSession, templateID, templateOw
_, exists = htmlDoc.doc.Find(fmt.Sprintf(`#repo_owner_dropdown .item[data-value="%d"]`, generateOwner.ID)).Attr("data-value")
assert.True(t, exists, "Generate owner '%s' is not present in select box", generateOwnerName)
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"uid": strconv.FormatInt(generateOwner.ID, 10),
"repo_name": generateRepoName,
"repo_template": templateID,
@@ -49,7 +49,6 @@ func TestRepoMergeUpstream(t *testing.T) {
// create fork-branch
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/test-repo-fork/branches/_new/branch/master", forkUser.Name), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"new_branch_name": "fork-branch",
})
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -81,7 +80,6 @@ func TestRepoMergeUpstream(t *testing.T) {
t.Run("DetectSameBranch", func(t *testing.T) {
// if the fork-branch name also exists in the base repo, then use that branch instead
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/_new/branch/master", map[string]string{
"_csrf": GetUserCSRFToken(t, sessionBaseUser),
"new_branch_name": "fork-branch",
})
sessionBaseUser.MakeRequest(t, req, http.StatusSeeOther)
@@ -99,14 +97,12 @@ func TestRepoMergeUpstream(t *testing.T) {
})
// click the "sync fork" button
req = NewRequestWithValues(t, "POST", mergeUpstreamLink, map[string]string{"_csrf": GetUserCSRFToken(t, session)})
req = NewRequest(t, "POST", mergeUpstreamLink)
session.MakeRequest(t, req, http.StatusOK)
checkFileContent("fork-branch", "test-content-1")
// delete the "fork-branch" from the base repo
req = NewRequestWithValues(t, "POST", "/user2/repo1/branches/delete?name=fork-branch", map[string]string{
"_csrf": GetUserCSRFToken(t, sessionBaseUser),
})
req = NewRequest(t, "POST", "/user2/repo1/branches/delete?name=fork-branch")
sessionBaseUser.MakeRequest(t, req, http.StatusOK)
})
@@ -151,7 +147,6 @@ func TestRepoMergeUpstream(t *testing.T) {
t.Run("FastForwardOnly", func(t *testing.T) {
// Create a clean branch for fast-forward testing
req = NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/test-repo-fork/branches/_new/branch/master", forkUser.Name), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"new_branch_name": "ff-test-branch",
})
session.MakeRequest(t, req, http.StatusSeeOther)
-1
View File
@@ -27,7 +27,6 @@ func testRepoMigrate(t testing.TB, session *TestSession, cloneAddr, repoName str
assert.True(t, exists, "The template has changed")
req = NewRequestWithValues(t, "POST", link, map[string]string{
"_csrf": htmlDoc.GetCSRF(),
"clone_addr": cloneAddr,
"uid": uid,
"repo_name": repoName,
+1 -4
View File
@@ -157,7 +157,6 @@ func testViewRepoPrivate(t *testing.T) {
// set unit code to "anonymous read"
req = NewRequestWithValues(t, "POST", "/org3/repo3/settings/public_access", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"repo-unit-access-" + strconv.Itoa(int(unit.TypeCode)): "anonymous-read",
})
session.MakeRequest(t, req, http.StatusSeeOther)
@@ -168,9 +167,7 @@ func testViewRepoPrivate(t *testing.T) {
assert.Contains(t, resp.Body.String(), `<span class="ui basic orange label">Public Access</span>`)
// remove "anonymous read"
req = NewRequestWithValues(t, "POST", "/org3/repo3/settings/public_access", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", "/org3/repo3/settings/public_access")
session.MakeRequest(t, req, http.StatusSeeOther)
// try to "anonymous read" (not found)
+4 -19
View File
@@ -83,9 +83,7 @@ func testAPICreateWebhookForRepo(t *testing.T, session *TestSession, userName, r
}
func testCreateWebhookForRepo(t *testing.T, session *TestSession, webhookType, userName, repoName, url, eventKind string) {
csrf := GetUserCSRFToken(t, session)
req := NewRequestWithValues(t, "POST", "/"+userName+"/"+repoName+"/settings/hooks/"+webhookType+"/new", map[string]string{
"_csrf": csrf,
"payload_url": url,
"events": eventKind,
"active": "true",
@@ -278,7 +276,6 @@ func Test_WebhookIssueComment(t *testing.T) {
commentID := testIssueAddComment(t, session, issueURL, "issue title3 comment1", "")
modifiedContent := "issue title2 comment1 - modified"
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": modifiedContent,
})
session.MakeRequest(t, req, http.StatusOK)
@@ -306,7 +303,6 @@ func Test_WebhookIssueComment(t *testing.T) {
payloads = make([]api.IssueCommentPayload, 0, 2)
triggeredEvent = ""
req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/comments/%d", "user2", "repo1", commentID), map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"content": commentContent,
})
session.MakeRequest(t, req, http.StatusOK)
@@ -934,12 +930,7 @@ func Test_WebhookStatus(t *testing.T) {
testCtx := NewAPITestContext(t, "user2", "repo1", auth_model.AccessTokenScopeAll)
// update a status for a commit via API
doAPICreateCommitStatus(testCtx, commitID, api.CreateStatusOption{
State: commitstatus.CommitStatusSuccess,
TargetURL: "http://test.ci/",
Description: "",
Context: "testci",
})(t)
doAPICreateCommitStatusTest(testCtx, commitID, commitstatus.CommitStatusSuccess, "testci")(t)
// 3. validate the webhook is triggered
assert.Equal(t, "status", triggeredEvent)
@@ -1284,9 +1275,7 @@ jobs:
// Call cancel ui api
// Only a web UI API exists for cancelling workflow runs, so use the UI endpoint.
cancelURL := fmt.Sprintf("/user2/repo1/actions/runs/%d/cancel", webhookData.payloads[0].WorkflowRun.RunNumber)
req := NewRequestWithValues(t, "POST", cancelURL, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", cancelURL)
session.MakeRequest(t, req, http.StatusOK)
assert.Len(t, webhookData.payloads, 2)
@@ -1418,9 +1407,7 @@ jobs:
// Call cancel ui api
// Only a web UI API exists for cancelling workflow runs, so use the UI endpoint.
cancelURL := fmt.Sprintf("/user2/repo1/actions/runs/%d/cancel", webhookData.payloads[0].WorkflowRun.RunNumber)
req := NewRequestWithValues(t, "POST", cancelURL, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req := NewRequest(t, "POST", cancelURL)
session.MakeRequest(t, req, http.StatusOK)
assert.Len(t, webhookData.payloads, 2)
@@ -1438,9 +1425,7 @@ jobs:
// Call rerun ui api
// Only a web UI API exists for rerunning workflow runs, so use the UI endpoint.
rerunURL := fmt.Sprintf("/user2/repo1/actions/runs/%d/rerun", webhookData.payloads[0].WorkflowRun.RunNumber)
req = NewRequestWithValues(t, "POST", rerunURL, map[string]string{
"_csrf": GetUserCSRFToken(t, session),
})
req = NewRequest(t, "POST", rerunURL)
session.MakeRequest(t, req, http.StatusOK)
assert.Len(t, webhookData.payloads, 3)
+2 -2
View File
@@ -184,7 +184,7 @@ func TestRequireSignInView(t *testing.T) {
defer test.MockVariableValue(&testWebRoutes, routers.NormalRoutes())()
req := NewRequest(t, "GET", "/user2/repo1/src/branch/master")
resp := MakeRequest(t, req, http.StatusSeeOther)
assert.Equal(t, "/user/login", resp.Header().Get("Location"))
assert.Equal(t, "/user/login?redirect_to=%2Fuser2%2Frepo1%2Fsrc%2Fbranch%2Fmaster", resp.Header().Get("Location"))
})
t.Run("BlockAnonymousAccessExpensive", func(t *testing.T) {
defer test.MockVariableValue(&setting.Service.RequireSignInViewStrict, false)()
@@ -196,6 +196,6 @@ func TestRequireSignInView(t *testing.T) {
req = NewRequest(t, "GET", "/user2/repo1/src/branch/master")
resp := MakeRequest(t, req, http.StatusSeeOther)
assert.Equal(t, "/user/login", resp.Header().Get("Location"))
assert.Equal(t, "/user/login?redirect_to=%2Fuser2%2Frepo1%2Fsrc%2Fbranch%2Fmaster", resp.Header().Get("Location"))
})
}
+2 -6
View File
@@ -46,9 +46,7 @@ func testViewTimetrackingControls(t *testing.T, session *TestSession, user, repo
AssertHTMLElement(t, htmlDoc, ".issue-add-time", canTrackTime)
issueLink := path.Join(user, repo, "issues", issue)
reqStart := NewRequestWithValues(t, "POST", path.Join(issueLink, "times", "stopwatch", "start"), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
})
reqStart := NewRequest(t, "POST", path.Join(issueLink, "times", "stopwatch", "start"))
if canTrackTime {
session.MakeRequest(t, reqStart, http.StatusOK)
@@ -65,9 +63,7 @@ func testViewTimetrackingControls(t *testing.T, session *TestSession, user, repo
// Sleep for 1 second to not get wrong order for stopping timer
time.Sleep(time.Second)
reqStop := NewRequestWithValues(t, "POST", path.Join(issueLink, "times", "stopwatch", "stop"), map[string]string{
"_csrf": htmlDoc.GetCSRF(),
})
reqStop := NewRequest(t, "POST", path.Join(issueLink, "times", "stopwatch", "stop"))
session.MakeRequest(t, reqStop, http.StatusOK)
req = NewRequest(t, "GET", issueLink)
-2
View File
@@ -35,7 +35,6 @@ func TestUserAvatar(t *testing.T) {
}
session := loginUser(t, "user2")
csrf := GetUserCSRFToken(t, session)
imgData := &bytes.Buffer{}
@@ -66,7 +65,6 @@ func TestUserAvatar(t *testing.T) {
}
req := NewRequestWithBody(t, "POST", "/user/settings/avatar", body)
req.Header.Add("X-Csrf-Token", csrf)
req.Header.Add("Content-Type", writer.FormDataContentType())
session.MakeRequest(t, req, http.StatusSeeOther)
+5 -48
View File
@@ -129,13 +129,7 @@ func TestUserSettingsUpdatePassword(t *testing.T) {
defer tests.PrintCurrentTest(t)()
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user/settings/account")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/account", map[string]string{
"_csrf": doc.GetCSRF(),
req := NewRequestWithValues(t, "POST", "/user/settings/account", map[string]string{
"old_password": "password",
"password": "password",
"retype": "password",
@@ -147,16 +141,8 @@ func TestUserSettingsUpdatePassword(t *testing.T) {
defer tests.PrintCurrentTest(t)()
WithDisabledFeatures(t, setting.UserFeatureManageCredentials)
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user/settings/account")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/account", map[string]string{
"_csrf": doc.GetCSRF(),
})
req := NewRequest(t, "POST", "/user/settings/account")
session.MakeRequest(t, req, http.StatusNotFound)
})
}
@@ -168,16 +154,8 @@ func TestUserSettingsUpdateEmail(t *testing.T) {
defer tests.PrintCurrentTest(t)()
WithDisabledFeatures(t, setting.UserFeatureManageCredentials)
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user/settings/account")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/account/email", map[string]string{
"_csrf": doc.GetCSRF(),
})
req := NewRequest(t, "POST", "/user/settings/account/email")
session.MakeRequest(t, req, http.StatusNotFound)
})
}
@@ -189,16 +167,8 @@ func TestUserSettingsDeleteEmail(t *testing.T) {
defer tests.PrintCurrentTest(t)()
WithDisabledFeatures(t, setting.UserFeatureManageCredentials)
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user/settings/account")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/account/email/delete", map[string]string{
"_csrf": doc.GetCSRF(),
})
req := NewRequest(t, "POST", "/user/settings/account/email/delete")
session.MakeRequest(t, req, http.StatusNotFound)
})
}
@@ -212,14 +182,7 @@ func TestUserSettingsDelete(t *testing.T) {
WithDisabledFeatures(t, setting.UserFeatureDeletion)
session := loginUser(t, "user2")
req := NewRequest(t, "GET", "/user/settings/account")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
req = NewRequestWithValues(t, "POST", "/user/settings/account/delete", map[string]string{
"_csrf": doc.GetCSRF(),
})
req := NewRequest(t, "POST", "/user/settings/account/delete")
session.MakeRequest(t, req, http.StatusNotFound)
})
}
@@ -308,15 +271,10 @@ func TestUserSettingsApplications(t *testing.T) {
t.Run("OAuthApplicationsEdit", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
req := NewRequest(t, "GET", "/user/settings/applications/oauth2/2")
resp := session.MakeRequest(t, req, http.StatusOK)
doc := NewHTMLParser(t, resp.Body)
t.Run("Invalid URL", func(t *testing.T) {
defer tests.PrintCurrentTest(t)()
req := NewRequestWithValues(t, "POST", "/user/settings/applications/oauth2/2", map[string]string{
"_csrf": doc.GetCSRF(),
"application_name": "Test native app",
"redirect_uris": "ftp://127.0.0.1",
"confidential_client": "false",
@@ -332,7 +290,6 @@ func TestUserSettingsApplications(t *testing.T) {
defer tests.PrintCurrentTest(t)()
req := NewRequestWithValues(t, "POST", "/user/settings/applications/oauth2/2", map[string]string{
"_csrf": doc.GetCSRF(),
"application_name": "Test native app",
"redirect_uris": "http://127.0.0.1",
"confidential_client": "false",
+16 -16
View File
@@ -27,6 +27,12 @@ func TestViewUser(t *testing.T) {
req := NewRequest(t, "GET", "/user2")
MakeRequest(t, req, http.StatusOK)
req = NewRequest(t, "GET", "/user2.keys")
resp := MakeRequest(t, req, http.StatusOK)
assert.Equal(t, `# Gitea isn't a key server. The keys are exported as the user uploaded and might not have been fully verified.
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDWVj0fQ5N8wNc0LVNA41wDLYJ89ZIbejrPfg/avyj3u/ZohAKsQclxG4Ju0VirduBFF9EOiuxoiFBRr3xRpqzpsZtnMPkWVWb+akZwBFAx8p+jKdy4QXR/SZqbVobrGwip2UjSrri1CtBxpJikojRIZfCnDaMOyd9Jp6KkujvniFzUWdLmCPxUE9zhTaPu0JsEP7MW0m6yx7ZUhHyfss+NtqmFTaDO+QlMR7L2QkDliN2Jl3Xa3PhuWnKJfWhdAq1Cw4oraKUOmIgXLkuiuxVQ6mD3AiFupkmfqdHq6h+uHHmyQqv3gU+/sD8GbGAhf6ftqhTsXjnv1Aj4R8NoDf9BS6KRkzkeun5UisSzgtfQzjOMEiJtmrep2ZQrMGahrXa+q4VKr0aKJfm+KlLfwm/JztfsBcqQWNcTURiCFqz+fgZw0Ey/de0eyMzldYTdXXNRYCKjs9bvBK+6SSXRM7AhftfQ0ZuoW5+gtinPrnmoOaSCEJbAiEiTO/BzOHgowiM=
`, resp.Body.String())
}
func TestRenameUsername(t *testing.T) {
@@ -34,7 +40,6 @@ func TestRenameUsername(t *testing.T) {
session := loginUser(t, "user2")
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": "newUsername",
"email": "user2@example.com",
"language": "en-US",
@@ -57,7 +62,6 @@ func TestViewLimitedAndPrivateUserAndRename(t *testing.T) {
oldName := org22.Name
newName := "org22_renamed"
req = NewRequestWithValues(t, "POST", "/org/"+oldName+"/settings/rename", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"org_name": oldName,
"new_org_name": newName,
})
@@ -79,7 +83,6 @@ func TestViewLimitedAndPrivateUserAndRename(t *testing.T) {
oldName = org23.Name
newName = "org23_renamed"
req = NewRequestWithValues(t, "POST", "/org/"+oldName+"/settings/rename", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"org_name": oldName,
"new_org_name": newName,
})
@@ -102,7 +105,6 @@ func TestViewLimitedAndPrivateUserAndRename(t *testing.T) {
newName = "user31_renamed"
session2 := loginUser(t, oldName)
req = NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session2),
"name": newName,
"visibility": "2", // private
})
@@ -150,7 +152,6 @@ func TestRenameInvalidUsername(t *testing.T) {
t.Logf("Testing username %s", invalidUsername)
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": invalidUsername,
"email": "user2@example.com",
})
@@ -178,7 +179,6 @@ func TestRenameReservedUsername(t *testing.T) {
locale := translation.NewLocale("en-US")
for _, reservedUsername := range reservedUsernames {
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": reservedUsername,
"email": "user2@example.com",
"language": "en-US",
@@ -200,8 +200,17 @@ func TestRenameReservedUsername(t *testing.T) {
func TestExportUserGPGKeys(t *testing.T) {
defer tests.PrepareTestEnv(t)()
testExportUserGPGKeys := func(t *testing.T, user, expected string) {
session := loginUser(t, user)
t.Logf("Testing username %s export gpg keys", user)
req := NewRequest(t, "GET", "/"+user+".gpg")
resp := session.MakeRequest(t, req, http.StatusOK)
assert.Equal(t, expected, resp.Body.String())
}
// Export empty key list
testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: Gitea isn't a key server. The keys are exported as the user uploaded and might not have been fully verified.
Note: This user hasn't uploaded any GPG keys.
@@ -243,6 +252,7 @@ GrE0MHOxUbc9tbtyk0F1SuzREUBH
-----END PGP PUBLIC KEY BLOCK-----`)
// Export new key
testExportUserGPGKeys(t, "user1", `-----BEGIN PGP PUBLIC KEY BLOCK-----
Comment: Gitea isn't a key server. The keys are exported as the user uploaded and might not have been fully verified.
xsBNBFyy/VUBCADJ7zbM20Z1RWmFoVgp5WkQfI2rU1Vj9cQHes9i42wVLLtcbPeo
QzubgzvMPITDy7nfWxgSf83E23DoHQ1ACFbQh/6eFSRrjsusp3YQ/08NSfPPbcu8
@@ -274,15 +284,6 @@ GrE0MHOxUbc9tbtyk0F1SuzREUBH
-----END PGP PUBLIC KEY BLOCK-----`)
}
func testExportUserGPGKeys(t *testing.T, user, expected string) {
session := loginUser(t, user)
t.Logf("Testing username %s export gpg keys", user)
req := NewRequest(t, "GET", "/"+user+".gpg")
resp := session.MakeRequest(t, req, http.StatusOK)
// t.Log(resp.Body.String())
assert.Equal(t, expected, resp.Body.String())
}
func TestGetUserRss(t *testing.T) {
defer tests.PrepareTestEnv(t)()
@@ -334,7 +335,6 @@ func TestUserLocationMapLink(t *testing.T) {
session := loginUser(t, "user2")
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": "user2",
"email": "user@example.com",
"language": "en-US",
-1
View File
@@ -21,7 +21,6 @@ func TestXSSUserFullName(t *testing.T) {
session := loginUser(t, user.Name)
req := NewRequestWithValues(t, "POST", "/user/settings", map[string]string{
"_csrf": GetUserCSRFToken(t, session),
"name": user.Name,
"full_name": fullName,
"email": user.Email,