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.

integration_test.go 9.4KB

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