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.

480 lines
14 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>
5 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
  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. // Make the user's default search path the created schema; this will affect new connections
  177. if _, err = db.Exec(fmt.Sprintf(`ALTER USER "%s" SET search_path = %s`, setting.Database.User, setting.Database.Schema)); err != nil {
  178. log.Fatalf("db.Exec: ALTER USER SET search_path: %v", err)
  179. }
  180. // Make the current connection's search the created schema
  181. if _, err = db.Exec(fmt.Sprintf(`SET search_path = %s`, setting.Database.Schema)); err != nil {
  182. log.Fatalf("db.Exec: ALTER USER SET search_path: %v", err)
  183. }
  184. case setting.Database.UseMSSQL:
  185. host, port := setting.ParseMSSQLHostPort(setting.Database.Host)
  186. db, err := sql.Open("mssql", fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
  187. host, port, "master", setting.Database.User, setting.Database.Passwd))
  188. if err != nil {
  189. log.Fatalf("sql.Open: %v", err)
  190. }
  191. 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 {
  192. log.Fatalf("db.Exec: %v", err)
  193. }
  194. defer db.Close()
  195. }
  196. routers.GlobalInit(graceful.GetManager().HammerContext())
  197. }
  198. func prepareTestEnv(t testing.TB, skip ...int) func() {
  199. t.Helper()
  200. ourSkip := 2
  201. if len(skip) > 0 {
  202. ourSkip += skip[0]
  203. }
  204. deferFn := PrintCurrentTest(t, ourSkip)
  205. assert.NoError(t, models.LoadFixtures())
  206. assert.NoError(t, util.RemoveAll(setting.RepoRootPath))
  207. assert.NoError(t, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
  208. setting.RepoRootPath))
  209. return deferFn
  210. }
  211. type TestSession struct {
  212. jar http.CookieJar
  213. }
  214. func (s *TestSession) GetCookie(name string) *http.Cookie {
  215. baseURL, err := url.Parse(setting.AppURL)
  216. if err != nil {
  217. return nil
  218. }
  219. for _, c := range s.jar.Cookies(baseURL) {
  220. if c.Name == name {
  221. return c
  222. }
  223. }
  224. return nil
  225. }
  226. func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  227. t.Helper()
  228. baseURL, err := url.Parse(setting.AppURL)
  229. assert.NoError(t, err)
  230. for _, c := range s.jar.Cookies(baseURL) {
  231. req.AddCookie(c)
  232. }
  233. resp := MakeRequest(t, req, expectedStatus)
  234. ch := http.Header{}
  235. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  236. cr := http.Request{Header: ch}
  237. s.jar.SetCookies(baseURL, cr.Cookies())
  238. return resp
  239. }
  240. func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
  241. t.Helper()
  242. baseURL, err := url.Parse(setting.AppURL)
  243. assert.NoError(t, err)
  244. for _, c := range s.jar.Cookies(baseURL) {
  245. req.AddCookie(c)
  246. }
  247. resp := MakeRequestNilResponseRecorder(t, req, expectedStatus)
  248. ch := http.Header{}
  249. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  250. cr := http.Request{Header: ch}
  251. s.jar.SetCookies(baseURL, cr.Cookies())
  252. return resp
  253. }
  254. const userPassword = "password"
  255. var loginSessionCache = make(map[string]*TestSession, 10)
  256. func emptyTestSession(t testing.TB) *TestSession {
  257. t.Helper()
  258. jar, err := cookiejar.New(nil)
  259. assert.NoError(t, err)
  260. return &TestSession{jar: jar}
  261. }
  262. func loginUser(t testing.TB, userName string) *TestSession {
  263. t.Helper()
  264. if session, ok := loginSessionCache[userName]; ok {
  265. return session
  266. }
  267. session := loginUserWithPassword(t, userName, userPassword)
  268. loginSessionCache[userName] = session
  269. return session
  270. }
  271. func loginUserWithPassword(t testing.TB, userName, password string) *TestSession {
  272. t.Helper()
  273. req := NewRequest(t, "GET", "/user/login")
  274. resp := MakeRequest(t, req, http.StatusOK)
  275. doc := NewHTMLParser(t, resp.Body)
  276. req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
  277. "_csrf": doc.GetCSRF(),
  278. "user_name": userName,
  279. "password": password,
  280. })
  281. resp = MakeRequest(t, req, http.StatusFound)
  282. ch := http.Header{}
  283. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  284. cr := http.Request{Header: ch}
  285. session := emptyTestSession(t)
  286. baseURL, err := url.Parse(setting.AppURL)
  287. assert.NoError(t, err)
  288. session.jar.SetCookies(baseURL, cr.Cookies())
  289. return session
  290. }
  291. //token has to be unique this counter take care of
  292. var tokenCounter int64
  293. func getTokenForLoggedInUser(t testing.TB, session *TestSession) string {
  294. t.Helper()
  295. tokenCounter++
  296. req := NewRequest(t, "GET", "/user/settings/applications")
  297. resp := session.MakeRequest(t, req, http.StatusOK)
  298. doc := NewHTMLParser(t, resp.Body)
  299. req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{
  300. "_csrf": doc.GetCSRF(),
  301. "name": fmt.Sprintf("api-testing-token-%d", tokenCounter),
  302. })
  303. resp = session.MakeRequest(t, req, http.StatusFound)
  304. req = NewRequest(t, "GET", "/user/settings/applications")
  305. resp = session.MakeRequest(t, req, http.StatusOK)
  306. htmlDoc := NewHTMLParser(t, resp.Body)
  307. token := htmlDoc.doc.Find(".ui.info p").Text()
  308. return token
  309. }
  310. func NewRequest(t testing.TB, method, urlStr string) *http.Request {
  311. t.Helper()
  312. return NewRequestWithBody(t, method, urlStr, nil)
  313. }
  314. func NewRequestf(t testing.TB, method, urlFormat string, args ...interface{}) *http.Request {
  315. t.Helper()
  316. return NewRequest(t, method, fmt.Sprintf(urlFormat, args...))
  317. }
  318. func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request {
  319. t.Helper()
  320. urlValues := url.Values{}
  321. for key, value := range values {
  322. urlValues[key] = []string{value}
  323. }
  324. req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode()))
  325. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  326. return req
  327. }
  328. func NewRequestWithJSON(t testing.TB, method, urlStr string, v interface{}) *http.Request {
  329. t.Helper()
  330. jsonBytes, err := json.Marshal(v)
  331. assert.NoError(t, err)
  332. req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes))
  333. req.Header.Add("Content-Type", "application/json")
  334. return req
  335. }
  336. func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request {
  337. t.Helper()
  338. request, err := http.NewRequest(method, urlStr, body)
  339. assert.NoError(t, err)
  340. request.RequestURI = urlStr
  341. return request
  342. }
  343. func AddBasicAuthHeader(request *http.Request, username string) *http.Request {
  344. request.SetBasicAuth(username, userPassword)
  345. return request
  346. }
  347. const NoExpectedStatus = -1
  348. func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  349. t.Helper()
  350. recorder := httptest.NewRecorder()
  351. mac.ServeHTTP(recorder, req)
  352. if expectedStatus != NoExpectedStatus {
  353. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  354. "Request: %s %s", req.Method, req.URL.String()) {
  355. logUnexpectedResponse(t, recorder)
  356. }
  357. }
  358. return recorder
  359. }
  360. func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
  361. t.Helper()
  362. recorder := NewNilResponseRecorder()
  363. mac.ServeHTTP(recorder, req)
  364. if expectedStatus != NoExpectedStatus {
  365. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  366. "Request: %s %s", req.Method, req.URL.String()) {
  367. logUnexpectedResponse(t, &recorder.ResponseRecorder)
  368. }
  369. }
  370. return recorder
  371. }
  372. // logUnexpectedResponse logs the contents of an unexpected response.
  373. func logUnexpectedResponse(t testing.TB, recorder *httptest.ResponseRecorder) {
  374. t.Helper()
  375. respBytes := recorder.Body.Bytes()
  376. if len(respBytes) == 0 {
  377. return
  378. } else if len(respBytes) < 500 {
  379. // if body is short, just log the whole thing
  380. t.Log("Response:", string(respBytes))
  381. return
  382. }
  383. // log the "flash" error message, if one exists
  384. // we must create a new buffer, so that we don't "use up" resp.Body
  385. htmlDoc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(respBytes))
  386. if err != nil {
  387. return // probably a non-HTML response
  388. }
  389. errMsg := htmlDoc.Find(".ui.negative.message").Text()
  390. if len(errMsg) > 0 {
  391. t.Log("A flash error message was found:", errMsg)
  392. }
  393. }
  394. func DecodeJSON(t testing.TB, resp *httptest.ResponseRecorder, v interface{}) {
  395. t.Helper()
  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, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
  414. setting.RepoRootPath))
  415. }