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.

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