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

integration_test.go 7.4KB

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