You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

integration_test.go 14 kB

Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
Template Repositories (#8768) * Start work on templates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Continue work Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix IsTemplate vs IsGenerated Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tabs vs spaces * Tabs vs Spaces * Add templates to API & start adding tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix integration tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Remove unused User Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move template tests to existing repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Minor re-check updates and cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test cleanup Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix optionalbool Signed-off-by: jolheiser <john.olheiser@gmail.com> * make fmt Signed-off-by: jolheiser <john.olheiser@gmail.com> * Test fixes and icon change Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add new user and repo for tests Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests (finally) Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update meta repo with env variables Signed-off-by: jolheiser <john.olheiser@gmail.com> * Move generation to create page Combine with repo create template Modify API search to prioritize owner for repo Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix tests and coverage Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix swagger and JS lint Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix API searching for own private repos Signed-off-by: jolheiser <john.olheiser@gmail.com> * Change wording Signed-off-by: jolheiser <john.olheiser@gmail.com> * Fix repo search test. User had a private repo that didn't show up Signed-off-by: jolheiser <john.olheiser@gmail.com> * Another search test fix Signed-off-by: jolheiser <john.olheiser@gmail.com> * Clarify git content Co-Authored-By: guillep2k <18600385+guillep2k@users.noreply.github.com> * Feedback updates Signed-off-by: jolheiser <john.olheiser@gmail.com> * Add topics WIP Signed-off-by: jolheiser <john.olheiser@gmail.com> * Finish adding topics Signed-off-by: jolheiser <john.olheiser@gmail.com> * Update locale Signed-off-by: jolheiser <john.olheiser@gmail.com>
5 years ago
Move macaron to chi (#14293) Use [chi](https://github.com/go-chi/chi) instead of the forked [macaron](https://gitea.com/macaron/macaron). Since macaron and chi have conflicts with session share, this big PR becomes a have-to thing. According my previous idea, we can replace macaron step by step but I'm wrong. :( Below is a list of big changes on this PR. - [x] Define `context.ResponseWriter` interface with an implementation `context.Response`. - [x] Use chi instead of macaron, and also a customize `Route` to wrap chi so that the router usage is similar as before. - [x] Create different routers for `web`, `api`, `internal` and `install` so that the codes will be more clear and no magic . - [x] Use https://github.com/unrolled/render instead of macaron's internal render - [x] Use https://github.com/NYTimes/gziphandler instead of https://gitea.com/macaron/gzip - [x] Use https://gitea.com/go-chi/session which is a modified version of https://gitea.com/macaron/session and removed `nodb` support since it will not be maintained. **BREAK** - [x] Use https://gitea.com/go-chi/captcha which is a modified version of https://gitea.com/macaron/captcha - [x] Use https://gitea.com/go-chi/cache which is a modified version of https://gitea.com/macaron/cache - [x] Use https://gitea.com/go-chi/binding which is a modified version of https://gitea.com/macaron/binding - [x] Use https://github.com/go-chi/cors instead of https://gitea.com/macaron/cors - [x] Dropped https://gitea.com/macaron/i18n and make a new one in `code.gitea.io/gitea/modules/translation` - [x] Move validation form structs from `code.gitea.io/gitea/modules/auth` to `code.gitea.io/gitea/modules/forms` to avoid dependency cycle. - [x] Removed macaron log service because it's not need any more. **BREAK** - [x] All form structs have to be get by `web.GetForm(ctx)` in the route function but not as a function parameter on routes definition. - [x] Move Git HTTP protocol implementation to use routers directly. - [x] Fix the problem that chi routes don't support trailing slash but macaron did. - [x] `/api/v1/swagger` now will be redirect to `/api/swagger` but not render directly so that `APIContext` will not create a html render. Notices: - Chi router don't support request with trailing slash - Integration test `TestUserHeatmap` maybe mysql version related. It's failed on my macOS(mysql 5.7.29 installed via brew) but succeed on CI. Co-authored-by: 6543 <6543@obermui.de>
4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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. "bytes"
  7. "context"
  8. "database/sql"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "net/http/cookiejar"
  13. "net/http/httptest"
  14. "net/url"
  15. "os"
  16. "path"
  17. "path/filepath"
  18. "runtime"
  19. "strings"
  20. "testing"
  21. "time"
  22. "code.gitea.io/gitea/models"
  23. "code.gitea.io/gitea/modules/base"
  24. "code.gitea.io/gitea/modules/graceful"
  25. "code.gitea.io/gitea/modules/log"
  26. "code.gitea.io/gitea/modules/queue"
  27. "code.gitea.io/gitea/modules/setting"
  28. "code.gitea.io/gitea/modules/storage"
  29. "code.gitea.io/gitea/modules/util"
  30. "code.gitea.io/gitea/modules/web"
  31. "code.gitea.io/gitea/routers"
  32. "code.gitea.io/gitea/routers/routes"
  33. "github.com/PuerkitoBio/goquery"
  34. jsoniter "github.com/json-iterator/go"
  35. "github.com/stretchr/testify/assert"
  36. )
  37. var c *web.Route
  38. type NilResponseRecorder struct {
  39. httptest.ResponseRecorder
  40. Length int
  41. }
  42. func (n *NilResponseRecorder) Write(b []byte) (int, error) {
  43. n.Length += len(b)
  44. return len(b), nil
  45. }
  46. // NewRecorder returns an initialized ResponseRecorder.
  47. func NewNilResponseRecorder() *NilResponseRecorder {
  48. return &NilResponseRecorder{
  49. ResponseRecorder: *httptest.NewRecorder(),
  50. }
  51. }
  52. func TestMain(m *testing.M) {
  53. defer log.Close()
  54. managerCtx, cancel := context.WithCancel(context.Background())
  55. graceful.InitManager(managerCtx)
  56. defer cancel()
  57. initIntegrationTest()
  58. c = routes.NormalRoutes()
  59. // integration test settings...
  60. if setting.Cfg != nil {
  61. testingCfg := setting.Cfg.Section("integration-tests")
  62. slowTest = testingCfg.Key("SLOW_TEST").MustDuration(slowTest)
  63. slowFlush = testingCfg.Key("SLOW_FLUSH").MustDuration(slowFlush)
  64. }
  65. if os.Getenv("GITEA_SLOW_TEST_TIME") != "" {
  66. duration, err := time.ParseDuration(os.Getenv("GITEA_SLOW_TEST_TIME"))
  67. if err == nil {
  68. slowTest = duration
  69. }
  70. }
  71. if os.Getenv("GITEA_SLOW_FLUSH_TIME") != "" {
  72. duration, err := time.ParseDuration(os.Getenv("GITEA_SLOW_FLUSH_TIME"))
  73. if err == nil {
  74. slowFlush = duration
  75. }
  76. }
  77. err := models.InitFixtures(
  78. path.Join(filepath.Dir(setting.AppPath), "models/fixtures/"),
  79. )
  80. if err != nil {
  81. fmt.Printf("Error initializing test database: %v\n", err)
  82. os.Exit(1)
  83. }
  84. exitCode := m.Run()
  85. writerCloser.t = nil
  86. if err = util.RemoveAll(setting.Indexer.IssuePath); err != nil {
  87. fmt.Printf("util.RemoveAll: %v\n", err)
  88. os.Exit(1)
  89. }
  90. if err = util.RemoveAll(setting.Indexer.RepoPath); err != nil {
  91. fmt.Printf("Unable to remove repo indexer: %v\n", err)
  92. os.Exit(1)
  93. }
  94. os.Exit(exitCode)
  95. }
  96. func initIntegrationTest() {
  97. giteaRoot := base.SetupGiteaRoot()
  98. if giteaRoot == "" {
  99. fmt.Println("Environment variable $GITEA_ROOT not set")
  100. os.Exit(1)
  101. }
  102. giteaBinary := "gitea"
  103. if runtime.GOOS == "windows" {
  104. giteaBinary += ".exe"
  105. }
  106. setting.AppPath = path.Join(giteaRoot, giteaBinary)
  107. if _, err := os.Stat(setting.AppPath); err != nil {
  108. fmt.Printf("Could not find gitea binary at %s\n", setting.AppPath)
  109. os.Exit(1)
  110. }
  111. giteaConf := os.Getenv("GITEA_CONF")
  112. if giteaConf == "" {
  113. fmt.Println("Environment variable $GITEA_CONF not set")
  114. os.Exit(1)
  115. } else if !path.IsAbs(giteaConf) {
  116. setting.CustomConf = path.Join(giteaRoot, giteaConf)
  117. } else {
  118. setting.CustomConf = giteaConf
  119. }
  120. setting.SetCustomPathAndConf("", "", "")
  121. setting.NewContext()
  122. util.RemoveAll(models.LocalCopyPath())
  123. setting.CheckLFSVersion()
  124. setting.InitDBConfig()
  125. if err := storage.Init(); err != nil {
  126. fmt.Printf("Init storage failed: %v", err)
  127. os.Exit(1)
  128. }
  129. switch {
  130. case setting.Database.UseMySQL:
  131. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/",
  132. setting.Database.User, setting.Database.Passwd, setting.Database.Host))
  133. defer db.Close()
  134. if err != nil {
  135. log.Fatal("sql.Open: %v", err)
  136. }
  137. if _, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", setting.Database.Name)); err != nil {
  138. log.Fatal("db.Exec: %v", err)
  139. }
  140. case setting.Database.UsePostgreSQL:
  141. db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s",
  142. setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.SSLMode))
  143. defer db.Close()
  144. if err != nil {
  145. log.Fatal("sql.Open: %v", err)
  146. }
  147. dbrows, err := db.Query(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname = '%s'", setting.Database.Name))
  148. if err != nil {
  149. log.Fatal("db.Query: %v", err)
  150. }
  151. defer dbrows.Close()
  152. if !dbrows.Next() {
  153. if _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", setting.Database.Name)); err != nil {
  154. log.Fatal("db.Exec: CREATE DATABASE: %v", err)
  155. }
  156. }
  157. // Check if we need to setup a specific schema
  158. if len(setting.Database.Schema) == 0 {
  159. break
  160. }
  161. db.Close()
  162. db, err = sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s",
  163. setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.Name, setting.Database.SSLMode))
  164. // This is a different db object; requires a different Close()
  165. defer db.Close()
  166. if err != nil {
  167. log.Fatal("sql.Open: %v", err)
  168. }
  169. schrows, err := db.Query(fmt.Sprintf("SELECT 1 FROM information_schema.schemata WHERE schema_name = '%s'", setting.Database.Schema))
  170. if err != nil {
  171. log.Fatal("db.Query: %v", err)
  172. }
  173. defer schrows.Close()
  174. if !schrows.Next() {
  175. // Create and setup a DB schema
  176. if _, err = db.Exec(fmt.Sprintf("CREATE SCHEMA %s", setting.Database.Schema)); err != nil {
  177. log.Fatal("db.Exec: CREATE SCHEMA: %v", err)
  178. }
  179. }
  180. case setting.Database.UseMSSQL:
  181. host, port := setting.ParseMSSQLHostPort(setting.Database.Host)
  182. db, err := sql.Open("mssql", fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
  183. host, port, "master", setting.Database.User, setting.Database.Passwd))
  184. if err != nil {
  185. log.Fatal("sql.Open: %v", err)
  186. }
  187. if _, err := db.Exec(fmt.Sprintf("If(db_id(N'%s') IS NULL) BEGIN CREATE DATABASE %s; END;", setting.Database.Name, setting.Database.Name)); err != nil {
  188. log.Fatal("db.Exec: %v", err)
  189. }
  190. defer db.Close()
  191. }
  192. routers.GlobalInit(graceful.GetManager().HammerContext())
  193. }
  194. func prepareTestEnv(t testing.TB, skip ...int) func() {
  195. t.Helper()
  196. ourSkip := 2
  197. if len(skip) > 0 {
  198. ourSkip += skip[0]
  199. }
  200. deferFn := PrintCurrentTest(t, ourSkip)
  201. assert.NoError(t, models.LoadFixtures())
  202. assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
  203. assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
  204. return deferFn
  205. }
  206. type TestSession struct {
  207. jar http.CookieJar
  208. }
  209. func (s *TestSession) GetCookie(name string) *http.Cookie {
  210. baseURL, err := url.Parse(setting.AppURL)
  211. if err != nil {
  212. return nil
  213. }
  214. for _, c := range s.jar.Cookies(baseURL) {
  215. if c.Name == name {
  216. return c
  217. }
  218. }
  219. return nil
  220. }
  221. func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  222. t.Helper()
  223. baseURL, err := url.Parse(setting.AppURL)
  224. assert.NoError(t, err)
  225. for _, c := range s.jar.Cookies(baseURL) {
  226. req.AddCookie(c)
  227. }
  228. resp := MakeRequest(t, req, expectedStatus)
  229. ch := http.Header{}
  230. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  231. cr := http.Request{Header: ch}
  232. s.jar.SetCookies(baseURL, cr.Cookies())
  233. return resp
  234. }
  235. func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
  236. t.Helper()
  237. baseURL, err := url.Parse(setting.AppURL)
  238. assert.NoError(t, err)
  239. for _, c := range s.jar.Cookies(baseURL) {
  240. req.AddCookie(c)
  241. }
  242. resp := MakeRequestNilResponseRecorder(t, req, expectedStatus)
  243. ch := http.Header{}
  244. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  245. cr := http.Request{Header: ch}
  246. s.jar.SetCookies(baseURL, cr.Cookies())
  247. return resp
  248. }
  249. const userPassword = "password"
  250. var loginSessionCache = make(map[string]*TestSession, 10)
  251. func emptyTestSession(t testing.TB) *TestSession {
  252. t.Helper()
  253. jar, err := cookiejar.New(nil)
  254. assert.NoError(t, err)
  255. return &TestSession{jar: jar}
  256. }
  257. func loginUser(t testing.TB, userName string) *TestSession {
  258. t.Helper()
  259. if session, ok := loginSessionCache[userName]; ok {
  260. return session
  261. }
  262. session := loginUserWithPassword(t, userName, userPassword)
  263. loginSessionCache[userName] = session
  264. return session
  265. }
  266. func loginUserWithPassword(t testing.TB, userName, password string) *TestSession {
  267. t.Helper()
  268. req := NewRequest(t, "GET", "/user/login")
  269. resp := MakeRequest(t, req, http.StatusOK)
  270. doc := NewHTMLParser(t, resp.Body)
  271. req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
  272. "_csrf": doc.GetCSRF(),
  273. "user_name": userName,
  274. "password": password,
  275. })
  276. resp = MakeRequest(t, req, http.StatusFound)
  277. ch := http.Header{}
  278. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  279. cr := http.Request{Header: ch}
  280. session := emptyTestSession(t)
  281. baseURL, err := url.Parse(setting.AppURL)
  282. assert.NoError(t, err)
  283. session.jar.SetCookies(baseURL, cr.Cookies())
  284. return session
  285. }
  286. //token has to be unique this counter take care of
  287. var tokenCounter int64
  288. func getTokenForLoggedInUser(t testing.TB, session *TestSession) string {
  289. t.Helper()
  290. tokenCounter++
  291. req := NewRequest(t, "GET", "/user/settings/applications")
  292. resp := session.MakeRequest(t, req, http.StatusOK)
  293. doc := NewHTMLParser(t, resp.Body)
  294. req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{
  295. "_csrf": doc.GetCSRF(),
  296. "name": fmt.Sprintf("api-testing-token-%d", tokenCounter),
  297. })
  298. resp = session.MakeRequest(t, req, http.StatusFound)
  299. req = NewRequest(t, "GET", "/user/settings/applications")
  300. resp = session.MakeRequest(t, req, http.StatusOK)
  301. htmlDoc := NewHTMLParser(t, resp.Body)
  302. token := htmlDoc.doc.Find(".ui.info p").Text()
  303. return token
  304. }
  305. func NewRequest(t testing.TB, method, urlStr string) *http.Request {
  306. t.Helper()
  307. return NewRequestWithBody(t, method, urlStr, nil)
  308. }
  309. func NewRequestf(t testing.TB, method, urlFormat string, args ...interface{}) *http.Request {
  310. t.Helper()
  311. return NewRequest(t, method, fmt.Sprintf(urlFormat, args...))
  312. }
  313. func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request {
  314. t.Helper()
  315. urlValues := url.Values{}
  316. for key, value := range values {
  317. urlValues[key] = []string{value}
  318. }
  319. req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode()))
  320. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  321. return req
  322. }
  323. func NewRequestWithJSON(t testing.TB, method, urlStr string, v interface{}) *http.Request {
  324. t.Helper()
  325. json := jsoniter.ConfigCompatibleWithStandardLibrary
  326. jsonBytes, err := json.Marshal(v)
  327. assert.NoError(t, err)
  328. req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes))
  329. req.Header.Add("Content-Type", "application/json")
  330. return req
  331. }
  332. func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request {
  333. t.Helper()
  334. if !strings.HasPrefix(urlStr, "http") && !strings.HasPrefix(urlStr, "/") {
  335. urlStr = "/" + urlStr
  336. }
  337. request, err := http.NewRequest(method, urlStr, body)
  338. assert.NoError(t, err)
  339. request.RequestURI = urlStr
  340. return request
  341. }
  342. func AddBasicAuthHeader(request *http.Request, username string) *http.Request {
  343. request.SetBasicAuth(username, userPassword)
  344. return request
  345. }
  346. const NoExpectedStatus = -1
  347. func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  348. t.Helper()
  349. recorder := httptest.NewRecorder()
  350. c.ServeHTTP(recorder, req)
  351. if expectedStatus != NoExpectedStatus {
  352. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  353. "Request: %s %s", req.Method, req.URL.String()) {
  354. logUnexpectedResponse(t, recorder)
  355. }
  356. }
  357. return recorder
  358. }
  359. func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
  360. t.Helper()
  361. recorder := NewNilResponseRecorder()
  362. c.ServeHTTP(recorder, req)
  363. if expectedStatus != NoExpectedStatus {
  364. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  365. "Request: %s %s", req.Method, req.URL.String()) {
  366. logUnexpectedResponse(t, &recorder.ResponseRecorder)
  367. }
  368. }
  369. return recorder
  370. }
  371. // logUnexpectedResponse logs the contents of an unexpected response.
  372. func logUnexpectedResponse(t testing.TB, recorder *httptest.ResponseRecorder) {
  373. t.Helper()
  374. respBytes := recorder.Body.Bytes()
  375. if len(respBytes) == 0 {
  376. return
  377. } else if len(respBytes) < 500 {
  378. // if body is short, just log the whole thing
  379. t.Log("Response:", string(respBytes))
  380. return
  381. }
  382. // log the "flash" error message, if one exists
  383. // we must create a new buffer, so that we don't "use up" resp.Body
  384. htmlDoc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(respBytes))
  385. if err != nil {
  386. return // probably a non-HTML response
  387. }
  388. errMsg := htmlDoc.Find(".ui.negative.message").Text()
  389. if len(errMsg) > 0 {
  390. t.Log("A flash error message was found:", errMsg)
  391. }
  392. }
  393. func DecodeJSON(t testing.TB, resp *httptest.ResponseRecorder, v interface{}) {
  394. t.Helper()
  395. json := jsoniter.ConfigCompatibleWithStandardLibrary
  396. decoder := json.NewDecoder(resp.Body)
  397. assert.NoError(t, decoder.Decode(v))
  398. }
  399. func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
  400. t.Helper()
  401. req := NewRequest(t, "GET", urlStr)
  402. resp := session.MakeRequest(t, req, http.StatusOK)
  403. doc := NewHTMLParser(t, resp.Body)
  404. return doc.GetCSRF()
  405. }
  406. // resetFixtures flushes queues, reloads fixtures and resets test repositories within a single test.
  407. // Most tests should call defer prepareTestEnv(t)() (or have onGiteaRun do that for them) but sometimes
  408. // within a single test this is required
  409. func resetFixtures(t *testing.T) {
  410. assert.NoError(t, queue.GetManager().FlushAll(context.Background(), -1))
  411. assert.NoError(t, models.LoadFixtures())
  412. assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
  413. assert.NoError(t, util.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"), setting.RepoRootPath))
  414. }