You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

git_test.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package integrations
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "math/rand"
  9. "net/http"
  10. "net/url"
  11. "path"
  12. "path/filepath"
  13. "strconv"
  14. "testing"
  15. "time"
  16. "code.gitea.io/gitea/models"
  17. "code.gitea.io/gitea/modules/git"
  18. "code.gitea.io/gitea/modules/setting"
  19. api "code.gitea.io/gitea/modules/structs"
  20. "code.gitea.io/gitea/modules/util"
  21. "github.com/stretchr/testify/assert"
  22. )
  23. const (
  24. littleSize = 1024 //1ko
  25. bigSize = 128 * 1024 * 1024 //128Mo
  26. )
  27. func TestGit(t *testing.T) {
  28. onGiteaRun(t, testGit)
  29. }
  30. func testGit(t *testing.T, u *url.URL) {
  31. username := "user2"
  32. baseAPITestContext := NewAPITestContext(t, username, "repo1")
  33. u.Path = baseAPITestContext.GitPath()
  34. forkedUserCtx := NewAPITestContext(t, "user4", "repo1")
  35. t.Run("HTTP", func(t *testing.T) {
  36. defer PrintCurrentTest(t)()
  37. ensureAnonymousClone(t, u)
  38. httpContext := baseAPITestContext
  39. httpContext.Reponame = "repo-tmp-17"
  40. forkedUserCtx.Reponame = httpContext.Reponame
  41. dstPath, err := ioutil.TempDir("", httpContext.Reponame)
  42. assert.NoError(t, err)
  43. defer util.RemoveAll(dstPath)
  44. t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false))
  45. t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, httpContext.Username, models.AccessModeRead))
  46. t.Run("ForkFromDifferentUser", doAPIForkRepository(httpContext, forkedUserCtx.Username))
  47. u.Path = httpContext.GitPath()
  48. u.User = url.UserPassword(username, userPassword)
  49. t.Run("Clone", doGitClone(dstPath, u))
  50. little, big := standardCommitAndPushTest(t, dstPath)
  51. littleLFS, bigLFS := lfsCommitAndPushTest(t, dstPath)
  52. rawTest(t, &httpContext, little, big, littleLFS, bigLFS)
  53. mediaTest(t, &httpContext, little, big, littleLFS, bigLFS)
  54. t.Run("BranchProtectMerge", doBranchProtectPRMerge(&httpContext, dstPath))
  55. t.Run("CreatePRAndSetManuallyMerged", doCreatePRAndSetManuallyMerged(httpContext, httpContext, dstPath, "master", "test-manually-merge"))
  56. t.Run("MergeFork", func(t *testing.T) {
  57. defer PrintCurrentTest(t)()
  58. t.Run("CreatePRAndMerge", doMergeFork(httpContext, forkedUserCtx, "master", httpContext.Username+":master"))
  59. rawTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  60. mediaTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  61. })
  62. t.Run("PushCreate", doPushCreate(httpContext, u))
  63. })
  64. t.Run("SSH", func(t *testing.T) {
  65. defer PrintCurrentTest(t)()
  66. sshContext := baseAPITestContext
  67. sshContext.Reponame = "repo-tmp-18"
  68. keyname := "my-testing-key"
  69. forkedUserCtx.Reponame = sshContext.Reponame
  70. t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false))
  71. t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, sshContext.Username, models.AccessModeRead))
  72. t.Run("ForkFromDifferentUser", doAPIForkRepository(sshContext, forkedUserCtx.Username))
  73. //Setup key the user ssh key
  74. withKeyFile(t, keyname, func(keyFile string) {
  75. t.Run("CreateUserKey", doAPICreateUserKey(sshContext, "test-key", keyFile))
  76. //Setup remote link
  77. //TODO: get url from api
  78. sshURL := createSSHUrl(sshContext.GitPath(), u)
  79. //Setup clone folder
  80. dstPath, err := ioutil.TempDir("", sshContext.Reponame)
  81. assert.NoError(t, err)
  82. defer util.RemoveAll(dstPath)
  83. t.Run("Clone", doGitClone(dstPath, sshURL))
  84. little, big := standardCommitAndPushTest(t, dstPath)
  85. littleLFS, bigLFS := lfsCommitAndPushTest(t, dstPath)
  86. rawTest(t, &sshContext, little, big, littleLFS, bigLFS)
  87. mediaTest(t, &sshContext, little, big, littleLFS, bigLFS)
  88. t.Run("BranchProtectMerge", doBranchProtectPRMerge(&sshContext, dstPath))
  89. t.Run("MergeFork", func(t *testing.T) {
  90. defer PrintCurrentTest(t)()
  91. t.Run("CreatePRAndMerge", doMergeFork(sshContext, forkedUserCtx, "master", sshContext.Username+":master"))
  92. rawTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  93. mediaTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  94. })
  95. t.Run("PushCreate", doPushCreate(sshContext, sshURL))
  96. })
  97. })
  98. }
  99. func ensureAnonymousClone(t *testing.T, u *url.URL) {
  100. dstLocalPath, err := ioutil.TempDir("", "repo1")
  101. assert.NoError(t, err)
  102. defer util.RemoveAll(dstLocalPath)
  103. t.Run("CloneAnonymous", doGitClone(dstLocalPath, u))
  104. }
  105. func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) {
  106. t.Run("Standard", func(t *testing.T) {
  107. defer PrintCurrentTest(t)()
  108. little, big = commitAndPushTest(t, dstPath, "data-file-")
  109. })
  110. return
  111. }
  112. func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS string) {
  113. t.Run("LFS", func(t *testing.T) {
  114. defer PrintCurrentTest(t)()
  115. setting.CheckLFSVersion()
  116. if !setting.LFS.StartServer {
  117. t.Skip()
  118. return
  119. }
  120. prefix := "lfs-data-file-"
  121. _, err := git.NewCommand("lfs").AddArguments("install").RunInDir(dstPath)
  122. assert.NoError(t, err)
  123. _, err = git.NewCommand("lfs").AddArguments("track", prefix+"*").RunInDir(dstPath)
  124. assert.NoError(t, err)
  125. err = git.AddChanges(dstPath, false, ".gitattributes")
  126. assert.NoError(t, err)
  127. err = git.CommitChangesWithArgs(dstPath, allowLFSFilters(), git.CommitChangesOptions{
  128. Committer: &git.Signature{
  129. Email: "user2@example.com",
  130. Name: "User Two",
  131. When: time.Now(),
  132. },
  133. Author: &git.Signature{
  134. Email: "user2@example.com",
  135. Name: "User Two",
  136. When: time.Now(),
  137. },
  138. Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
  139. })
  140. assert.NoError(t, err)
  141. littleLFS, bigLFS = commitAndPushTest(t, dstPath, prefix)
  142. t.Run("Locks", func(t *testing.T) {
  143. defer PrintCurrentTest(t)()
  144. lockTest(t, dstPath)
  145. })
  146. })
  147. return
  148. }
  149. func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string) {
  150. t.Run("PushCommit", func(t *testing.T) {
  151. defer PrintCurrentTest(t)()
  152. t.Run("Little", func(t *testing.T) {
  153. defer PrintCurrentTest(t)()
  154. little = doCommitAndPush(t, littleSize, dstPath, prefix)
  155. })
  156. t.Run("Big", func(t *testing.T) {
  157. if testing.Short() {
  158. t.Skip("Skipping test in short mode.")
  159. return
  160. }
  161. defer PrintCurrentTest(t)()
  162. big = doCommitAndPush(t, bigSize, dstPath, prefix)
  163. })
  164. })
  165. return
  166. }
  167. func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
  168. t.Run("Raw", func(t *testing.T) {
  169. defer PrintCurrentTest(t)()
  170. username := ctx.Username
  171. reponame := ctx.Reponame
  172. session := loginUser(t, username)
  173. // Request raw paths
  174. req := NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", little))
  175. resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  176. assert.Equal(t, littleSize, resp.Length)
  177. setting.CheckLFSVersion()
  178. if setting.LFS.StartServer {
  179. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", littleLFS))
  180. resp := session.MakeRequest(t, req, http.StatusOK)
  181. assert.NotEqual(t, littleSize, resp.Body.Len())
  182. assert.LessOrEqual(t, resp.Body.Len(), 1024)
  183. if resp.Body.Len() != littleSize && resp.Body.Len() <= 1024 {
  184. assert.Contains(t, resp.Body.String(), models.LFSMetaFileIdentifier)
  185. }
  186. }
  187. if !testing.Short() {
  188. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", big))
  189. resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  190. assert.Equal(t, bigSize, resp.Length)
  191. if setting.LFS.StartServer {
  192. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", bigLFS))
  193. resp := session.MakeRequest(t, req, http.StatusOK)
  194. assert.NotEqual(t, bigSize, resp.Body.Len())
  195. if resp.Body.Len() != bigSize && resp.Body.Len() <= 1024 {
  196. assert.Contains(t, resp.Body.String(), models.LFSMetaFileIdentifier)
  197. }
  198. }
  199. }
  200. })
  201. }
  202. func mediaTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
  203. t.Run("Media", func(t *testing.T) {
  204. defer PrintCurrentTest(t)()
  205. username := ctx.Username
  206. reponame := ctx.Reponame
  207. session := loginUser(t, username)
  208. // Request media paths
  209. req := NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", little))
  210. resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  211. assert.Equal(t, littleSize, resp.Length)
  212. setting.CheckLFSVersion()
  213. if setting.LFS.StartServer {
  214. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", littleLFS))
  215. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  216. assert.Equal(t, littleSize, resp.Length)
  217. }
  218. if !testing.Short() {
  219. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", big))
  220. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  221. assert.Equal(t, bigSize, resp.Length)
  222. if setting.LFS.StartServer {
  223. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", bigLFS))
  224. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  225. assert.Equal(t, bigSize, resp.Length)
  226. }
  227. }
  228. })
  229. }
  230. func lockTest(t *testing.T, repoPath string) {
  231. lockFileTest(t, "README.md", repoPath)
  232. }
  233. func lockFileTest(t *testing.T, filename, repoPath string) {
  234. _, err := git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath)
  235. assert.NoError(t, err)
  236. _, err = git.NewCommand("lfs").AddArguments("lock", filename).RunInDir(repoPath)
  237. assert.NoError(t, err)
  238. _, err = git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath)
  239. assert.NoError(t, err)
  240. _, err = git.NewCommand("lfs").AddArguments("unlock", filename).RunInDir(repoPath)
  241. assert.NoError(t, err)
  242. }
  243. func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string {
  244. name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix)
  245. assert.NoError(t, err)
  246. _, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) //Push
  247. assert.NoError(t, err)
  248. return name
  249. }
  250. func generateCommitWithNewData(size int, repoPath, email, fullName, prefix string) (string, error) {
  251. //Generate random file
  252. bufSize := 4 * 1024
  253. if bufSize > size {
  254. bufSize = size
  255. }
  256. buffer := make([]byte, bufSize)
  257. tmpFile, err := ioutil.TempFile(repoPath, prefix)
  258. if err != nil {
  259. return "", err
  260. }
  261. defer tmpFile.Close()
  262. written := 0
  263. for written < size {
  264. n := size - written
  265. if n > bufSize {
  266. n = bufSize
  267. }
  268. _, err := rand.Read(buffer[:n])
  269. if err != nil {
  270. return "", err
  271. }
  272. n, err = tmpFile.Write(buffer[:n])
  273. if err != nil {
  274. return "", err
  275. }
  276. written += n
  277. }
  278. if err != nil {
  279. return "", err
  280. }
  281. //Commit
  282. // Now here we should explicitly allow lfs filters to run
  283. globalArgs := allowLFSFilters()
  284. err = git.AddChangesWithArgs(repoPath, globalArgs, false, filepath.Base(tmpFile.Name()))
  285. if err != nil {
  286. return "", err
  287. }
  288. err = git.CommitChangesWithArgs(repoPath, globalArgs, git.CommitChangesOptions{
  289. Committer: &git.Signature{
  290. Email: email,
  291. Name: fullName,
  292. When: time.Now(),
  293. },
  294. Author: &git.Signature{
  295. Email: email,
  296. Name: fullName,
  297. When: time.Now(),
  298. },
  299. Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
  300. })
  301. return filepath.Base(tmpFile.Name()), err
  302. }
  303. func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
  304. return func(t *testing.T) {
  305. defer PrintCurrentTest(t)()
  306. t.Run("CreateBranchProtected", doGitCreateBranch(dstPath, "protected"))
  307. t.Run("PushProtectedBranch", doGitPushTestRepository(dstPath, "origin", "protected"))
  308. ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame)
  309. t.Run("ProtectProtectedBranchNoWhitelist", doProtectBranch(ctx, "protected", ""))
  310. t.Run("GenerateCommit", func(t *testing.T) {
  311. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  312. assert.NoError(t, err)
  313. })
  314. t.Run("FailToPushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "origin", "protected"))
  315. t.Run("PushToUnprotectedBranch", doGitPushTestRepository(dstPath, "origin", "protected:unprotected"))
  316. var pr api.PullRequest
  317. var err error
  318. t.Run("CreatePullRequest", func(t *testing.T) {
  319. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, "protected", "unprotected")(t)
  320. assert.NoError(t, err)
  321. })
  322. t.Run("GenerateCommit", func(t *testing.T) {
  323. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  324. assert.NoError(t, err)
  325. })
  326. t.Run("PushToUnprotectedBranch", doGitPushTestRepository(dstPath, "origin", "protected:unprotected-2"))
  327. var pr2 api.PullRequest
  328. t.Run("CreatePullRequest", func(t *testing.T) {
  329. pr2, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, "unprotected", "unprotected-2")(t)
  330. assert.NoError(t, err)
  331. })
  332. t.Run("MergePR2", doAPIMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr2.Index))
  333. t.Run("MergePR", doAPIMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index))
  334. t.Run("PullProtected", doGitPull(dstPath, "origin", "protected"))
  335. t.Run("ProtectProtectedBranchWhitelist", doProtectBranch(ctx, "protected", baseCtx.Username))
  336. t.Run("CheckoutMaster", doGitCheckoutBranch(dstPath, "master"))
  337. t.Run("CreateBranchForced", doGitCreateBranch(dstPath, "toforce"))
  338. t.Run("GenerateCommit", func(t *testing.T) {
  339. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  340. assert.NoError(t, err)
  341. })
  342. t.Run("FailToForcePushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "-f", "origin", "toforce:protected"))
  343. t.Run("MergeProtectedToToforce", doGitMerge(dstPath, "protected"))
  344. t.Run("PushToProtectedBranch", doGitPushTestRepository(dstPath, "origin", "toforce:protected"))
  345. t.Run("CheckoutMasterAgain", doGitCheckoutBranch(dstPath, "master"))
  346. }
  347. }
  348. func doProtectBranch(ctx APITestContext, branch string, userToWhitelist string) func(t *testing.T) {
  349. // We are going to just use the owner to set the protection.
  350. return func(t *testing.T) {
  351. csrf := GetCSRF(t, ctx.Session, fmt.Sprintf("/%s/%s/settings/branches", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame)))
  352. if userToWhitelist == "" {
  353. // Change branch to protected
  354. req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/branches/%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), url.PathEscape(branch)), map[string]string{
  355. "_csrf": csrf,
  356. "protected": "on",
  357. })
  358. ctx.Session.MakeRequest(t, req, http.StatusFound)
  359. } else {
  360. user, err := models.GetUserByName(userToWhitelist)
  361. assert.NoError(t, err)
  362. // Change branch to protected
  363. req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/branches/%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), url.PathEscape(branch)), map[string]string{
  364. "_csrf": csrf,
  365. "protected": "on",
  366. "enable_push": "whitelist",
  367. "enable_whitelist": "on",
  368. "whitelist_users": strconv.FormatInt(user.ID, 10),
  369. })
  370. ctx.Session.MakeRequest(t, req, http.StatusFound)
  371. }
  372. // Check if master branch has been locked successfully
  373. flashCookie := ctx.Session.GetCookie("macaron_flash")
  374. assert.NotNil(t, flashCookie)
  375. assert.EqualValues(t, "success%3DBranch%2Bprotection%2Bfor%2Bbranch%2B%2527"+url.QueryEscape(branch)+"%2527%2Bhas%2Bbeen%2Bupdated.", flashCookie.Value)
  376. }
  377. }
  378. func doMergeFork(ctx, baseCtx APITestContext, baseBranch, headBranch string) func(t *testing.T) {
  379. return func(t *testing.T) {
  380. defer PrintCurrentTest(t)()
  381. var pr api.PullRequest
  382. var err error
  383. // Create a test pullrequest
  384. t.Run("CreatePullRequest", func(t *testing.T) {
  385. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t)
  386. assert.NoError(t, err)
  387. })
  388. // Ensure the PR page works
  389. t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
  390. // Then get the diff string
  391. var diffHash string
  392. t.Run("GetDiff", func(t *testing.T) {
  393. req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d.diff", url.PathEscape(baseCtx.Username), url.PathEscape(baseCtx.Reponame), pr.Index))
  394. resp := ctx.Session.MakeRequestNilResponseHashSumRecorder(t, req, http.StatusOK)
  395. diffHash = string(resp.Hash.Sum(nil))
  396. })
  397. // Now: Merge the PR & make sure that doesn't break the PR page or change its diff
  398. t.Run("MergePR", doAPIMergePullRequest(baseCtx, baseCtx.Username, baseCtx.Reponame, pr.Index))
  399. t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
  400. t.Run("EnsureDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffHash))
  401. // Then: Delete the head branch & make sure that doesn't break the PR page or change its diff
  402. t.Run("DeleteHeadBranch", doBranchDelete(baseCtx, baseCtx.Username, baseCtx.Reponame, headBranch))
  403. t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
  404. t.Run("EnsureDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffHash))
  405. // Delete the head repository & make sure that doesn't break the PR page or change its diff
  406. t.Run("DeleteHeadRepository", doAPIDeleteRepository(ctx))
  407. t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
  408. t.Run("EnsureDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffHash))
  409. }
  410. }
  411. func doCreatePRAndSetManuallyMerged(ctx, baseCtx APITestContext, dstPath, baseBranch, headBranch string) func(t *testing.T) {
  412. return func(t *testing.T) {
  413. defer PrintCurrentTest(t)()
  414. var (
  415. pr api.PullRequest
  416. err error
  417. lastCommitID string
  418. )
  419. trueBool := true
  420. falseBool := false
  421. t.Run("AllowSetManuallyMergedAndSwitchOffAutodetectManualMerge", doAPIEditRepository(baseCtx, &api.EditRepoOption{
  422. HasPullRequests: &trueBool,
  423. AllowManualMerge: &trueBool,
  424. AutodetectManualMerge: &falseBool,
  425. }))
  426. t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
  427. t.Run("PushToHeadBranch", doGitPushTestRepository(dstPath, "origin", headBranch))
  428. t.Run("CreateEmptyPullRequest", func(t *testing.T) {
  429. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t)
  430. assert.NoError(t, err)
  431. })
  432. lastCommitID = pr.Base.Sha
  433. t.Run("ManuallyMergePR", doAPIManuallyMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, lastCommitID, pr.Index))
  434. }
  435. }
  436. func doEnsureCanSeePull(ctx APITestContext, pr api.PullRequest) func(t *testing.T) {
  437. return func(t *testing.T) {
  438. req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), pr.Index))
  439. ctx.Session.MakeRequest(t, req, http.StatusOK)
  440. req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d/files", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), pr.Index))
  441. ctx.Session.MakeRequest(t, req, http.StatusOK)
  442. req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d/commits", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), pr.Index))
  443. ctx.Session.MakeRequest(t, req, http.StatusOK)
  444. }
  445. }
  446. func doEnsureDiffNoChange(ctx APITestContext, pr api.PullRequest, diffHash string) func(t *testing.T) {
  447. return func(t *testing.T) {
  448. req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d.diff", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), pr.Index))
  449. resp := ctx.Session.MakeRequestNilResponseHashSumRecorder(t, req, http.StatusOK)
  450. actual := string(resp.Hash.Sum(nil))
  451. equal := diffHash == actual
  452. assert.True(t, equal, "Unexpected change in the diff string: expected hash: %s but was actually: %s", diffHash, actual)
  453. }
  454. }
  455. func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) {
  456. return func(t *testing.T) {
  457. defer PrintCurrentTest(t)()
  458. // create a context for a currently non-existent repository
  459. ctx.Reponame = fmt.Sprintf("repo-tmp-push-create-%s", u.Scheme)
  460. u.Path = ctx.GitPath()
  461. // Create a temporary directory
  462. tmpDir, err := ioutil.TempDir("", ctx.Reponame)
  463. assert.NoError(t, err)
  464. defer util.RemoveAll(tmpDir)
  465. // Now create local repository to push as our test and set its origin
  466. t.Run("InitTestRepository", doGitInitTestRepository(tmpDir))
  467. t.Run("AddRemote", doGitAddRemote(tmpDir, "origin", u))
  468. // Disable "Push To Create" and attempt to push
  469. setting.Repository.EnablePushCreateUser = false
  470. t.Run("FailToPushAndCreateTestRepository", doGitPushTestRepositoryFail(tmpDir, "origin", "master"))
  471. // Enable "Push To Create"
  472. setting.Repository.EnablePushCreateUser = true
  473. // Assert that cloning from a non-existent repository does not create it and that it definitely wasn't create above
  474. t.Run("FailToCloneFromNonExistentRepository", doGitCloneFail(u))
  475. // Then "Push To Create"x
  476. t.Run("SuccessfullyPushAndCreateTestRepository", doGitPushTestRepository(tmpDir, "origin", "master"))
  477. // Finally, fetch repo from database and ensure the correct repository has been created
  478. repo, err := models.GetRepositoryByOwnerAndName(ctx.Username, ctx.Reponame)
  479. assert.NoError(t, err)
  480. assert.False(t, repo.IsEmpty)
  481. assert.True(t, repo.IsPrivate)
  482. // Now add a remote that is invalid to "Push To Create"
  483. invalidCtx := ctx
  484. invalidCtx.Reponame = fmt.Sprintf("invalid/repo-tmp-push-create-%s", u.Scheme)
  485. u.Path = invalidCtx.GitPath()
  486. t.Run("AddInvalidRemote", doGitAddRemote(tmpDir, "invalid", u))
  487. // Fail to "Push To Create" the invalid
  488. t.Run("FailToPushAndCreateInvalidTestRepository", doGitPushTestRepositoryFail(tmpDir, "invalid", "master"))
  489. }
  490. }
  491. func doBranchDelete(ctx APITestContext, owner, repo, branch string) func(*testing.T) {
  492. return func(t *testing.T) {
  493. csrf := GetCSRF(t, ctx.Session, fmt.Sprintf("/%s/%s/branches", url.PathEscape(owner), url.PathEscape(repo)))
  494. req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/branches/delete?name=%s", url.PathEscape(owner), url.PathEscape(repo), url.QueryEscape(branch)), map[string]string{
  495. "_csrf": csrf,
  496. })
  497. ctx.Session.MakeRequest(t, req, http.StatusOK)
  498. }
  499. }