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/base"
  23. "code.gitea.io/gitea/modules/setting"
  24. "code.gitea.io/gitea/routers"
  25. "code.gitea.io/gitea/routers/routes"
  26. "github.com/PuerkitoBio/goquery"
  27. "github.com/Unknwon/com"
  28. "github.com/stretchr/testify/assert"
  29. "gopkg.in/macaron.v1"
  30. "gopkg.in/testfixtures.v2"
  31. )
  32. var mac *macaron.Macaron
  33. type NilResponseRecorder struct {
  34. httptest.ResponseRecorder
  35. Length int
  36. }
  37. func (n *NilResponseRecorder) Write(b []byte) (int, error) {
  38. n.Length += len(b)
  39. return len(b), nil
  40. }
  41. // NewRecorder returns an initialized ResponseRecorder.
  42. func NewNilResponseRecorder() *NilResponseRecorder {
  43. return &NilResponseRecorder{
  44. ResponseRecorder: *httptest.NewRecorder(),
  45. }
  46. }
  47. func TestMain(m *testing.M) {
  48. initIntegrationTest()
  49. mac = routes.NewMacaron()
  50. routes.RegisterRoutes(mac)
  51. var helper testfixtures.Helper
  52. if setting.UseMySQL {
  53. helper = &testfixtures.MySQL{}
  54. } else if setting.UsePostgreSQL {
  55. helper = &testfixtures.PostgreSQL{}
  56. } else if setting.UseSQLite3 {
  57. helper = &testfixtures.SQLite{}
  58. } else if setting.UseMSSQL {
  59. helper = &testfixtures.SQLServer{}
  60. } else {
  61. fmt.Println("Unsupported RDBMS for integration tests")
  62. os.Exit(1)
  63. }
  64. err := models.InitFixtures(
  65. helper,
  66. path.Join(filepath.Dir(setting.AppPath), "models/fixtures/"),
  67. )
  68. if err != nil {
  69. fmt.Printf("Error initializing test database: %v\n", err)
  70. os.Exit(1)
  71. }
  72. exitCode := m.Run()
  73. writerCloser.t = nil
  74. if err = os.RemoveAll(setting.Indexer.IssuePath); err != nil {
  75. fmt.Printf("os.RemoveAll: %v\n", err)
  76. os.Exit(1)
  77. }
  78. if err = os.RemoveAll(setting.Indexer.RepoPath); err != nil {
  79. fmt.Printf("Unable to remove repo indexer: %v\n", err)
  80. os.Exit(1)
  81. }
  82. os.Exit(exitCode)
  83. }
  84. func initIntegrationTest() {
  85. giteaRoot := base.SetupGiteaRoot()
  86. if giteaRoot == "" {
  87. fmt.Println("Environment variable $GITEA_ROOT not set")
  88. os.Exit(1)
  89. }
  90. setting.AppPath = path.Join(giteaRoot, "gitea")
  91. if _, err := os.Stat(setting.AppPath); err != nil {
  92. fmt.Printf("Could not find gitea binary at %s\n", setting.AppPath)
  93. os.Exit(1)
  94. }
  95. giteaConf := os.Getenv("GITEA_CONF")
  96. if giteaConf == "" {
  97. fmt.Println("Environment variable $GITEA_CONF not set")
  98. os.Exit(1)
  99. } else if !path.IsAbs(giteaConf) {
  100. setting.CustomConf = path.Join(giteaRoot, giteaConf)
  101. } else {
  102. setting.CustomConf = giteaConf
  103. }
  104. setting.SetCustomPathAndConf("", "", "")
  105. setting.NewContext()
  106. setting.CheckLFSVersion()
  107. models.LoadConfigs()
  108. switch {
  109. case setting.UseMySQL:
  110. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/",
  111. models.DbCfg.User, models.DbCfg.Passwd, models.DbCfg.Host))
  112. defer db.Close()
  113. if err != nil {
  114. log.Fatalf("sql.Open: %v", err)
  115. }
  116. if _, err = db.Exec("CREATE DATABASE IF NOT EXISTS testgitea"); err != nil {
  117. log.Fatalf("db.Exec: %v", err)
  118. }
  119. case setting.UsePostgreSQL:
  120. db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s",
  121. models.DbCfg.User, models.DbCfg.Passwd, models.DbCfg.Host, models.DbCfg.SSLMode))
  122. defer db.Close()
  123. if err != nil {
  124. log.Fatalf("sql.Open: %v", err)
  125. }
  126. rows, err := db.Query(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname = '%s'", models.DbCfg.Name))
  127. if err != nil {
  128. log.Fatalf("db.Query: %v", err)
  129. }
  130. defer rows.Close()
  131. if rows.Next() {
  132. break
  133. }
  134. if _, err = db.Exec("CREATE DATABASE testgitea"); err != nil {
  135. log.Fatalf("db.Exec: %v", err)
  136. }
  137. case setting.UseMSSQL:
  138. host, port := models.ParseMSSQLHostPort(models.DbCfg.Host)
  139. db, err := sql.Open("mssql", fmt.Sprintf("server=%s; port=%s; database=%s; user id=%s; password=%s;",
  140. host, port, "master", models.DbCfg.User, models.DbCfg.Passwd))
  141. if err != nil {
  142. log.Fatalf("sql.Open: %v", err)
  143. }
  144. if _, err := db.Exec("If(db_id(N'gitea') IS NULL) BEGIN CREATE DATABASE gitea; END;"); err != nil {
  145. log.Fatalf("db.Exec: %v", err)
  146. }
  147. defer db.Close()
  148. }
  149. routers.GlobalInit()
  150. }
  151. func prepareTestEnv(t testing.TB, skip ...int) {
  152. ourSkip := 2
  153. if len(skip) > 0 {
  154. ourSkip += skip[0]
  155. }
  156. PrintCurrentTest(t, ourSkip)
  157. assert.NoError(t, models.LoadFixtures())
  158. assert.NoError(t, os.RemoveAll(setting.RepoRootPath))
  159. assert.NoError(t, os.RemoveAll(models.LocalCopyPath()))
  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.Header()["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.Header()["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.Header()["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. }