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

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