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.

integration_test.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. //nolint:forbidigo
  4. package integration
  5. import (
  6. "bytes"
  7. "context"
  8. "fmt"
  9. "hash"
  10. "hash/fnv"
  11. "io"
  12. "net/http"
  13. "net/http/cookiejar"
  14. "net/http/httptest"
  15. "net/url"
  16. "os"
  17. "path/filepath"
  18. "strings"
  19. "sync/atomic"
  20. "testing"
  21. "time"
  22. "code.gitea.io/gitea/models/auth"
  23. "code.gitea.io/gitea/models/unittest"
  24. gitea_context "code.gitea.io/gitea/modules/context"
  25. "code.gitea.io/gitea/modules/graceful"
  26. "code.gitea.io/gitea/modules/json"
  27. "code.gitea.io/gitea/modules/log"
  28. "code.gitea.io/gitea/modules/setting"
  29. "code.gitea.io/gitea/modules/testlogger"
  30. "code.gitea.io/gitea/modules/util"
  31. "code.gitea.io/gitea/modules/web"
  32. "code.gitea.io/gitea/routers"
  33. "code.gitea.io/gitea/tests"
  34. "github.com/PuerkitoBio/goquery"
  35. "github.com/stretchr/testify/assert"
  36. "github.com/xeipuuv/gojsonschema"
  37. )
  38. var testWebRoutes *web.Route
  39. type NilResponseRecorder struct {
  40. httptest.ResponseRecorder
  41. Length int
  42. }
  43. func (n *NilResponseRecorder) Write(b []byte) (int, error) {
  44. n.Length += len(b)
  45. return len(b), nil
  46. }
  47. // NewRecorder returns an initialized ResponseRecorder.
  48. func NewNilResponseRecorder() *NilResponseRecorder {
  49. return &NilResponseRecorder{
  50. ResponseRecorder: *httptest.NewRecorder(),
  51. }
  52. }
  53. type NilResponseHashSumRecorder struct {
  54. httptest.ResponseRecorder
  55. Hash hash.Hash
  56. Length int
  57. }
  58. func (n *NilResponseHashSumRecorder) Write(b []byte) (int, error) {
  59. _, _ = n.Hash.Write(b)
  60. n.Length += len(b)
  61. return len(b), nil
  62. }
  63. // NewRecorder returns an initialized ResponseRecorder.
  64. func NewNilResponseHashSumRecorder() *NilResponseHashSumRecorder {
  65. return &NilResponseHashSumRecorder{
  66. Hash: fnv.New32(),
  67. ResponseRecorder: *httptest.NewRecorder(),
  68. }
  69. }
  70. func TestMain(m *testing.M) {
  71. defer log.GetManager().Close()
  72. managerCtx, cancel := context.WithCancel(context.Background())
  73. graceful.InitManager(managerCtx)
  74. defer cancel()
  75. tests.InitTest(true)
  76. testWebRoutes = routers.NormalRoutes()
  77. // integration test settings...
  78. if setting.CfgProvider != nil {
  79. testingCfg := setting.CfgProvider.Section("integration-tests")
  80. testlogger.SlowTest = testingCfg.Key("SLOW_TEST").MustDuration(testlogger.SlowTest)
  81. testlogger.SlowFlush = testingCfg.Key("SLOW_FLUSH").MustDuration(testlogger.SlowFlush)
  82. }
  83. if os.Getenv("GITEA_SLOW_TEST_TIME") != "" {
  84. duration, err := time.ParseDuration(os.Getenv("GITEA_SLOW_TEST_TIME"))
  85. if err == nil {
  86. testlogger.SlowTest = duration
  87. }
  88. }
  89. if os.Getenv("GITEA_SLOW_FLUSH_TIME") != "" {
  90. duration, err := time.ParseDuration(os.Getenv("GITEA_SLOW_FLUSH_TIME"))
  91. if err == nil {
  92. testlogger.SlowFlush = duration
  93. }
  94. }
  95. os.Unsetenv("GIT_AUTHOR_NAME")
  96. os.Unsetenv("GIT_AUTHOR_EMAIL")
  97. os.Unsetenv("GIT_AUTHOR_DATE")
  98. os.Unsetenv("GIT_COMMITTER_NAME")
  99. os.Unsetenv("GIT_COMMITTER_EMAIL")
  100. os.Unsetenv("GIT_COMMITTER_DATE")
  101. err := unittest.InitFixtures(
  102. unittest.FixturesOptions{
  103. Dir: filepath.Join(filepath.Dir(setting.AppPath), "models/fixtures/"),
  104. },
  105. )
  106. if err != nil {
  107. fmt.Printf("Error initializing test database: %v\n", err)
  108. os.Exit(1)
  109. }
  110. // FIXME: the console logger is deleted by mistake, so if there is any `log.Fatal`, developers won't see any error message.
  111. // Instead, "No tests were found", last nonsense log is "According to the configuration, subsequent logs will not be printed to the console"
  112. exitCode := m.Run()
  113. testlogger.WriterCloser.Reset()
  114. if err = util.RemoveAll(setting.Indexer.IssuePath); err != nil {
  115. fmt.Printf("util.RemoveAll: %v\n", err)
  116. os.Exit(1)
  117. }
  118. if err = util.RemoveAll(setting.Indexer.RepoPath); err != nil {
  119. fmt.Printf("Unable to remove repo indexer: %v\n", err)
  120. os.Exit(1)
  121. }
  122. os.Exit(exitCode)
  123. }
  124. type TestSession struct {
  125. jar http.CookieJar
  126. }
  127. func (s *TestSession) GetCookie(name string) *http.Cookie {
  128. baseURL, err := url.Parse(setting.AppURL)
  129. if err != nil {
  130. return nil
  131. }
  132. for _, c := range s.jar.Cookies(baseURL) {
  133. if c.Name == name {
  134. return c
  135. }
  136. }
  137. return nil
  138. }
  139. func (s *TestSession) MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  140. t.Helper()
  141. baseURL, err := url.Parse(setting.AppURL)
  142. assert.NoError(t, err)
  143. for _, c := range s.jar.Cookies(baseURL) {
  144. req.AddCookie(c)
  145. }
  146. resp := MakeRequest(t, req, expectedStatus)
  147. ch := http.Header{}
  148. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  149. cr := http.Request{Header: ch}
  150. s.jar.SetCookies(baseURL, cr.Cookies())
  151. return resp
  152. }
  153. func (s *TestSession) MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
  154. t.Helper()
  155. baseURL, err := url.Parse(setting.AppURL)
  156. assert.NoError(t, err)
  157. for _, c := range s.jar.Cookies(baseURL) {
  158. req.AddCookie(c)
  159. }
  160. resp := MakeRequestNilResponseRecorder(t, req, expectedStatus)
  161. ch := http.Header{}
  162. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  163. cr := http.Request{Header: ch}
  164. s.jar.SetCookies(baseURL, cr.Cookies())
  165. return resp
  166. }
  167. func (s *TestSession) MakeRequestNilResponseHashSumRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseHashSumRecorder {
  168. t.Helper()
  169. baseURL, err := url.Parse(setting.AppURL)
  170. assert.NoError(t, err)
  171. for _, c := range s.jar.Cookies(baseURL) {
  172. req.AddCookie(c)
  173. }
  174. resp := MakeRequestNilResponseHashSumRecorder(t, req, expectedStatus)
  175. ch := http.Header{}
  176. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  177. cr := http.Request{Header: ch}
  178. s.jar.SetCookies(baseURL, cr.Cookies())
  179. return resp
  180. }
  181. const userPassword = "password"
  182. func emptyTestSession(t testing.TB) *TestSession {
  183. t.Helper()
  184. jar, err := cookiejar.New(nil)
  185. assert.NoError(t, err)
  186. return &TestSession{jar: jar}
  187. }
  188. func getUserToken(t testing.TB, userName string, scope ...auth.AccessTokenScope) string {
  189. return getTokenForLoggedInUser(t, loginUser(t, userName), scope...)
  190. }
  191. func loginUser(t testing.TB, userName string) *TestSession {
  192. t.Helper()
  193. return loginUserWithPassword(t, userName, userPassword)
  194. }
  195. func loginUserWithPassword(t testing.TB, userName, password string) *TestSession {
  196. t.Helper()
  197. req := NewRequest(t, "GET", "/user/login")
  198. resp := MakeRequest(t, req, http.StatusOK)
  199. doc := NewHTMLParser(t, resp.Body)
  200. req = NewRequestWithValues(t, "POST", "/user/login", map[string]string{
  201. "_csrf": doc.GetCSRF(),
  202. "user_name": userName,
  203. "password": password,
  204. })
  205. resp = MakeRequest(t, req, http.StatusSeeOther)
  206. ch := http.Header{}
  207. ch.Add("Cookie", strings.Join(resp.Header()["Set-Cookie"], ";"))
  208. cr := http.Request{Header: ch}
  209. session := emptyTestSession(t)
  210. baseURL, err := url.Parse(setting.AppURL)
  211. assert.NoError(t, err)
  212. session.jar.SetCookies(baseURL, cr.Cookies())
  213. return session
  214. }
  215. // token has to be unique this counter take care of
  216. var tokenCounter int64
  217. // getTokenForLoggedInUser returns a token for a logged in user.
  218. // The scope is an optional list of snake_case strings like the frontend form fields,
  219. // but without the "scope_" prefix.
  220. func getTokenForLoggedInUser(t testing.TB, session *TestSession, scopes ...auth.AccessTokenScope) string {
  221. t.Helper()
  222. var token string
  223. req := NewRequest(t, "GET", "/user/settings/applications")
  224. resp := session.MakeRequest(t, req, http.StatusOK)
  225. var csrf string
  226. for _, cookie := range resp.Result().Cookies() {
  227. if cookie.Name != "_csrf" {
  228. continue
  229. }
  230. csrf = cookie.Value
  231. break
  232. }
  233. if csrf == "" {
  234. doc := NewHTMLParser(t, resp.Body)
  235. csrf = doc.GetCSRF()
  236. }
  237. assert.NotEmpty(t, csrf)
  238. urlValues := url.Values{}
  239. urlValues.Add("_csrf", csrf)
  240. urlValues.Add("name", fmt.Sprintf("api-testing-token-%d", atomic.AddInt64(&tokenCounter, 1)))
  241. for _, scope := range scopes {
  242. urlValues.Add("scope", string(scope))
  243. }
  244. req = NewRequestWithURLValues(t, "POST", "/user/settings/applications", urlValues)
  245. resp = session.MakeRequest(t, req, http.StatusSeeOther)
  246. // Log the flash values on failure
  247. if !assert.Equal(t, resp.Result().Header["Location"], []string{"/user/settings/applications"}) {
  248. for _, cookie := range resp.Result().Cookies() {
  249. if cookie.Name != gitea_context.CookieNameFlash {
  250. continue
  251. }
  252. flash, _ := url.ParseQuery(cookie.Value)
  253. for key, value := range flash {
  254. t.Logf("Flash %q: %q", key, value)
  255. }
  256. }
  257. }
  258. req = NewRequest(t, "GET", "/user/settings/applications")
  259. resp = session.MakeRequest(t, req, http.StatusOK)
  260. htmlDoc := NewHTMLParser(t, resp.Body)
  261. token = htmlDoc.doc.Find(".ui.info p").Text()
  262. assert.NotEmpty(t, token)
  263. return token
  264. }
  265. func NewRequest(t testing.TB, method, urlStr string) *http.Request {
  266. t.Helper()
  267. return NewRequestWithBody(t, method, urlStr, nil)
  268. }
  269. func NewRequestf(t testing.TB, method, urlFormat string, args ...any) *http.Request {
  270. t.Helper()
  271. return NewRequest(t, method, fmt.Sprintf(urlFormat, args...))
  272. }
  273. func NewRequestWithValues(t testing.TB, method, urlStr string, values map[string]string) *http.Request {
  274. t.Helper()
  275. urlValues := url.Values{}
  276. for key, value := range values {
  277. urlValues[key] = []string{value}
  278. }
  279. return NewRequestWithURLValues(t, method, urlStr, urlValues)
  280. }
  281. func NewRequestWithURLValues(t testing.TB, method, urlStr string, urlValues url.Values) *http.Request {
  282. t.Helper()
  283. req := NewRequestWithBody(t, method, urlStr, bytes.NewBufferString(urlValues.Encode()))
  284. req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
  285. return req
  286. }
  287. func NewRequestWithJSON(t testing.TB, method, urlStr string, v any) *http.Request {
  288. t.Helper()
  289. jsonBytes, err := json.Marshal(v)
  290. assert.NoError(t, err)
  291. req := NewRequestWithBody(t, method, urlStr, bytes.NewBuffer(jsonBytes))
  292. req.Header.Add("Content-Type", "application/json")
  293. return req
  294. }
  295. func NewRequestWithBody(t testing.TB, method, urlStr string, body io.Reader) *http.Request {
  296. t.Helper()
  297. if !strings.HasPrefix(urlStr, "http") && !strings.HasPrefix(urlStr, "/") {
  298. urlStr = "/" + urlStr
  299. }
  300. request, err := http.NewRequest(method, urlStr, body)
  301. assert.NoError(t, err)
  302. request.RequestURI = urlStr
  303. return request
  304. }
  305. func AddBasicAuthHeader(request *http.Request, username string) *http.Request {
  306. request.SetBasicAuth(username, userPassword)
  307. return request
  308. }
  309. const NoExpectedStatus = -1
  310. func MakeRequest(t testing.TB, req *http.Request, expectedStatus int) *httptest.ResponseRecorder {
  311. t.Helper()
  312. recorder := httptest.NewRecorder()
  313. if req.RemoteAddr == "" {
  314. req.RemoteAddr = "test-mock:12345"
  315. }
  316. testWebRoutes.ServeHTTP(recorder, req)
  317. if expectedStatus != NoExpectedStatus {
  318. if !assert.EqualValues(t, expectedStatus, recorder.Code, "Request: %s %s", req.Method, req.URL.String()) {
  319. logUnexpectedResponse(t, recorder)
  320. }
  321. }
  322. return recorder
  323. }
  324. func MakeRequestNilResponseRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseRecorder {
  325. t.Helper()
  326. recorder := NewNilResponseRecorder()
  327. testWebRoutes.ServeHTTP(recorder, req)
  328. if expectedStatus != NoExpectedStatus {
  329. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  330. "Request: %s %s", req.Method, req.URL.String()) {
  331. logUnexpectedResponse(t, &recorder.ResponseRecorder)
  332. }
  333. }
  334. return recorder
  335. }
  336. func MakeRequestNilResponseHashSumRecorder(t testing.TB, req *http.Request, expectedStatus int) *NilResponseHashSumRecorder {
  337. t.Helper()
  338. recorder := NewNilResponseHashSumRecorder()
  339. testWebRoutes.ServeHTTP(recorder, req)
  340. if expectedStatus != NoExpectedStatus {
  341. if !assert.EqualValues(t, expectedStatus, recorder.Code,
  342. "Request: %s %s", req.Method, req.URL.String()) {
  343. logUnexpectedResponse(t, &recorder.ResponseRecorder)
  344. }
  345. }
  346. return recorder
  347. }
  348. // logUnexpectedResponse logs the contents of an unexpected response.
  349. func logUnexpectedResponse(t testing.TB, recorder *httptest.ResponseRecorder) {
  350. t.Helper()
  351. respBytes := recorder.Body.Bytes()
  352. if len(respBytes) == 0 {
  353. return
  354. } else if len(respBytes) < 500 {
  355. // if body is short, just log the whole thing
  356. t.Log("Response: ", string(respBytes))
  357. return
  358. } else {
  359. t.Log("Response length: ", len(respBytes))
  360. }
  361. // log the "flash" error message, if one exists
  362. // we must create a new buffer, so that we don't "use up" resp.Body
  363. htmlDoc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(respBytes))
  364. if err != nil {
  365. return // probably a non-HTML response
  366. }
  367. errMsg := htmlDoc.Find(".ui.negative.message").Text()
  368. if len(errMsg) > 0 {
  369. t.Log("A flash error message was found:", errMsg)
  370. }
  371. }
  372. func DecodeJSON(t testing.TB, resp *httptest.ResponseRecorder, v any) {
  373. t.Helper()
  374. decoder := json.NewDecoder(resp.Body)
  375. assert.NoError(t, decoder.Decode(v))
  376. }
  377. func VerifyJSONSchema(t testing.TB, resp *httptest.ResponseRecorder, schemaFile string) {
  378. t.Helper()
  379. schemaFilePath := filepath.Join(filepath.Dir(setting.AppPath), "tests", "integration", "schemas", schemaFile)
  380. _, schemaFileErr := os.Stat(schemaFilePath)
  381. assert.Nil(t, schemaFileErr)
  382. schema, schemaFileReadErr := os.ReadFile(schemaFilePath)
  383. assert.Nil(t, schemaFileReadErr)
  384. assert.True(t, len(schema) > 0)
  385. nodeinfoSchema := gojsonschema.NewStringLoader(string(schema))
  386. nodeinfoString := gojsonschema.NewStringLoader(resp.Body.String())
  387. result, schemaValidationErr := gojsonschema.Validate(nodeinfoSchema, nodeinfoString)
  388. assert.Nil(t, schemaValidationErr)
  389. assert.Empty(t, result.Errors())
  390. assert.True(t, result.Valid())
  391. }
  392. func GetCSRF(t testing.TB, session *TestSession, urlStr string) string {
  393. t.Helper()
  394. req := NewRequest(t, "GET", urlStr)
  395. resp := session.MakeRequest(t, req, http.StatusOK)
  396. doc := NewHTMLParser(t, resp.Body)
  397. return doc.GetCSRF()
  398. }