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.

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