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.

308 lines
7.7 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/url"
  15. "os"
  16. "path"
  17. "strings"
  18. "testing"
  19. "code.gitea.io/gitea/models"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/routers"
  22. "code.gitea.io/gitea/routers/routes"
  23. "github.com/Unknwon/com"
  24. "github.com/stretchr/testify/assert"
  25. "gopkg.in/macaron.v1"
  26. "gopkg.in/testfixtures.v2"
  27. )
  28. var mac *macaron.Macaron
  29. func TestMain(m *testing.M) {
  30. initIntegrationTest()
  31. mac = routes.NewMacaron()
  32. routes.RegisterRoutes(mac)
  33. var helper testfixtures.Helper
  34. if setting.UseMySQL {
  35. helper = &testfixtures.MySQL{}
  36. } else if setting.UsePostgreSQL {
  37. helper = &testfixtures.PostgreSQL{}
  38. } else if setting.UseSQLite3 {
  39. helper = &testfixtures.SQLite{}
  40. } else {
  41. fmt.Println("Unsupported RDBMS for integration tests")
  42. os.Exit(1)
  43. }
  44. err := models.InitFixtures(
  45. helper,
  46. "models/fixtures/",
  47. )
  48. if err != nil {
  49. fmt.Printf("Error initializing test database: %v\n", err)
  50. os.Exit(1)
  51. }
  52. exitCode := m.Run()
  53. if err = os.RemoveAll(setting.Indexer.IssuePath); err != nil {
  54. fmt.Printf("os.RemoveAll: %v\n", err)
  55. os.Exit(1)
  56. }
  57. os.Exit(exitCode)
  58. }
  59. func initIntegrationTest() {
  60. giteaRoot := os.Getenv("GITEA_ROOT")
  61. if giteaRoot == "" {
  62. fmt.Println("Environment variable $GITEA_ROOT not set")
  63. os.Exit(1)
  64. }
  65. setting.AppPath = path.Join(giteaRoot, "gitea")
  66. if _, err := os.Stat(setting.AppPath); err != nil {
  67. fmt.Printf("Could not find gitea binary at %s\n", setting.AppPath)
  68. os.Exit(1)
  69. }
  70. giteaConf := os.Getenv("GITEA_CONF")
  71. if giteaConf == "" {
  72. fmt.Println("Environment variable $GITEA_CONF not set")
  73. os.Exit(1)
  74. } else if !path.IsAbs(giteaConf) {
  75. setting.CustomConf = path.Join(giteaRoot, giteaConf)
  76. } else {
  77. setting.CustomConf = giteaConf
  78. }
  79. setting.NewContext()
  80. models.LoadConfigs()
  81. switch {
  82. case setting.UseMySQL:
  83. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/",
  84. models.DbCfg.User, models.DbCfg.Passwd, models.DbCfg.Host))
  85. defer db.Close()
  86. if err != nil {
  87. log.Fatalf("sql.Open: %v", err)
  88. }
  89. if _, err = db.Exec("CREATE DATABASE IF NOT EXISTS testgitea"); err != nil {
  90. log.Fatalf("db.Exec: %v", err)
  91. }
  92. case setting.UsePostgreSQL:
  93. db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s",
  94. models.DbCfg.User, models.DbCfg.Passwd, models.DbCfg.Host, models.DbCfg.SSLMode))
  95. defer db.Close()
  96. if err != nil {
  97. log.Fatalf("sql.Open: %v", err)
  98. }
  99. rows, err := db.Query(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname = '%s'",
  100. models.DbCfg.Name))
  101. if err != nil {
  102. log.Fatalf("db.Query: %v", err)
  103. }
  104. defer rows.Close()
  105. if rows.Next() {
  106. break
  107. }
  108. if _, err = db.Exec("CREATE DATABASE testgitea"); err != nil {
  109. log.Fatalf("db.Exec: %v", err)
  110. }
  111. }
  112. routers.GlobalInit()
  113. }
  114. func prepareTestEnv(t testing.TB) {
  115. assert.NoError(t, models.LoadFixtures())
  116. assert.NoError(t, os.RemoveAll(setting.RepoRootPath))
  117. assert.NoError(t, com.CopyDir("integrations/gitea-repositories-meta", setting.RepoRootPath))
  118. }
  119. type TestSession struct {
  120. jar http.CookieJar
  121. }
  122. func (s *TestSession) GetCookie(name string) *http.Cookie {
  123. baseURL, err := url.Parse(setting.AppURL)
  124. if err != nil {
  125. return nil
  126. }
  127. for _, c := range s.jar.Cookies(baseURL) {
  128. if c.Name == name {
  129. return c
  130. }
  131. }
  132. return nil
  133. }
  134. func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *TestResponse {
  135. baseURL, err := url.Parse(setting.AppURL)
  136. assert.NoError(t, err)
  137. for _, c := range s.jar.Cookies(baseURL) {
  138. req.AddCookie(c)
  139. }
  140. resp := MakeRequest(t, req, expectedStatus)
  141. ch := http.Header{}
  142. ch.Add("Cookie", strings.Join(resp.Headers["Set-Cookie"], ";"))
  143. cr := http.Request{Header: ch}
  144. s.jar.SetCookies(baseURL, cr.Cookies())
  145. return resp
  146. }
  147. const userPassword = "password"
  148. var loginSessionCache = make(map[string]*TestSession, 10)
  149. func emptyTestSession(t testing.TB) *TestSession {
  150. jar, err := cookiejar.New(nil)
  151. assert.NoError(t, err)
  152. return &TestSession{jar: jar}
  153. }
  154. func loginUser(t testing.TB, userName string) *TestSession {
  155. if session, ok := loginSessionCache[userName]; ok {
  156. return session
  157. }
  158. session := loginUserWithPassword(t, userName, userPassword)
  159. loginSessionCache[userName] = session
  160. return session
  161. }
  162. func loginUserWithPassword(t testing.TB, userName, password string) *TestSession {
  163. req := NewRequest(t, "GET", "/user/login")
  164. resp := MakeRequest(t, req, http.StatusOK)
  165. doc := NewHTMLParser(t, resp.Body)
  166. req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
  167. "_csrf": doc.GetCSRF(),
  168. "user_name": userName,
  169. "password": password,
  170. })
  171. resp = MakeRequest(t, req, http.StatusFound)
  172. ch := http.Header{}
  173. ch.Add("Cookie", strings.Join(resp.Headers["Set-Cookie"], ";"))
  174. cr := http.Request{Header: ch}
  175. session := emptyTestSession(t)
  176. baseURL, err := url.Parse(setting.AppURL)
  177. assert.NoError(t, err)
  178. session.jar.SetCookies(baseURL, cr.Cookies())
  179. return session
  180. }
  181. type TestResponseWriter struct {
  182. HeaderCode int
  183. Writer io.Writer
  184. Headers http.Header
  185. }
  186. func (w *TestResponseWriter) Header() http.Header {
  187. return w.Headers
  188. }
  189. func (w *TestResponseWriter) Write(b []byte) (int, error) {
  190. return w.Writer.Write(b)
  191. }
  192. func (w *TestResponseWriter) WriteHeader(n int) {
  193. w.HeaderCode = n
  194. }
  195. type TestResponse struct {
  196. HeaderCode int
  197. Body []byte
  198. Headers http.Header
  199. }
  200. func NewRequest(t testing.TB, method, urlStr string) *http.Request {
  201. return NewRequestWithBody(t, method, urlStr, nil)
  202. }
  203. func NewRequestf(t testing.TB, method, urlFormat string, args ...interface{}) *http.Request {
  204. return NewRequest(t, method, fmt.Sprintf(urlFormat, args...))
  205. }
  206. func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request {
  207. urlValues := url.Values{}
  208. for key, value := range values {
  209. urlValues[key] = []string{value}
  210. }
  211. req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode()))
  212. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  213. return req
  214. }
  215. func NewRequestWithJSON(t testing.TB, method, urlStr string, v interface{}) *http.Request {
  216. jsonBytes, err := json.Marshal(v)
  217. assert.NoError(t, err)
  218. req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes))
  219. req.Header.Add("Content-Type", "application/json")
  220. return req
  221. }
  222. func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request {
  223. request, err := http.NewRequest(method, urlStr, body)
  224. assert.NoError(t, err)
  225. request.RequestURI = urlStr
  226. return request
  227. }
  228. const NoExpectedStatus = -1
  229. func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *TestResponse {
  230. buffer := bytes.NewBuffer(nil)
  231. respWriter := &TestResponseWriter{
  232. Writer: buffer,
  233. Headers: make(map[string][]string),
  234. }
  235. mac.ServeHTTP(respWriter, req)
  236. if expectedStatus != NoExpectedStatus {
  237. assert.EqualValues(t, expectedStatus, respWriter.HeaderCode,
  238. "Request URL: %s", req.URL.String())
  239. }
  240. return &TestResponse{
  241. HeaderCode: respWriter.HeaderCode,
  242. Body: buffer.Bytes(),
  243. Headers: respWriter.Headers,
  244. }
  245. }
  246. func DecodeJSON(t testing.TB, resp *TestResponse, v interface{}) {
  247. decoder := json.NewDecoder(bytes.NewBuffer(resp.Body))
  248. assert.NoError(t, decoder.Decode(v))
  249. }
  250. func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
  251. req := NewRequest(t, "GET", urlStr)
  252. resp := session.MakeRequest(t, req, http.StatusOK)
  253. doc := NewHTMLParser(t, resp.Body)
  254. return doc.GetCSRF()
  255. }
  256. func RedirectURL(t testing.TB, resp *TestResponse) string {
  257. urlSlice := resp.Headers["Location"]
  258. assert.NotEmpty(t, urlSlice, "No redirect URL founds")
  259. return urlSlice[0]
  260. }