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.

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