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.

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