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 8.0 kB

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