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 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  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. "encoding/hex"
  7. "fmt"
  8. "io/ioutil"
  9. "math/rand"
  10. "net/http"
  11. "net/url"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "testing"
  16. "time"
  17. "code.gitea.io/gitea/models"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/lfs"
  20. "code.gitea.io/gitea/modules/setting"
  21. api "code.gitea.io/gitea/modules/structs"
  22. "code.gitea.io/gitea/modules/util"
  23. "github.com/stretchr/testify/assert"
  24. )
  25. const (
  26. littleSize = 1024 //1ko
  27. bigSize = 128 * 1024 * 1024 //128Mo
  28. )
  29. func TestGit(t *testing.T) {
  30. onGiteaRun(t, testGit)
  31. }
  32. func testGit(t *testing.T, u *url.URL) {
  33. username := "user2"
  34. baseAPITestContext := NewAPITestContext(t, username, "repo1")
  35. u.Path = baseAPITestContext.GitPath()
  36. forkedUserCtx := NewAPITestContext(t, "user4", "repo1")
  37. t.Run("HTTP", func(t *testing.T) {
  38. defer PrintCurrentTest(t)()
  39. ensureAnonymousClone(t, u)
  40. httpContext := baseAPITestContext
  41. httpContext.Reponame = "repo-tmp-17"
  42. forkedUserCtx.Reponame = httpContext.Reponame
  43. dstPath, err := ioutil.TempDir("", httpContext.Reponame)
  44. assert.NoError(t, err)
  45. defer util.RemoveAll(dstPath)
  46. t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false))
  47. t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, httpContext.Username, models.AccessModeRead))
  48. t.Run("ForkFromDifferentUser", doAPIForkRepository(httpContext, forkedUserCtx.Username))
  49. u.Path = httpContext.GitPath()
  50. u.User = url.UserPassword(username, userPassword)
  51. t.Run("Clone", doGitClone(dstPath, u))
  52. little, big := standardCommitAndPushTest(t, dstPath)
  53. littleLFS, bigLFS := lfsCommitAndPushTest(t, dstPath)
  54. rawTest(t, &httpContext, little, big, littleLFS, bigLFS)
  55. mediaTest(t, &httpContext, little, big, littleLFS, bigLFS)
  56. t.Run("CreateAgitFlowPull", doCreateAgitFlowPull(dstPath, &httpContext, "master", "test/head"))
  57. t.Run("BranchProtectMerge", doBranchProtectPRMerge(&httpContext, dstPath))
  58. t.Run("CreatePRAndSetManuallyMerged", doCreatePRAndSetManuallyMerged(httpContext, httpContext, dstPath, "master", "test-manually-merge"))
  59. t.Run("MergeFork", func(t *testing.T) {
  60. defer PrintCurrentTest(t)()
  61. t.Run("CreatePRAndMerge", doMergeFork(httpContext, forkedUserCtx, "master", httpContext.Username+":master"))
  62. rawTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  63. mediaTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  64. })
  65. t.Run("PushCreate", doPushCreate(httpContext, u))
  66. })
  67. t.Run("SSH", func(t *testing.T) {
  68. defer PrintCurrentTest(t)()
  69. sshContext := baseAPITestContext
  70. sshContext.Reponame = "repo-tmp-18"
  71. keyname := "my-testing-key"
  72. forkedUserCtx.Reponame = sshContext.Reponame
  73. t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false))
  74. t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, sshContext.Username, models.AccessModeRead))
  75. t.Run("ForkFromDifferentUser", doAPIForkRepository(sshContext, forkedUserCtx.Username))
  76. //Setup key the user ssh key
  77. withKeyFile(t, keyname, func(keyFile string) {
  78. t.Run("CreateUserKey", doAPICreateUserKey(sshContext, "test-key", keyFile))
  79. //Setup remote link
  80. //TODO: get url from api
  81. sshURL := createSSHUrl(sshContext.GitPath(), u)
  82. //Setup clone folder
  83. dstPath, err := ioutil.TempDir("", sshContext.Reponame)
  84. assert.NoError(t, err)
  85. defer util.RemoveAll(dstPath)
  86. t.Run("Clone", doGitClone(dstPath, sshURL))
  87. little, big := standardCommitAndPushTest(t, dstPath)
  88. littleLFS, bigLFS := lfsCommitAndPushTest(t, dstPath)
  89. rawTest(t, &sshContext, little, big, littleLFS, bigLFS)
  90. mediaTest(t, &sshContext, little, big, littleLFS, bigLFS)
  91. t.Run("CreateAgitFlowPull", doCreateAgitFlowPull(dstPath, &sshContext, "master", "test/head2"))
  92. t.Run("BranchProtectMerge", doBranchProtectPRMerge(&sshContext, dstPath))
  93. t.Run("MergeFork", func(t *testing.T) {
  94. defer PrintCurrentTest(t)()
  95. t.Run("CreatePRAndMerge", doMergeFork(sshContext, forkedUserCtx, "master", sshContext.Username+":master"))
  96. rawTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  97. mediaTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  98. })
  99. t.Run("PushCreate", doPushCreate(sshContext, sshURL))
  100. })
  101. })
  102. }
  103. func ensureAnonymousClone(t *testing.T, u *url.URL) {
  104. dstLocalPath, err := ioutil.TempDir("", "repo1")
  105. assert.NoError(t, err)
  106. defer util.RemoveAll(dstLocalPath)
  107. t.Run("CloneAnonymous", doGitClone(dstLocalPath, u))
  108. }
  109. func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) {
  110. t.Run("Standard", func(t *testing.T) {
  111. defer PrintCurrentTest(t)()
  112. little, big = commitAndPushTest(t, dstPath, "data-file-")
  113. })
  114. return
  115. }
  116. func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS string) {
  117. t.Run("LFS", func(t *testing.T) {
  118. defer PrintCurrentTest(t)()
  119. git.CheckLFSVersion()
  120. if !setting.LFS.StartServer {
  121. t.Skip()
  122. return
  123. }
  124. prefix := "lfs-data-file-"
  125. _, err := git.NewCommand("lfs").AddArguments("install").RunInDir(dstPath)
  126. assert.NoError(t, err)
  127. _, err = git.NewCommand("lfs").AddArguments("track", prefix+"*").RunInDir(dstPath)
  128. assert.NoError(t, err)
  129. err = git.AddChanges(dstPath, false, ".gitattributes")
  130. assert.NoError(t, err)
  131. err = git.CommitChangesWithArgs(dstPath, allowLFSFilters(), git.CommitChangesOptions{
  132. Committer: &git.Signature{
  133. Email: "user2@example.com",
  134. Name: "User Two",
  135. When: time.Now(),
  136. },
  137. Author: &git.Signature{
  138. Email: "user2@example.com",
  139. Name: "User Two",
  140. When: time.Now(),
  141. },
  142. Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
  143. })
  144. assert.NoError(t, err)
  145. littleLFS, bigLFS = commitAndPushTest(t, dstPath, prefix)
  146. t.Run("Locks", func(t *testing.T) {
  147. defer PrintCurrentTest(t)()
  148. lockTest(t, dstPath)
  149. })
  150. })
  151. return
  152. }
  153. func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string) {
  154. t.Run("PushCommit", func(t *testing.T) {
  155. defer PrintCurrentTest(t)()
  156. t.Run("Little", func(t *testing.T) {
  157. defer PrintCurrentTest(t)()
  158. little = doCommitAndPush(t, littleSize, dstPath, prefix)
  159. })
  160. t.Run("Big", func(t *testing.T) {
  161. if testing.Short() {
  162. t.Skip("Skipping test in short mode.")
  163. return
  164. }
  165. defer PrintCurrentTest(t)()
  166. big = doCommitAndPush(t, bigSize, dstPath, prefix)
  167. })
  168. })
  169. return
  170. }
  171. func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
  172. t.Run("Raw", func(t *testing.T) {
  173. defer PrintCurrentTest(t)()
  174. username := ctx.Username
  175. reponame := ctx.Reponame
  176. session := loginUser(t, username)
  177. // Request raw paths
  178. req := NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", little))
  179. resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  180. assert.Equal(t, littleSize, resp.Length)
  181. git.CheckLFSVersion()
  182. if setting.LFS.StartServer {
  183. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", littleLFS))
  184. resp := session.MakeRequest(t, req, http.StatusOK)
  185. assert.NotEqual(t, littleSize, resp.Body.Len())
  186. assert.LessOrEqual(t, resp.Body.Len(), 1024)
  187. if resp.Body.Len() != littleSize && resp.Body.Len() <= 1024 {
  188. assert.Contains(t, resp.Body.String(), lfs.MetaFileIdentifier)
  189. }
  190. }
  191. if !testing.Short() {
  192. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", big))
  193. resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  194. assert.Equal(t, bigSize, resp.Length)
  195. if setting.LFS.StartServer {
  196. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", bigLFS))
  197. resp := session.MakeRequest(t, req, http.StatusOK)
  198. assert.NotEqual(t, bigSize, resp.Body.Len())
  199. if resp.Body.Len() != bigSize && resp.Body.Len() <= 1024 {
  200. assert.Contains(t, resp.Body.String(), lfs.MetaFileIdentifier)
  201. }
  202. }
  203. }
  204. })
  205. }
  206. func mediaTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
  207. t.Run("Media", func(t *testing.T) {
  208. defer PrintCurrentTest(t)()
  209. username := ctx.Username
  210. reponame := ctx.Reponame
  211. session := loginUser(t, username)
  212. // Request media paths
  213. req := NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", little))
  214. resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  215. assert.Equal(t, littleSize, resp.Length)
  216. git.CheckLFSVersion()
  217. if setting.LFS.StartServer {
  218. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", littleLFS))
  219. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  220. assert.Equal(t, littleSize, resp.Length)
  221. }
  222. if !testing.Short() {
  223. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", big))
  224. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  225. assert.Equal(t, bigSize, resp.Length)
  226. if setting.LFS.StartServer {
  227. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", bigLFS))
  228. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  229. assert.Equal(t, bigSize, resp.Length)
  230. }
  231. }
  232. })
  233. }
  234. func lockTest(t *testing.T, repoPath string) {
  235. lockFileTest(t, "README.md", repoPath)
  236. }
  237. func lockFileTest(t *testing.T, filename, repoPath string) {
  238. _, err := git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath)
  239. assert.NoError(t, err)
  240. _, err = git.NewCommand("lfs").AddArguments("lock", filename).RunInDir(repoPath)
  241. assert.NoError(t, err)
  242. _, err = git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath)
  243. assert.NoError(t, err)
  244. _, err = git.NewCommand("lfs").AddArguments("unlock", filename).RunInDir(repoPath)
  245. assert.NoError(t, err)
  246. }
  247. func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string {
  248. name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix)
  249. assert.NoError(t, err)
  250. _, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) //Push
  251. assert.NoError(t, err)
  252. return name
  253. }
  254. func generateCommitWithNewData(size int, repoPath, email, fullName, prefix string) (string, error) {
  255. //Generate random file
  256. bufSize := 4 * 1024
  257. if bufSize > size {
  258. bufSize = size
  259. }
  260. buffer := make([]byte, bufSize)
  261. tmpFile, err := ioutil.TempFile(repoPath, prefix)
  262. if err != nil {
  263. return "", err
  264. }
  265. defer tmpFile.Close()
  266. written := 0
  267. for written < size {
  268. n := size - written
  269. if n > bufSize {
  270. n = bufSize
  271. }
  272. _, err := rand.Read(buffer[:n])
  273. if err != nil {
  274. return "", err
  275. }
  276. n, err = tmpFile.Write(buffer[:n])
  277. if err != nil {
  278. return "", err
  279. }
  280. written += n
  281. }
  282. if err != nil {
  283. return "", err
  284. }
  285. //Commit
  286. // Now here we should explicitly allow lfs filters to run
  287. globalArgs := allowLFSFilters()
  288. err = git.AddChangesWithArgs(repoPath, globalArgs, false, filepath.Base(tmpFile.Name()))
  289. if err != nil {
  290. return "", err
  291. }
  292. err = git.CommitChangesWithArgs(repoPath, globalArgs, git.CommitChangesOptions{
  293. Committer: &git.Signature{
  294. Email: email,
  295. Name: fullName,
  296. When: time.Now(),
  297. },
  298. Author: &git.Signature{
  299. Email: email,
  300. Name: fullName,
  301. When: time.Now(),
  302. },
  303. Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
  304. })
  305. return filepath.Base(tmpFile.Name()), err
  306. }
  307. func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
  308. return func(t *testing.T) {
  309. defer PrintCurrentTest(t)()
  310. t.Run("CreateBranchProtected", doGitCreateBranch(dstPath, "protected"))
  311. t.Run("PushProtectedBranch", doGitPushTestRepository(dstPath, "origin", "protected"))
  312. ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame)
  313. t.Run("ProtectProtectedBranchNoWhitelist", doProtectBranch(ctx, "protected", "", ""))
  314. t.Run("GenerateCommit", func(t *testing.T) {
  315. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  316. assert.NoError(t, err)
  317. })
  318. t.Run("FailToPushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "origin", "protected"))
  319. t.Run("PushToUnprotectedBranch", doGitPushTestRepository(dstPath, "origin", "protected:unprotected"))
  320. var pr api.PullRequest
  321. var err error
  322. t.Run("CreatePullRequest", func(t *testing.T) {
  323. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, "protected", "unprotected")(t)
  324. assert.NoError(t, err)
  325. })
  326. t.Run("GenerateCommit", func(t *testing.T) {
  327. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  328. assert.NoError(t, err)
  329. })
  330. t.Run("PushToUnprotectedBranch", doGitPushTestRepository(dstPath, "origin", "protected:unprotected-2"))
  331. var pr2 api.PullRequest
  332. t.Run("CreatePullRequest", func(t *testing.T) {
  333. pr2, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, "unprotected", "unprotected-2")(t)
  334. assert.NoError(t, err)
  335. })
  336. t.Run("MergePR2", doAPIMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr2.Index))
  337. t.Run("MergePR", doAPIMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index))
  338. t.Run("PullProtected", doGitPull(dstPath, "origin", "protected"))
  339. t.Run("ProtectProtectedBranchUnprotectedFilePaths", doProtectBranch(ctx, "protected", "", "unprotected-file-*"))
  340. t.Run("GenerateCommit", func(t *testing.T) {
  341. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "unprotected-file-")
  342. assert.NoError(t, err)
  343. })
  344. t.Run("PushUnprotectedFilesToProtectedBranch", doGitPushTestRepository(dstPath, "origin", "protected"))
  345. t.Run("ProtectProtectedBranchWhitelist", doProtectBranch(ctx, "protected", baseCtx.Username, ""))
  346. t.Run("CheckoutMaster", doGitCheckoutBranch(dstPath, "master"))
  347. t.Run("CreateBranchForced", doGitCreateBranch(dstPath, "toforce"))
  348. t.Run("GenerateCommit", func(t *testing.T) {
  349. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  350. assert.NoError(t, err)
  351. })
  352. t.Run("FailToForcePushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "-f", "origin", "toforce:protected"))
  353. t.Run("MergeProtectedToToforce", doGitMerge(dstPath, "protected"))
  354. t.Run("PushToProtectedBranch", doGitPushTestRepository(dstPath, "origin", "toforce:protected"))
  355. t.Run("CheckoutMasterAgain", doGitCheckoutBranch(dstPath, "master"))
  356. }
  357. }
  358. func doProtectBranch(ctx APITestContext, branch string, userToWhitelist string, unprotectedFilePatterns string) func(t *testing.T) {
  359. // We are going to just use the owner to set the protection.
  360. return func(t *testing.T) {
  361. csrf := GetCSRF(t, ctx.Session, fmt.Sprintf("/%s/%s/settings/branches", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame)))
  362. if userToWhitelist == "" {
  363. // Change branch to protected
  364. 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{
  365. "_csrf": csrf,
  366. "protected": "on",
  367. "unprotected_file_patterns": unprotectedFilePatterns,
  368. })
  369. ctx.Session.MakeRequest(t, req, http.StatusFound)
  370. } else {
  371. user, err := models.GetUserByName(userToWhitelist)
  372. assert.NoError(t, err)
  373. // Change branch to protected
  374. 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{
  375. "_csrf": csrf,
  376. "protected": "on",
  377. "enable_push": "whitelist",
  378. "enable_whitelist": "on",
  379. "whitelist_users": strconv.FormatInt(user.ID, 10),
  380. "unprotected_file_patterns": unprotectedFilePatterns,
  381. })
  382. ctx.Session.MakeRequest(t, req, http.StatusFound)
  383. }
  384. // Check if master branch has been locked successfully
  385. flashCookie := ctx.Session.GetCookie("macaron_flash")
  386. assert.NotNil(t, flashCookie)
  387. assert.EqualValues(t, "success%3DBranch%2Bprotection%2Bfor%2Bbranch%2B%2527"+url.QueryEscape(branch)+"%2527%2Bhas%2Bbeen%2Bupdated.", flashCookie.Value)
  388. }
  389. }
  390. func doMergeFork(ctx, baseCtx APITestContext, baseBranch, headBranch string) func(t *testing.T) {
  391. return func(t *testing.T) {
  392. defer PrintCurrentTest(t)()
  393. var pr api.PullRequest
  394. var err error
  395. // Create a test pullrequest
  396. t.Run("CreatePullRequest", func(t *testing.T) {
  397. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t)
  398. assert.NoError(t, err)
  399. })
  400. // Ensure the PR page works
  401. t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
  402. // Then get the diff string
  403. var diffHash string
  404. var diffLength int
  405. t.Run("GetDiff", func(t *testing.T) {
  406. req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d.diff", url.PathEscape(baseCtx.Username), url.PathEscape(baseCtx.Reponame), pr.Index))
  407. resp := ctx.Session.MakeRequestNilResponseHashSumRecorder(t, req, http.StatusOK)
  408. diffHash = string(resp.Hash.Sum(nil))
  409. diffLength = resp.Length
  410. })
  411. // Now: Merge the PR & make sure that doesn't break the PR page or change its diff
  412. t.Run("MergePR", doAPIMergePullRequest(baseCtx, baseCtx.Username, baseCtx.Reponame, pr.Index))
  413. t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
  414. t.Run("CheckPR", func(t *testing.T) {
  415. oldMergeBase := pr.MergeBase
  416. pr2, err := doAPIGetPullRequest(baseCtx, baseCtx.Username, baseCtx.Reponame, pr.Index)(t)
  417. assert.NoError(t, err)
  418. assert.Equal(t, oldMergeBase, pr2.MergeBase)
  419. })
  420. t.Run("EnsurDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffHash, diffLength))
  421. // Then: Delete the head branch & make sure that doesn't break the PR page or change its diff
  422. t.Run("DeleteHeadBranch", doBranchDelete(baseCtx, baseCtx.Username, baseCtx.Reponame, headBranch))
  423. t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
  424. t.Run("EnsureDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffHash, diffLength))
  425. // Delete the head repository & make sure that doesn't break the PR page or change its diff
  426. t.Run("DeleteHeadRepository", doAPIDeleteRepository(ctx))
  427. t.Run("EnsureCanSeePull", doEnsureCanSeePull(baseCtx, pr))
  428. t.Run("EnsureDiffNoChange", doEnsureDiffNoChange(baseCtx, pr, diffHash, diffLength))
  429. }
  430. }
  431. func doCreatePRAndSetManuallyMerged(ctx, baseCtx APITestContext, dstPath, baseBranch, headBranch string) func(t *testing.T) {
  432. return func(t *testing.T) {
  433. defer PrintCurrentTest(t)()
  434. var (
  435. pr api.PullRequest
  436. err error
  437. lastCommitID string
  438. )
  439. trueBool := true
  440. falseBool := false
  441. t.Run("AllowSetManuallyMergedAndSwitchOffAutodetectManualMerge", doAPIEditRepository(baseCtx, &api.EditRepoOption{
  442. HasPullRequests: &trueBool,
  443. AllowManualMerge: &trueBool,
  444. AutodetectManualMerge: &falseBool,
  445. }))
  446. t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
  447. t.Run("PushToHeadBranch", doGitPushTestRepository(dstPath, "origin", headBranch))
  448. t.Run("CreateEmptyPullRequest", func(t *testing.T) {
  449. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t)
  450. assert.NoError(t, err)
  451. })
  452. lastCommitID = pr.Base.Sha
  453. t.Run("ManuallyMergePR", doAPIManuallyMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, lastCommitID, pr.Index))
  454. }
  455. }
  456. func doEnsureCanSeePull(ctx APITestContext, pr api.PullRequest) func(t *testing.T) {
  457. return func(t *testing.T) {
  458. req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), pr.Index))
  459. ctx.Session.MakeRequest(t, req, http.StatusOK)
  460. req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d/files", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), pr.Index))
  461. ctx.Session.MakeRequest(t, req, http.StatusOK)
  462. req = NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d/commits", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), pr.Index))
  463. ctx.Session.MakeRequest(t, req, http.StatusOK)
  464. }
  465. }
  466. func doEnsureDiffNoChange(ctx APITestContext, pr api.PullRequest, diffHash string, diffLength int) func(t *testing.T) {
  467. return func(t *testing.T) {
  468. req := NewRequest(t, "GET", fmt.Sprintf("/%s/%s/pulls/%d.diff", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), pr.Index))
  469. resp := ctx.Session.MakeRequestNilResponseHashSumRecorder(t, req, http.StatusOK)
  470. actual := string(resp.Hash.Sum(nil))
  471. actualLength := resp.Length
  472. equal := diffHash == actual
  473. assert.True(t, equal, "Unexpected change in the diff string: expected hash: %s size: %d but was actually: %s size: %d", hex.EncodeToString([]byte(diffHash)), diffLength, hex.EncodeToString([]byte(actual)), actualLength)
  474. }
  475. }
  476. func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) {
  477. return func(t *testing.T) {
  478. defer PrintCurrentTest(t)()
  479. // create a context for a currently non-existent repository
  480. ctx.Reponame = fmt.Sprintf("repo-tmp-push-create-%s", u.Scheme)
  481. u.Path = ctx.GitPath()
  482. // Create a temporary directory
  483. tmpDir, err := ioutil.TempDir("", ctx.Reponame)
  484. assert.NoError(t, err)
  485. defer util.RemoveAll(tmpDir)
  486. // Now create local repository to push as our test and set its origin
  487. t.Run("InitTestRepository", doGitInitTestRepository(tmpDir))
  488. t.Run("AddRemote", doGitAddRemote(tmpDir, "origin", u))
  489. // Disable "Push To Create" and attempt to push
  490. setting.Repository.EnablePushCreateUser = false
  491. t.Run("FailToPushAndCreateTestRepository", doGitPushTestRepositoryFail(tmpDir, "origin", "master"))
  492. // Enable "Push To Create"
  493. setting.Repository.EnablePushCreateUser = true
  494. // Assert that cloning from a non-existent repository does not create it and that it definitely wasn't create above
  495. t.Run("FailToCloneFromNonExistentRepository", doGitCloneFail(u))
  496. // Then "Push To Create"x
  497. t.Run("SuccessfullyPushAndCreateTestRepository", doGitPushTestRepository(tmpDir, "origin", "master"))
  498. // Finally, fetch repo from database and ensure the correct repository has been created
  499. repo, err := models.GetRepositoryByOwnerAndName(ctx.Username, ctx.Reponame)
  500. assert.NoError(t, err)
  501. assert.False(t, repo.IsEmpty)
  502. assert.True(t, repo.IsPrivate)
  503. // Now add a remote that is invalid to "Push To Create"
  504. invalidCtx := ctx
  505. invalidCtx.Reponame = fmt.Sprintf("invalid/repo-tmp-push-create-%s", u.Scheme)
  506. u.Path = invalidCtx.GitPath()
  507. t.Run("AddInvalidRemote", doGitAddRemote(tmpDir, "invalid", u))
  508. // Fail to "Push To Create" the invalid
  509. t.Run("FailToPushAndCreateInvalidTestRepository", doGitPushTestRepositoryFail(tmpDir, "invalid", "master"))
  510. }
  511. }
  512. func doBranchDelete(ctx APITestContext, owner, repo, branch string) func(*testing.T) {
  513. return func(t *testing.T) {
  514. csrf := GetCSRF(t, ctx.Session, fmt.Sprintf("/%s/%s/branches", url.PathEscape(owner), url.PathEscape(repo)))
  515. req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/branches/delete?name=%s", url.PathEscape(owner), url.PathEscape(repo), url.QueryEscape(branch)), map[string]string{
  516. "_csrf": csrf,
  517. })
  518. ctx.Session.MakeRequest(t, req, http.StatusOK)
  519. }
  520. }
  521. func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headBranch string) func(t *testing.T) {
  522. return func(t *testing.T) {
  523. defer PrintCurrentTest(t)()
  524. // skip this test if git version is low
  525. if git.CheckGitVersionAtLeast("2.29") != nil {
  526. return
  527. }
  528. gitRepo, err := git.OpenRepository(dstPath)
  529. if !assert.NoError(t, err) {
  530. return
  531. }
  532. defer gitRepo.Close()
  533. var (
  534. pr1, pr2 *models.PullRequest
  535. commit string
  536. )
  537. repo, err := models.GetRepositoryByOwnerAndName(ctx.Username, ctx.Reponame)
  538. if !assert.NoError(t, err) {
  539. return
  540. }
  541. pullNum := models.GetCount(t, &models.PullRequest{})
  542. t.Run("CreateHeadBranch", doGitCreateBranch(dstPath, headBranch))
  543. t.Run("AddCommit", func(t *testing.T) {
  544. err := ioutil.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content"), 0666)
  545. if !assert.NoError(t, err) {
  546. return
  547. }
  548. err = git.AddChanges(dstPath, true)
  549. assert.NoError(t, err)
  550. err = git.CommitChanges(dstPath, git.CommitChangesOptions{
  551. Committer: &git.Signature{
  552. Email: "user2@example.com",
  553. Name: "user2",
  554. When: time.Now(),
  555. },
  556. Author: &git.Signature{
  557. Email: "user2@example.com",
  558. Name: "user2",
  559. When: time.Now(),
  560. },
  561. Message: "Testing commit 1",
  562. })
  563. assert.NoError(t, err)
  564. commit, err = gitRepo.GetRefCommitID("HEAD")
  565. assert.NoError(t, err)
  566. })
  567. t.Run("Push", func(t *testing.T) {
  568. _, err := git.NewCommand("push", "origin", "HEAD:refs/for/master", "-o", "topic="+headBranch).RunInDir(dstPath)
  569. if !assert.NoError(t, err) {
  570. return
  571. }
  572. models.AssertCount(t, &models.PullRequest{}, pullNum+1)
  573. pr1 = models.AssertExistsAndLoadBean(t, &models.PullRequest{
  574. HeadRepoID: repo.ID,
  575. Flow: models.PullRequestFlowAGit,
  576. }).(*models.PullRequest)
  577. if !assert.NotEmpty(t, pr1) {
  578. return
  579. }
  580. prMsg, err := doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr1.Index)(t)
  581. if !assert.NoError(t, err) {
  582. return
  583. }
  584. assert.Equal(t, "user2/"+headBranch, pr1.HeadBranch)
  585. assert.Equal(t, false, prMsg.HasMerged)
  586. assert.Contains(t, "Testing commit 1", prMsg.Body)
  587. assert.Equal(t, commit, prMsg.Head.Sha)
  588. _, err = git.NewCommand("push", "origin", "HEAD:refs/for/master/test/"+headBranch).RunInDir(dstPath)
  589. if !assert.NoError(t, err) {
  590. return
  591. }
  592. models.AssertCount(t, &models.PullRequest{}, pullNum+2)
  593. pr2 = models.AssertExistsAndLoadBean(t, &models.PullRequest{
  594. HeadRepoID: repo.ID,
  595. Index: pr1.Index + 1,
  596. Flow: models.PullRequestFlowAGit,
  597. }).(*models.PullRequest)
  598. if !assert.NotEmpty(t, pr2) {
  599. return
  600. }
  601. prMsg, err = doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr2.Index)(t)
  602. if !assert.NoError(t, err) {
  603. return
  604. }
  605. assert.Equal(t, "user2/test/"+headBranch, pr2.HeadBranch)
  606. assert.Equal(t, false, prMsg.HasMerged)
  607. })
  608. if pr1 == nil || pr2 == nil {
  609. return
  610. }
  611. t.Run("AddCommit2", func(t *testing.T) {
  612. err := ioutil.WriteFile(path.Join(dstPath, "test_file"), []byte("## test content \n ## test content 2"), 0666)
  613. if !assert.NoError(t, err) {
  614. return
  615. }
  616. err = git.AddChanges(dstPath, true)
  617. assert.NoError(t, err)
  618. err = git.CommitChanges(dstPath, git.CommitChangesOptions{
  619. Committer: &git.Signature{
  620. Email: "user2@example.com",
  621. Name: "user2",
  622. When: time.Now(),
  623. },
  624. Author: &git.Signature{
  625. Email: "user2@example.com",
  626. Name: "user2",
  627. When: time.Now(),
  628. },
  629. Message: "Testing commit 2",
  630. })
  631. assert.NoError(t, err)
  632. commit, err = gitRepo.GetRefCommitID("HEAD")
  633. assert.NoError(t, err)
  634. })
  635. t.Run("Push2", func(t *testing.T) {
  636. _, err := git.NewCommand("push", "origin", "HEAD:refs/for/master", "-o", "topic="+headBranch).RunInDir(dstPath)
  637. if !assert.NoError(t, err) {
  638. return
  639. }
  640. models.AssertCount(t, &models.PullRequest{}, pullNum+2)
  641. prMsg, err := doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr1.Index)(t)
  642. if !assert.NoError(t, err) {
  643. return
  644. }
  645. assert.Equal(t, false, prMsg.HasMerged)
  646. assert.Equal(t, commit, prMsg.Head.Sha)
  647. _, err = git.NewCommand("push", "origin", "HEAD:refs/for/master/test/"+headBranch).RunInDir(dstPath)
  648. if !assert.NoError(t, err) {
  649. return
  650. }
  651. models.AssertCount(t, &models.PullRequest{}, pullNum+2)
  652. prMsg, err = doAPIGetPullRequest(*ctx, ctx.Username, ctx.Reponame, pr2.Index)(t)
  653. if !assert.NoError(t, err) {
  654. return
  655. }
  656. assert.Equal(t, false, prMsg.HasMerged)
  657. assert.Equal(t, commit, prMsg.Head.Sha)
  658. })
  659. t.Run("Merge", doAPIMergePullRequest(*ctx, ctx.Username, ctx.Reponame, pr1.Index))
  660. t.Run("CheckoutMasterAgain", doGitCheckoutBranch(dstPath, "master"))
  661. }
  662. }