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.

457 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>
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. "code.gitea.io/gitea/models"
  24. "code.gitea.io/gitea/modules/base"
  25. "code.gitea.io/gitea/modules/graceful"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/routers"
  28. "code.gitea.io/gitea/routers/routes"
  29. "gitea.com/macaron/macaron"
  30. "github.com/PuerkitoBio/goquery"
  31. "github.com/stretchr/testify/assert"
  32. "github.com/unknwon/com"
  33. "gopkg.in/testfixtures.v2"
  34. )
  35. var mac *macaron.Macaron
  36. type NilResponseRecorder struct {
  37. httptest.ResponseRecorder
  38. Length int
  39. }
  40. func (n *NilResponseRecorder) Write(b []byte) (int, error) {
  41. n.Length += len(b)
  42. return len(b), nil
  43. }
  44. // NewRecorder returns an initialized ResponseRecorder.
  45. func NewNilResponseRecorder() *NilResponseRecorder {
  46. return &NilResponseRecorder{
  47. ResponseRecorder: *httptest.NewRecorder(),
  48. }
  49. }
  50. func TestMain(m *testing.M) {
  51. managerCtx, cancel := context.WithCancel(context.Background())
  52. graceful.InitManager(managerCtx)
  53. defer cancel()
  54. initIntegrationTest()
  55. mac = routes.NewMacaron()
  56. routes.RegisterRoutes(mac)
  57. var helper testfixtures.Helper
  58. if setting.Database.UseMySQL {
  59. helper = &testfixtures.MySQL{}
  60. } else if setting.Database.UsePostgreSQL {
  61. helper = &testfixtures.PostgreSQL{}
  62. } else if setting.Database.UseSQLite3 {
  63. helper = &testfixtures.SQLite{}
  64. } else if setting.Database.UseMSSQL {
  65. helper = &testfixtures.SQLServer{}
  66. } else {
  67. fmt.Println("Unsupported RDBMS for integration tests")
  68. os.Exit(1)
  69. }
  70. err := models.InitFixtures(
  71. helper,
  72. path.Join(filepath.Dir(setting.AppPath), "models/fixtures/"),
  73. )
  74. if err != nil {
  75. fmt.Printf("Error initializing test database: %v\n", err)
  76. os.Exit(1)
  77. }
  78. exitCode := m.Run()
  79. writerCloser.t = nil
  80. if err = os.RemoveAll(setting.Indexer.IssuePath); err != nil {
  81. fmt.Printf("os.RemoveAll: %v\n", err)
  82. os.Exit(1)
  83. }
  84. if err = os.RemoveAll(setting.Indexer.RepoPath); err != nil {
  85. fmt.Printf("Unable to remove repo indexer: %v\n", err)
  86. os.Exit(1)
  87. }
  88. os.Exit(exitCode)
  89. }
  90. func initIntegrationTest() {
  91. giteaRoot := base.SetupGiteaRoot()
  92. if giteaRoot == "" {
  93. fmt.Println("Environment variable $GITEA_ROOT not set")
  94. os.Exit(1)
  95. }
  96. giteaBinary := "gitea"
  97. if runtime.GOOS == "windows" {
  98. giteaBinary += ".exe"
  99. }
  100. setting.AppPath = path.Join(giteaRoot, giteaBinary)
  101. if _, err := os.Stat(setting.AppPath); err != nil {
  102. fmt.Printf("Could not find gitea binary at %s\n", setting.AppPath)
  103. os.Exit(1)
  104. }
  105. giteaConf := os.Getenv("GITEA_CONF")
  106. if giteaConf == "" {
  107. fmt.Println("Environment variable $GITEA_CONF not set")
  108. os.Exit(1)
  109. } else if !path.IsAbs(giteaConf) {
  110. setting.CustomConf = path.Join(giteaRoot, giteaConf)
  111. } else {
  112. setting.CustomConf = giteaConf
  113. }
  114. setting.SetCustomPathAndConf("", "", "")
  115. setting.NewContext()
  116. os.RemoveAll(models.LocalCopyPath())
  117. setting.CheckLFSVersion()
  118. setting.InitDBConfig()
  119. switch {
  120. case setting.Database.UseMySQL:
  121. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/",
  122. setting.Database.User, setting.Database.Passwd, setting.Database.Host))
  123. defer db.Close()
  124. if err != nil {
  125. log.Fatalf("sql.Open: %v", err)
  126. }
  127. if _, err = db.Exec(fmt.Sprintf("CREATE DATABASE IF NOT EXISTS %s", setting.Database.Name)); err != nil {
  128. log.Fatalf("db.Exec: %v", err)
  129. }
  130. case setting.Database.UsePostgreSQL:
  131. db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s",
  132. setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.SSLMode))
  133. defer db.Close()
  134. if err != nil {
  135. log.Fatalf("sql.Open: %v", err)
  136. }
  137. dbrows, err := db.Query(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname = '%s'", setting.Database.Name))
  138. if err != nil {
  139. log.Fatalf("db.Query: %v", err)
  140. }
  141. defer dbrows.Close()
  142. if !dbrows.Next() {
  143. if _, err = db.Exec(fmt.Sprintf("CREATE DATABASE %s", setting.Database.Name)); err != nil {
  144. log.Fatalf("db.Exec: CREATE DATABASE: %v", err)
  145. }
  146. }
  147. // Check if we need to setup a specific schema
  148. if len(setting.Database.Schema) == 0 {
  149. break
  150. }
  151. db.Close()
  152. db, err = sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=%s",
  153. setting.Database.User, setting.Database.Passwd, setting.Database.Host, setting.Database.Name, setting.Database.SSLMode))
  154. // This is a different db object; requires a different Close()
  155. defer db.Close()
  156. if err != nil {
  157. log.Fatalf("sql.Open: %v", err)
  158. }
  159. schrows, err := db.Query(fmt.Sprintf("SELECT 1 FROM information_schema.schemata WHERE schema_name = '%s'", setting.Database.Schema))
  160. if err != nil {
  161. log.Fatalf("db.Query: %v", err)
  162. }
  163. defer schrows.Close()
  164. if !schrows.Next() {
  165. // Create and setup a DB schema
  166. if _, err = db.Exec(fmt.Sprintf("CREATE SCHEMA %s", setting.Database.Schema)); err != nil {
  167. log.Fatalf("db.Exec: CREATE SCHEMA: %v", err)
  168. }
  169. }
  170. // Make the user's default search path the created schema; this will affect new connections
  171. if _, err = db.Exec(fmt.Sprintf(`ALTER USER "%s" SET search_path = %s`, setting.Database.User, setting.Database.Schema)); err != nil {
  172. log.Fatalf("db.Exec: ALTER USER SET search_path: %v", err)
  173. }
  174. // Make the current connection's search the created schema
  175. if _, err = db.Exec(fmt.Sprintf(`SET search_path = %s`, setting.Database.Schema)); err != nil {
  176. log.Fatalf("db.Exec: ALTER USER SET search_path: %v", err)
  177. }
  178. case setting.Database.UseMSSQL:
  179. host, port := setting.ParseMSSQLHostPort(setting.Database.Host)
  180. db, err := sql.Open("mssql", fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
  181. host, port, "master", setting.Database.User, setting.Database.Passwd))
  182. if err != nil {
  183. log.Fatalf("sql.Open: %v", err)
  184. }
  185. 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 {
  186. log.Fatalf("db.Exec: %v", err)
  187. }
  188. defer db.Close()
  189. }
  190. routers.GlobalInit(graceful.GetManager().HammerContext())
  191. }
  192. func prepareTestEnv(t testing.TB, skip ...int) func() {
  193. t.Helper()
  194. ourSkip := 2
  195. if len(skip) > 0 {
  196. ourSkip += skip[0]
  197. }
  198. deferFn := PrintCurrentTest(t, ourSkip)
  199. assert.NoError(t, models.LoadFixtures())
  200. assert.NoError(t, os.RemoveAll(setting.RepoRootPath))
  201. assert.NoError(t, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
  202. setting.RepoRootPath))
  203. return deferFn
  204. }
  205. type TestSession struct {
  206. jar http.CookieJar
  207. }
  208. func (s *TestSession) GetCookie(name string) *http.Cookie {
  209. baseURL, err := url.Parse(setting.AppURL)
  210. if err != nil {
  211. return nil
  212. }
  213. for _, c := range s.jar.Cookies(baseURL) {
  214. if c.Name == name {
  215. return c
  216. }
  217. }
  218. return nil
  219. }
  220. func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  221. t.Helper()
  222. baseURL, err := url.Parse(setting.AppURL)
  223. assert.NoError(t, err)
  224. for _, c := range s.jar.Cookies(baseURL) {
  225. req.AddCookie(c)
  226. }
  227. resp := MakeRequest(t, req, expectedStatus)
  228. ch := http.Header{}
  229. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  230. cr := http.Request{Header: ch}
  231. s.jar.SetCookies(baseURL, cr.Cookies())
  232. return resp
  233. }
  234. func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
  235. t.Helper()
  236. baseURL, err := url.Parse(setting.AppURL)
  237. assert.NoError(t, err)
  238. for _, c := range s.jar.Cookies(baseURL) {
  239. req.AddCookie(c)
  240. }
  241. resp := MakeRequestNilResponseRecorder(t, req, expectedStatus)
  242. ch := http.Header{}
  243. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  244. cr := http.Request{Header: ch}
  245. s.jar.SetCookies(baseURL, cr.Cookies())
  246. return resp
  247. }
  248. const userPassword = "password"
  249. var loginSessionCache = make(map[string]*TestSession, 10)
  250. func emptyTestSession(t testing.TB) *TestSession {
  251. t.Helper()
  252. jar, err := cookiejar.New(nil)
  253. assert.NoError(t, err)
  254. return &TestSession{jar: jar}
  255. }
  256. func loginUser(t testing.TB, userName string) *TestSession {
  257. t.Helper()
  258. if session, ok := loginSessionCache[userName]; ok {
  259. return session
  260. }
  261. session := loginUserWithPassword(t, userName, userPassword)
  262. loginSessionCache[userName] = session
  263. return session
  264. }
  265. func loginUserWithPassword(t testing.TB, userName, password string) *TestSession {
  266. t.Helper()
  267. req := NewRequest(t, "GET", "/user/login")
  268. resp := MakeRequest(t, req, http.StatusOK)
  269. doc := NewHTMLParser(t, resp.Body)
  270. req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
  271. "_csrf": doc.GetCSRF(),
  272. "user_name": userName,
  273. "password": password,
  274. })
  275. resp = MakeRequest(t, req, http.StatusFound)
  276. ch := http.Header{}
  277. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  278. cr := http.Request{Header: ch}
  279. session := emptyTestSession(t)
  280. baseURL, err := url.Parse(setting.AppURL)
  281. assert.NoError(t, err)
  282. session.jar.SetCookies(baseURL, cr.Cookies())
  283. return session
  284. }
  285. func getTokenForLoggedInUser(t testing.TB, session *TestSession) string {
  286. t.Helper()
  287. req := NewRequest(t, "GET", "/user/settings/applications")
  288. resp := session.MakeRequest(t, req, http.StatusOK)
  289. doc := NewHTMLParser(t, resp.Body)
  290. req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{
  291. "_csrf": doc.GetCSRF(),
  292. "name": "api-testing-token",
  293. })
  294. resp = session.MakeRequest(t, req, http.StatusFound)
  295. req = NewRequest(t, "GET", "/user/settings/applications")
  296. resp = session.MakeRequest(t, req, http.StatusOK)
  297. htmlDoc := NewHTMLParser(t, resp.Body)
  298. token := htmlDoc.doc.Find(".ui.info p").Text()
  299. return token
  300. }
  301. func NewRequest(t testing.TB, method, urlStr string) *http.Request {
  302. t.Helper()
  303. return NewRequestWithBody(t, method, urlStr, nil)
  304. }
  305. func NewRequestf(t testing.TB, method, urlFormat string, args ...interface{}) *http.Request {
  306. t.Helper()
  307. return NewRequest(t, method, fmt.Sprintf(urlFormat, args...))
  308. }
  309. func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request {
  310. t.Helper()
  311. urlValues := url.Values{}
  312. for key, value := range values {
  313. urlValues[key] = []string{value}
  314. }
  315. req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode()))
  316. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  317. return req
  318. }
  319. func NewRequestWithJSON(t testing.TB, method, urlStr string, v interface{}) *http.Request {
  320. t.Helper()
  321. jsonBytes, err := json.Marshal(v)
  322. assert.NoError(t, err)
  323. req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes))
  324. req.Header.Add("Content-Type", "application/json")
  325. return req
  326. }
  327. func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request {
  328. t.Helper()
  329. request, err := http.NewRequest(method, urlStr, body)
  330. assert.NoError(t, err)
  331. request.RequestURI = urlStr
  332. return request
  333. }
  334. func AddBasicAuthHeader(request *http.Request, username string) *http.Request {
  335. request.SetBasicAuth(username, userPassword)
  336. return request
  337. }
  338. const NoExpectedStatus = -1
  339. func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  340. t.Helper()
  341. recorder := httptest.NewRecorder()
  342. mac.ServeHTTP(recorder, req)
  343. if expectedStatus != NoExpectedStatus {
  344. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  345. "Request: %s %s", req.Method, req.URL.String()) {
  346. logUnexpectedResponse(t, recorder)
  347. }
  348. }
  349. return recorder
  350. }
  351. func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
  352. t.Helper()
  353. recorder := NewNilResponseRecorder()
  354. mac.ServeHTTP(recorder, req)
  355. if expectedStatus != NoExpectedStatus {
  356. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  357. "Request: %s %s", req.Method, req.URL.String()) {
  358. logUnexpectedResponse(t, &recorder.ResponseRecorder)
  359. }
  360. }
  361. return recorder
  362. }
  363. // logUnexpectedResponse logs the contents of an unexpected response.
  364. func logUnexpectedResponse(t testing.TB, recorder *httptest.ResponseRecorder) {
  365. t.Helper()
  366. respBytes := recorder.Body.Bytes()
  367. if len(respBytes) == 0 {
  368. return
  369. } else if len(respBytes) < 500 {
  370. // if body is short, just log the whole thing
  371. t.Log("Response:", string(respBytes))
  372. return
  373. }
  374. // log the "flash" error message, if one exists
  375. // we must create a new buffer, so that we don't "use up" resp.Body
  376. htmlDoc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(respBytes))
  377. if err != nil {
  378. return // probably a non-HTML response
  379. }
  380. errMsg := htmlDoc.Find(".ui.negative.message").Text()
  381. if len(errMsg) > 0 {
  382. t.Log("A flash error message was found:", errMsg)
  383. }
  384. }
  385. func DecodeJSON(t testing.TB, resp *httptest.ResponseRecorder, v interface{}) {
  386. t.Helper()
  387. decoder := json.NewDecoder(resp.Body)
  388. assert.NoError(t, decoder.Decode(v))
  389. }
  390. func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
  391. t.Helper()
  392. req := NewRequest(t, "GET", urlStr)
  393. resp := session.MakeRequest(t, req, http.StatusOK)
  394. doc := NewHTMLParser(t, resp.Body)
  395. return doc.GetCSRF()
  396. }