You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

integration_test.go 7.6 kB

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, os.RemoveAll(models.LocalCopyPath()))
  124. assert.NoError(t, com.CopyDir(path.Join(filepath.Dir(setting.AppPath), "integrations/gitea-repositories-meta"),
  125. setting.RepoRootPath))
  126. }
  127. type TestSession struct {
  128. jar http.CookieJar
  129. }
  130. func (s *TestSession) GetCookie(name string) *http.Cookie {
  131. baseURL, err := url.Parse(setting.AppURL)
  132. if err != nil {
  133. return nil
  134. }
  135. for _, c := range s.jar.Cookies(baseURL) {
  136. if c.Name == name {
  137. return c
  138. }
  139. }
  140. return nil
  141. }
  142. func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  143. baseURL, err := url.Parse(setting.AppURL)
  144. assert.NoError(t, err)
  145. for _, c := range s.jar.Cookies(baseURL) {
  146. req.AddCookie(c)
  147. }
  148. resp := MakeRequest(t, req, expectedStatus)
  149. ch := http.Header{}
  150. ch.Add("Cookie", strings.Join(resp.HeaderMap["Set-Cookie"], ";"))
  151. cr := http.Request{Header: ch}
  152. s.jar.SetCookies(baseURL, cr.Cookies())
  153. return resp
  154. }
  155. const userPassword = "password"
  156. var loginSessionCache = make(map[string]*TestSession, 10)
  157. func emptyTestSession(t testing.TB) *TestSession {
  158. jar, err := cookiejar.New(nil)
  159. assert.NoError(t, err)
  160. return &TestSession{jar: jar}
  161. }
  162. func loginUser(t testing.TB, userName string) *TestSession {
  163. if session, ok := loginSessionCache[userName]; ok {
  164. return session
  165. }
  166. session := loginUserWithPassword(t, userName, userPassword)
  167. loginSessionCache[userName] = session
  168. return session
  169. }
  170. func loginUserWithPassword(t testing.TB, userName, password string) *TestSession {
  171. req := NewRequest(t, "GET", "/user/login")
  172. resp := MakeRequest(t, req, http.StatusOK)
  173. doc := NewHTMLParser(t, resp.Body)
  174. req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
  175. "_csrf": doc.GetCSRF(),
  176. "user_name": userName,
  177. "password": password,
  178. })
  179. resp = MakeRequest(t, req, http.StatusFound)
  180. ch := http.Header{}
  181. ch.Add("Cookie", strings.Join(resp.HeaderMap["Set-Cookie"], ";"))
  182. cr := http.Request{Header: ch}
  183. session := emptyTestSession(t)
  184. baseURL, err := url.Parse(setting.AppURL)
  185. assert.NoError(t, err)
  186. session.jar.SetCookies(baseURL, cr.Cookies())
  187. return session
  188. }
  189. func NewRequest(t testing.TB, method, urlStr string) *http.Request {
  190. return NewRequestWithBody(t, method, urlStr, nil)
  191. }
  192. func NewRequestf(t testing.TB, method, urlFormat string, args ...interface{}) *http.Request {
  193. return NewRequest(t, method, fmt.Sprintf(urlFormat, args...))
  194. }
  195. func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request {
  196. urlValues := url.Values{}
  197. for key, value := range values {
  198. urlValues[key] = []string{value}
  199. }
  200. req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode()))
  201. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  202. return req
  203. }
  204. func NewRequestWithJSON(t testing.TB, method, urlStr string, v interface{}) *http.Request {
  205. jsonBytes, err := json.Marshal(v)
  206. assert.NoError(t, err)
  207. req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes))
  208. req.Header.Add("Content-Type", "application/json")
  209. return req
  210. }
  211. func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request {
  212. request, err := http.NewRequest(method, urlStr, body)
  213. assert.NoError(t, err)
  214. request.RequestURI = urlStr
  215. return request
  216. }
  217. const NoExpectedStatus = -1
  218. func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  219. recorder := httptest.NewRecorder()
  220. mac.ServeHTTP(recorder, req)
  221. if expectedStatus != NoExpectedStatus {
  222. assert.EqualValues(t, expectedStatus, recorder.Code,
  223. "Request: %s %s", req.Method, req.URL.String())
  224. }
  225. return recorder
  226. }
  227. func DecodeJSON(t testing.TB, resp *httptest.ResponseRecorder, v interface{}) {
  228. decoder := json.NewDecoder(resp.Body)
  229. assert.NoError(t, decoder.Decode(v))
  230. }
  231. func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
  232. req := NewRequest(t, "GET", urlStr)
  233. resp := session.MakeRequest(t, req, http.StatusOK)
  234. doc := NewHTMLParser(t, resp.Body)
  235. return doc.GetCSRF()
  236. }
  237. func RedirectURL(t testing.TB, resp *httptest.ResponseRecorder) string {
  238. urlSlice := resp.HeaderMap["Location"]
  239. assert.NotEmpty(t, urlSlice, "No redirect URL founds")
  240. return urlSlice[0]
  241. }