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

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