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.

470 lines
13 KiB

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>
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>
4 years ago
  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. "encoding/json"
  10. "fmt"
  11. "io"
  12. "log"
  13. "net/http"
  14. "net/http/cookiejar"
  15. "net/http/httptest"
  16. "net/url"
  17. "os"
  18. "path"
  19. "path/filepath"
  20. "runtime"
  21. "strings"
  22. "testing"
  23. "time"
  24. "code.gitea.io/gitea/models"
  25. "code.gitea.io/gitea/modules/base"
  26. "code.gitea.io/gitea/modules/graceful"
  27. "code.gitea.io/gitea/modules/queue"
  28. "code.gitea.io/gitea/modules/setting"
  29. "code.gitea.io/gitea/modules/util"
  30. "code.gitea.io/gitea/routers"
  31. "code.gitea.io/gitea/routers/routes"
  32. "gitea.com/macaron/macaron"
  33. "github.com/PuerkitoBio/goquery"
  34. "github.com/stretchr/testify/assert"
  35. "github.com/unknwon/com"
  36. )
  37. var mac *macaron.Macaron
  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. managerCtx, cancel := context.WithCancel(context.Background())
  54. graceful.InitManager(managerCtx)
  55. defer cancel()
  56. initIntegrationTest()
  57. mac = routes.NewMacaron()
  58. routes.RegisterRoutes(mac)
  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. switch {
  126. case setting.Database.UseMySQL:
  127. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/",
  128. setting.Database.User, setting.Database.Passwd, setting.Database.Host))
  129. defer db.Close()
  130. if err != nil {
  131. log.Fatalf("sql.Open: %v", err)
  132. }
  133. if _, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", setting.Database.Name)); err != nil {
  134. log.Fatalf("db.Exec: %v", err)
  135. }
  136. case setting.Database.UsePostgreSQL:
  137. db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s",
  138. setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.SSLMode))
  139. defer db.Close()
  140. if err != nil {
  141. log.Fatalf("sql.Open: %v", err)
  142. }
  143. dbrows, err := db.Query(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname = '%s'", setting.Database.Name))
  144. if err != nil {
  145. log.Fatalf("db.Query: %v", err)
  146. }
  147. defer dbrows.Close()
  148. if !dbrows.Next() {
  149. if _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", setting.Database.Name)); err != nil {
  150. log.Fatalf("db.Exec: CREATE DATABASE: %v", err)
  151. }
  152. }
  153. // Check if we need to setup a specific schema
  154. if len(setting.Database.Schema) == 0 {
  155. break
  156. }
  157. db.Close()
  158. db, err = sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s",
  159. setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.Name, setting.Database.SSLMode))
  160. // This is a different db object; requires a different Close()
  161. defer db.Close()
  162. if err != nil {
  163. log.Fatalf("sql.Open: %v", err)
  164. }
  165. schrows, err := db.Query(fmt.Sprintf("SELECT 1 FROM information_schema.schemata WHERE schema_name = '%s'", setting.Database.Schema))
  166. if err != nil {
  167. log.Fatalf("db.Query: %v", err)
  168. }
  169. defer schrows.Close()
  170. if !schrows.Next() {
  171. // Create and setup a DB schema
  172. if _, err = db.Exec(fmt.Sprintf("CREATE SCHEMA %s", setting.Database.Schema)); err != nil {
  173. log.Fatalf("db.Exec: CREATE SCHEMA: %v", err)
  174. }
  175. }
  176. case setting.Database.UseMSSQL:
  177. host, port := setting.ParseMSSQLHostPort(setting.Database.Host)
  178. db, err := sql.Open("mssql", fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
  179. host, port, "master", setting.Database.User, setting.Database.Passwd))
  180. if err != nil {
  181. log.Fatalf("sql.Open: %v", err)
  182. }
  183. 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 {
  184. log.Fatalf("db.Exec: %v", err)
  185. }
  186. defer db.Close()
  187. }
  188. routers.GlobalInit(graceful.GetManager().HammerContext())
  189. }
  190. func prepareTestEnv(t testing.TB, skip ...int) func() {
  191. t.Helper()
  192. ourSkip := 2
  193. if len(skip) > 0 {
  194. ourSkip += skip[0]
  195. }
  196. deferFn := PrintCurrentTest(t, ourSkip)
  197. assert.NoError(t, models.LoadFixtures())
  198. assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
  199. assert.NoError(t, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
  200. setting.RepoRootPath))
  201. return deferFn
  202. }
  203. type TestSession struct {
  204. jar http.CookieJar
  205. }
  206. func (s *TestSession) GetCookie(name string) *http.Cookie {
  207. baseURL, err := url.Parse(setting.AppURL)
  208. if err != nil {
  209. return nil
  210. }
  211. for _, c := range s.jar.Cookies(baseURL) {
  212. if c.Name == name {
  213. return c
  214. }
  215. }
  216. return nil
  217. }
  218. func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  219. t.Helper()
  220. baseURL, err := url.Parse(setting.AppURL)
  221. assert.NoError(t, err)
  222. for _, c := range s.jar.Cookies(baseURL) {
  223. req.AddCookie(c)
  224. }
  225. resp := MakeRequest(t, req, expectedStatus)
  226. ch := http.Header{}
  227. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  228. cr := http.Request{Header: ch}
  229. s.jar.SetCookies(baseURL, cr.Cookies())
  230. return resp
  231. }
  232. func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
  233. t.Helper()
  234. baseURL, err := url.Parse(setting.AppURL)
  235. assert.NoError(t, err)
  236. for _, c := range s.jar.Cookies(baseURL) {
  237. req.AddCookie(c)
  238. }
  239. resp := MakeRequestNilResponseRecorder(t, req, expectedStatus)
  240. ch := http.Header{}
  241. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  242. cr := http.Request{Header: ch}
  243. s.jar.SetCookies(baseURL, cr.Cookies())
  244. return resp
  245. }
  246. const userPassword = "password"
  247. var loginSessionCache = make(map[string]*TestSession, 10)
  248. func emptyTestSession(t testing.TB) *TestSession {
  249. t.Helper()
  250. jar, err := cookiejar.New(nil)
  251. assert.NoError(t, err)
  252. return &TestSession{jar: jar}
  253. }
  254. func loginUser(t testing.TB, userName string) *TestSession {
  255. t.Helper()
  256. if session, ok := loginSessionCache[userName]; ok {
  257. return session
  258. }
  259. session := loginUserWithPassword(t, userName, userPassword)
  260. loginSessionCache[userName] = session
  261. return session
  262. }
  263. func loginUserWithPassword(t testing.TB, userName, password string) *TestSession {
  264. t.Helper()
  265. req := NewRequest(t, "GET", "/user/login")
  266. resp := MakeRequest(t, req, http.StatusOK)
  267. doc := NewHTMLParser(t, resp.Body)
  268. req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
  269. "_csrf": doc.GetCSRF(),
  270. "user_name": userName,
  271. "password": password,
  272. })
  273. resp = MakeRequest(t, req, http.StatusFound)
  274. ch := http.Header{}
  275. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  276. cr := http.Request{Header: ch}
  277. session := emptyTestSession(t)
  278. baseURL, err := url.Parse(setting.AppURL)
  279. assert.NoError(t, err)
  280. session.jar.SetCookies(baseURL, cr.Cookies())
  281. return session
  282. }
  283. //token has to be unique this counter take care of
  284. var tokenCounter int64
  285. func getTokenForLoggedInUser(t testing.TB, session *TestSession) string {
  286. t.Helper()
  287. tokenCounter++
  288. req := NewRequest(t, "GET", "/user/settings/applications")
  289. resp := session.MakeRequest(t, req, http.StatusOK)
  290. doc := NewHTMLParser(t, resp.Body)
  291. req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{
  292. "_csrf": doc.GetCSRF(),
  293. "name": fmt.Sprintf("api-testing-token-%d", tokenCounter),
  294. })
  295. resp = session.MakeRequest(t, req, http.StatusFound)
  296. req = NewRequest(t, "GET", "/user/settings/applications")
  297. resp = session.MakeRequest(t, req, http.StatusOK)
  298. htmlDoc := NewHTMLParser(t, resp.Body)
  299. token := htmlDoc.doc.Find(".ui.info p").Text()
  300. return token
  301. }
  302. func NewRequest(t testing.TB, method, urlStr string) *http.Request {
  303. t.Helper()
  304. return NewRequestWithBody(t, method, urlStr, nil)
  305. }
  306. func NewRequestf(t testing.TB, method, urlFormat string, args ...interface{}) *http.Request {
  307. t.Helper()
  308. return NewRequest(t, method, fmt.Sprintf(urlFormat, args...))
  309. }
  310. func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request {
  311. t.Helper()
  312. urlValues := url.Values{}
  313. for key, value := range values {
  314. urlValues[key] = []string{value}
  315. }
  316. req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode()))
  317. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  318. return req
  319. }
  320. func NewRequestWithJSON(t testing.TB, method, urlStr string, v interface{}) *http.Request {
  321. t.Helper()
  322. jsonBytes, err := json.Marshal(v)
  323. assert.NoError(t, err)
  324. req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes))
  325. req.Header.Add("Content-Type", "application/json")
  326. return req
  327. }
  328. func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request {
  329. t.Helper()
  330. request, err := http.NewRequest(method, urlStr, body)
  331. assert.NoError(t, err)
  332. request.RequestURI = urlStr
  333. return request
  334. }
  335. func AddBasicAuthHeader(request *http.Request, username string) *http.Request {
  336. request.SetBasicAuth(username, userPassword)
  337. return request
  338. }
  339. const NoExpectedStatus = -1
  340. func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  341. t.Helper()
  342. recorder := httptest.NewRecorder()
  343. mac.ServeHTTP(recorder, req)
  344. if expectedStatus != NoExpectedStatus {
  345. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  346. "Request: %s %s", req.Method, req.URL.String()) {
  347. logUnexpectedResponse(t, recorder)
  348. }
  349. }
  350. return recorder
  351. }
  352. func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
  353. t.Helper()
  354. recorder := NewNilResponseRecorder()
  355. mac.ServeHTTP(recorder, req)
  356. if expectedStatus != NoExpectedStatus {
  357. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  358. "Request: %s %s", req.Method, req.URL.String()) {
  359. logUnexpectedResponse(t, &recorder.ResponseRecorder)
  360. }
  361. }
  362. return recorder
  363. }
  364. // logUnexpectedResponse logs the contents of an unexpected response.
  365. func logUnexpectedResponse(t testing.TB, recorder *httptest.ResponseRecorder) {
  366. t.Helper()
  367. respBytes := recorder.Body.Bytes()
  368. if len(respBytes) == 0 {
  369. return
  370. } else if len(respBytes) < 500 {
  371. // if body is short, just log the whole thing
  372. t.Log("Response:", string(respBytes))
  373. return
  374. }
  375. // log the "flash" error message, if one exists
  376. // we must create a new buffer, so that we don't "use up" resp.Body
  377. htmlDoc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(respBytes))
  378. if err != nil {
  379. return // probably a non-HTML response
  380. }
  381. errMsg := htmlDoc.Find(".ui.negative.message").Text()
  382. if len(errMsg) > 0 {
  383. t.Log("A flash error message was found:", errMsg)
  384. }
  385. }
  386. func DecodeJSON(t testing.TB, resp *httptest.ResponseRecorder, v interface{}) {
  387. t.Helper()
  388. decoder := json.NewDecoder(resp.Body)
  389. assert.NoError(t, decoder.Decode(v))
  390. }
  391. func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
  392. t.Helper()
  393. req := NewRequest(t, "GET", urlStr)
  394. resp := session.MakeRequest(t, req, http.StatusOK)
  395. doc := NewHTMLParser(t, resp.Body)
  396. return doc.GetCSRF()
  397. }
  398. // resetFixtures flushes queues, reloads fixtures and resets test repositories within a single test.
  399. // Most tests should call defer prepareTestEnv(t)() (or have onGiteaRun do that for them) but sometimes
  400. // within a single test this is required
  401. func resetFixtures(t *testing.T) {
  402. assert.NoError(t, queue.GetManager().FlushAll(context.Background(), -1))
  403. assert.NoError(t, models.LoadFixtures())
  404. assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
  405. assert.NoError(t, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
  406. setting.RepoRootPath))
  407. }