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.

237 lines
5.6 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. "fmt"
  9. "io"
  10. "log"
  11. "net/http"
  12. "net/http/cookiejar"
  13. "net/url"
  14. "os"
  15. "path"
  16. "strings"
  17. "testing"
  18. "code.gitea.io/gitea/models"
  19. "code.gitea.io/gitea/modules/setting"
  20. "code.gitea.io/gitea/routers"
  21. "code.gitea.io/gitea/routers/routes"
  22. "github.com/Unknwon/com"
  23. "github.com/stretchr/testify/assert"
  24. "gopkg.in/macaron.v1"
  25. "gopkg.in/testfixtures.v2"
  26. )
  27. var mac *macaron.Macaron
  28. func TestMain(m *testing.M) {
  29. initIntegrationTest()
  30. mac = routes.NewMacaron()
  31. routes.RegisterRoutes(mac)
  32. var helper testfixtures.Helper
  33. if setting.UseMySQL {
  34. helper = &testfixtures.MySQL{}
  35. } else if setting.UsePostgreSQL {
  36. helper = &testfixtures.PostgreSQL{}
  37. } else if setting.UseSQLite3 {
  38. helper = &testfixtures.SQLite{}
  39. } else {
  40. fmt.Println("Unsupported RDBMS for integration tests")
  41. os.Exit(1)
  42. }
  43. err := models.InitFixtures(
  44. helper,
  45. "models/fixtures/",
  46. )
  47. if err != nil {
  48. fmt.Printf("Error initializing test database: %v\n", err)
  49. os.Exit(1)
  50. }
  51. os.Exit(m.Run())
  52. }
  53. func initIntegrationTest() {
  54. giteaRoot := os.Getenv("GITEA_ROOT")
  55. if giteaRoot == "" {
  56. fmt.Println("Environment variable $GITEA_ROOT not set")
  57. os.Exit(1)
  58. }
  59. setting.AppPath = path.Join(giteaRoot, "gitea")
  60. giteaConf := os.Getenv("GITEA_CONF")
  61. if giteaConf == "" {
  62. fmt.Println("Environment variable $GITEA_CONF not set")
  63. os.Exit(1)
  64. } else if !path.IsAbs(giteaConf) {
  65. setting.CustomConf = path.Join(giteaRoot, giteaConf)
  66. } else {
  67. setting.CustomConf = giteaConf
  68. }
  69. setting.NewContext()
  70. models.LoadConfigs()
  71. switch {
  72. case setting.UseMySQL:
  73. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/",
  74. models.DbCfg.User, models.DbCfg.Passwd, models.DbCfg.Host))
  75. defer db.Close()
  76. if err != nil {
  77. log.Fatalf("sql.Open: %v", err)
  78. }
  79. if _, err = db.Exec("CREATE DATABASE IF NOT EXISTS testgitea"); err != nil {
  80. log.Fatalf("db.Exec: %v", err)
  81. }
  82. case setting.UsePostgreSQL:
  83. db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s",
  84. models.DbCfg.User, models.DbCfg.Passwd, models.DbCfg.Host, models.DbCfg.SSLMode))
  85. defer db.Close()
  86. if err != nil {
  87. log.Fatalf("sql.Open: %v", err)
  88. }
  89. rows, err := db.Query(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname = '%s'",
  90. models.DbCfg.Name))
  91. if err != nil {
  92. log.Fatalf("db.Query: %v", err)
  93. }
  94. defer rows.Close()
  95. if rows.Next() {
  96. break
  97. }
  98. if _, err = db.Exec("CREATE DATABASE testgitea"); err != nil {
  99. log.Fatalf("db.Exec: %v", err)
  100. }
  101. }
  102. routers.GlobalInit()
  103. }
  104. func prepareTestEnv(t *testing.T) {
  105. assert.NoError(t, models.LoadFixtures())
  106. assert.NoError(t, os.RemoveAll("integrations/gitea-integration"))
  107. assert.NoError(t, com.CopyDir("integrations/gitea-integration-meta", "integrations/gitea-integration"))
  108. }
  109. type TestSession struct {
  110. jar http.CookieJar
  111. }
  112. func (s *TestSession) GetCookie(name string) *http.Cookie {
  113. baseURL, err := url.Parse(setting.AppURL)
  114. if err != nil {
  115. return nil
  116. }
  117. for _, c := range s.jar.Cookies(baseURL) {
  118. if c.Name == name {
  119. return c
  120. }
  121. }
  122. return nil
  123. }
  124. func (s *TestSession) MakeRequest(t *testing.T, req *http.Request) *TestResponse {
  125. baseURL, err := url.Parse(setting.AppURL)
  126. assert.NoError(t, err)
  127. for _, c := range s.jar.Cookies(baseURL) {
  128. req.AddCookie(c)
  129. }
  130. resp := MakeRequest(req)
  131. ch := http.Header{}
  132. ch.Add("Cookie", strings.Join(resp.Headers["Set-Cookie"], ";"))
  133. cr := http.Request{Header: ch}
  134. s.jar.SetCookies(baseURL, cr.Cookies())
  135. return resp
  136. }
  137. func loginUser(t *testing.T, userName, password string) *TestSession {
  138. req := NewRequest(t, "GET", "/user/login")
  139. resp := MakeRequest(req)
  140. assert.EqualValues(t, http.StatusOK, resp.HeaderCode)
  141. doc, err := NewHtmlParser(resp.Body)
  142. assert.NoError(t, err)
  143. req = NewRequestBody(t, "POST", "/user/login",
  144. bytes.NewBufferString(url.Values{
  145. "_csrf": []string{doc.GetInputValueByName("_csrf")},
  146. "user_name": []string{userName},
  147. "password": []string{password},
  148. }.Encode()),
  149. )
  150. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  151. resp = MakeRequest(req)
  152. assert.EqualValues(t, http.StatusFound, resp.HeaderCode)
  153. ch := http.Header{}
  154. ch.Add("Cookie", strings.Join(resp.Headers["Set-Cookie"], ";"))
  155. cr := http.Request{Header: ch}
  156. jar, err := cookiejar.New(nil)
  157. assert.NoError(t, err)
  158. baseURL, err := url.Parse(setting.AppURL)
  159. assert.NoError(t, err)
  160. jar.SetCookies(baseURL, cr.Cookies())
  161. return &TestSession{jar: jar}
  162. }
  163. type TestResponseWriter struct {
  164. HeaderCode int
  165. Writer io.Writer
  166. Headers http.Header
  167. }
  168. func (w *TestResponseWriter) Header() http.Header {
  169. return w.Headers
  170. }
  171. func (w *TestResponseWriter) Write(b []byte) (int, error) {
  172. return w.Writer.Write(b)
  173. }
  174. func (w *TestResponseWriter) WriteHeader(n int) {
  175. w.HeaderCode = n
  176. }
  177. type TestResponse struct {
  178. HeaderCode int
  179. Body []byte
  180. Headers http.Header
  181. }
  182. func NewRequest(t *testing.T, method, url string) *http.Request {
  183. return NewRequestBody(t, method, url, nil)
  184. }
  185. func NewRequestBody(t *testing.T, method, url string, body io.Reader) *http.Request {
  186. request, err := http.NewRequest(method, url, body)
  187. assert.NoError(t, err)
  188. request.RequestURI = url
  189. return request
  190. }
  191. func MakeRequest(req *http.Request) *TestResponse {
  192. buffer := bytes.NewBuffer(nil)
  193. respWriter := &TestResponseWriter{
  194. Writer: buffer,
  195. Headers: make(map[string][]string),
  196. }
  197. mac.ServeHTTP(respWriter, req)
  198. return &TestResponse{
  199. HeaderCode: respWriter.HeaderCode,
  200. Body: buffer.Bytes(),
  201. Headers: respWriter.Headers,
  202. }
  203. }