Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

integration_test.go 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. os.Exit(m.Run())
  53. }
  54. func initIntegrationTest() {
  55. giteaRoot := os.Getenv("GITEA_ROOT")
  56. if giteaRoot == "" {
  57. fmt.Println("Environment variable $GITEA_ROOT not set")
  58. os.Exit(1)
  59. }
  60. setting.AppPath = path.Join(giteaRoot, "gitea")
  61. giteaConf := os.Getenv("GITEA_CONF")
  62. if giteaConf == "" {
  63. fmt.Println("Environment variable $GITEA_CONF not set")
  64. os.Exit(1)
  65. } else if !path.IsAbs(giteaConf) {
  66. setting.CustomConf = path.Join(giteaRoot, giteaConf)
  67. } else {
  68. setting.CustomConf = giteaConf
  69. }
  70. setting.NewContext()
  71. models.LoadConfigs()
  72. switch {
  73. case setting.UseMySQL:
  74. db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@tcp(%s)/",
  75. models.DbCfg.User, models.DbCfg.Passwd, models.DbCfg.Host))
  76. defer db.Close()
  77. if err != nil {
  78. log.Fatalf("sql.Open: %v", err)
  79. }
  80. if _, err = db.Exec("CREATE DATABASE IF NOT EXISTS testgitea"); err != nil {
  81. log.Fatalf("db.Exec: %v", err)
  82. }
  83. case setting.UsePostgreSQL:
  84. db, err := sql.Open("postgres", fmt.Sprintf("postgres://%s:%s@%s/?sslmode=%s",
  85. models.DbCfg.User, models.DbCfg.Passwd, models.DbCfg.Host, models.DbCfg.SSLMode))
  86. defer db.Close()
  87. if err != nil {
  88. log.Fatalf("sql.Open: %v", err)
  89. }
  90. rows, err := db.Query(fmt.Sprintf("SELECT 1 FROM pg_database WHERE datname = '%s'",
  91. models.DbCfg.Name))
  92. if err != nil {
  93. log.Fatalf("db.Query: %v", err)
  94. }
  95. defer rows.Close()
  96. if rows.Next() {
  97. break
  98. }
  99. if _, err = db.Exec("CREATE DATABASE testgitea"); err != nil {
  100. log.Fatalf("db.Exec: %v", err)
  101. }
  102. }
  103. routers.GlobalInit()
  104. }
  105. func prepareTestEnv(t testing.TB) {
  106. assert.NoError(t, models.LoadFixtures())
  107. assert.NoError(t, os.RemoveAll("integrations/gitea-integration"))
  108. assert.NoError(t, com.CopyDir("integrations/gitea-integration-meta", "integrations/gitea-integration"))
  109. }
  110. type TestSession struct {
  111. jar http.CookieJar
  112. }
  113. func (s *TestSession) GetCookie(name string) *http.Cookie {
  114. baseURL, err := url.Parse(setting.AppURL)
  115. if err != nil {
  116. return nil
  117. }
  118. for _, c := range s.jar.Cookies(baseURL) {
  119. if c.Name == name {
  120. return c
  121. }
  122. }
  123. return nil
  124. }
  125. func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *TestResponse {
  126. baseURL, err := url.Parse(setting.AppURL)
  127. assert.NoError(t, err)
  128. for _, c := range s.jar.Cookies(baseURL) {
  129. req.AddCookie(c)
  130. }
  131. resp := MakeRequest(t, req, expectedStatus)
  132. ch := http.Header{}
  133. ch.Add("Cookie", strings.Join(resp.Headers["Set-Cookie"], ";"))
  134. cr := http.Request{Header: ch}
  135. s.jar.SetCookies(baseURL, cr.Cookies())
  136. return resp
  137. }
  138. const userPassword = "password"
  139. func loginUser(t testing.TB, userName string) *TestSession {
  140. return loginUserWithPassword(t, userName, userPassword)
  141. }
  142. func loginUserWithPassword(t testing.TB, userName, password string) *TestSession {
  143. req := NewRequest(t, "GET", "/user/login")
  144. resp := MakeRequest(t, req, http.StatusOK)
  145. doc := NewHTMLParser(t, resp.Body)
  146. req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
  147. "_csrf": doc.GetCSRF(),
  148. "user_name": userName,
  149. "password": password,
  150. })
  151. resp = MakeRequest(t, req, http.StatusFound)
  152. ch := http.Header{}
  153. ch.Add("Cookie", strings.Join(resp.Headers["Set-Cookie"], ";"))
  154. cr := http.Request{Header: ch}
  155. jar, err := cookiejar.New(nil)
  156. assert.NoError(t, err)
  157. baseURL, err := url.Parse(setting.AppURL)
  158. assert.NoError(t, err)
  159. jar.SetCookies(baseURL, cr.Cookies())
  160. return &TestSession{jar: jar}
  161. }
  162. type TestResponseWriter struct {
  163. HeaderCode int
  164. Writer io.Writer
  165. Headers http.Header
  166. }
  167. func (w *TestResponseWriter) Header() http.Header {
  168. return w.Headers
  169. }
  170. func (w *TestResponseWriter) Write(b []byte) (int, error) {
  171. return w.Writer.Write(b)
  172. }
  173. func (w *TestResponseWriter) WriteHeader(n int) {
  174. w.HeaderCode = n
  175. }
  176. type TestResponse struct {
  177. HeaderCode int
  178. Body []byte
  179. Headers http.Header
  180. }
  181. func NewRequest(t testing.TB, method, urlStr string) *http.Request {
  182. return NewRequestWithBody(t, method, urlStr, nil)
  183. }
  184. func NewRequestf(t testing.TB, method, urlFormat string, args ...interface{}) *http.Request {
  185. return NewRequest(t, method, fmt.Sprintf(urlFormat, args...))
  186. }
  187. func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request {
  188. urlValues := url.Values{}
  189. for key, value := range values {
  190. urlValues[key] = []string{value}
  191. }
  192. req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode()))
  193. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  194. return req
  195. }
  196. func NewRequestWithJSON(t testing.TB, method, urlStr string, v interface{}) *http.Request {
  197. jsonBytes, err := json.Marshal(v)
  198. assert.NoError(t, err)
  199. req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes))
  200. req.Header.Add("Content-Type", "application/json")
  201. return req
  202. }
  203. func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request {
  204. request, err := http.NewRequest(method, urlStr, body)
  205. assert.NoError(t, err)
  206. request.RequestURI = urlStr
  207. return request
  208. }
  209. const NoExpectedStatus = -1
  210. func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *TestResponse {
  211. buffer := bytes.NewBuffer(nil)
  212. respWriter := &TestResponseWriter{
  213. Writer: buffer,
  214. Headers: make(map[string][]string),
  215. }
  216. mac.ServeHTTP(respWriter, req)
  217. if expectedStatus != NoExpectedStatus {
  218. assert.EqualValues(t, expectedStatus, respWriter.HeaderCode)
  219. }
  220. return &TestResponse{
  221. HeaderCode: respWriter.HeaderCode,
  222. Body: buffer.Bytes(),
  223. Headers: respWriter.Headers,
  224. }
  225. }
  226. func DecodeJSON(t testing.TB, resp *TestResponse, v interface{}) {
  227. decoder := json.NewDecoder(bytes.NewBuffer(resp.Body))
  228. assert.NoError(t, decoder.Decode(v))
  229. }
  230. func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
  231. req := NewRequest(t, "GET", urlStr)
  232. resp := session.MakeRequest(t, req, http.StatusOK)
  233. doc := NewHTMLParser(t, resp.Body)
  234. return doc.GetCSRF()
  235. }
  236. func RedirectURL(t testing.TB, resp *TestResponse) string {
  237. urlSlice := resp.Headers["Location"]
  238. assert.NotEmpty(t, urlSlice, "No redirect URL founds")
  239. return urlSlice[0]
  240. }