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.

393 lines
11 KiB

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