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 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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 getTokenForLoggedInUser(t testing.TB, session *TestSession) string {
  192. req := NewRequest(t, "GET", "/user/settings/applications")
  193. resp := session.MakeRequest(t, req, http.StatusOK)
  194. doc := NewHTMLParser(t, resp.Body)
  195. req = NewRequestWithValues(t, "POST", "/user/settings/applications", map[string]string{
  196. "_csrf": doc.GetCSRF(),
  197. "name": "api-testing-token",
  198. })
  199. resp = session.MakeRequest(t, req, http.StatusFound)
  200. req = NewRequest(t, "GET", "/user/settings/applications")
  201. resp = session.MakeRequest(t, req, http.StatusOK)
  202. htmlDoc := NewHTMLParser(t, resp.Body)
  203. token := htmlDoc.doc.Find(".ui.info p").Text()
  204. return token
  205. }
  206. func NewRequest(t testing.TB, method, urlStr string) *http.Request {
  207. return NewRequestWithBody(t, method, urlStr, nil)
  208. }
  209. func NewRequestf(t testing.TB, method, urlFormat string, args ...interface{}) *http.Request {
  210. return NewRequest(t, method, fmt.Sprintf(urlFormat, args...))
  211. }
  212. func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request {
  213. urlValues := url.Values{}
  214. for key, value := range values {
  215. urlValues[key] = []string{value}
  216. }
  217. req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode()))
  218. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  219. return req
  220. }
  221. func NewRequestWithJSON(t testing.TB, method, urlStr string, v interface{}) *http.Request {
  222. jsonBytes, err := json.Marshal(v)
  223. assert.NoError(t, err)
  224. req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes))
  225. req.Header.Add("Content-Type", "application/json")
  226. return req
  227. }
  228. func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request {
  229. request, err := http.NewRequest(method, urlStr, body)
  230. assert.NoError(t, err)
  231. request.RequestURI = urlStr
  232. return request
  233. }
  234. func AddBasicAuthHeader(request *http.Request, username string) *http.Request {
  235. request.SetBasicAuth(username, userPassword)
  236. return request
  237. }
  238. const NoExpectedStatus = -1
  239. func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  240. recorder := httptest.NewRecorder()
  241. mac.ServeHTTP(recorder, req)
  242. if expectedStatus != NoExpectedStatus {
  243. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  244. "Request: %s %s", req.Method, req.URL.String()) {
  245. logUnexpectedResponse(t, recorder)
  246. }
  247. }
  248. return recorder
  249. }
  250. // logUnexpectedResponse logs the contents of an unexpected response.
  251. func logUnexpectedResponse(t testing.TB, recorder *httptest.ResponseRecorder) {
  252. respBytes := recorder.Body.Bytes()
  253. if len(respBytes) == 0 {
  254. return
  255. } else if len(respBytes) < 500 {
  256. // if body is short, just log the whole thing
  257. t.Log("Response:", string(respBytes))
  258. return
  259. }
  260. // log the "flash" error message, if one exists
  261. // we must create a new buffer, so that we don't "use up" resp.Body
  262. htmlDoc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(respBytes))
  263. if err != nil {
  264. return // probably a non-HTML response
  265. }
  266. errMsg := htmlDoc.Find(".ui.negative.message").Text()
  267. if len(errMsg) > 0 {
  268. t.Log("A flash error message was found:", errMsg)
  269. }
  270. }
  271. func DecodeJSON(t testing.TB, resp *httptest.ResponseRecorder, v interface{}) {
  272. decoder := json.NewDecoder(resp.Body)
  273. assert.NoError(t, decoder.Decode(v))
  274. }
  275. func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
  276. req := NewRequest(t, "GET", urlStr)
  277. resp := session.MakeRequest(t, req, http.StatusOK)
  278. doc := NewHTMLParser(t, resp.Body)
  279. return doc.GetCSRF()
  280. }