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.

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