Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

git_test.go 21KB

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