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

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