gitea源码

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package test
  4. import (
  5. "net/http"
  6. "net/http/httptest"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "code.gitea.io/gitea/modules/json"
  12. "code.gitea.io/gitea/modules/util"
  13. )
  14. // RedirectURL returns the redirect URL of a http response.
  15. // It also works for JSONRedirect: `{"redirect": "..."}`
  16. // FIXME: it should separate the logic of checking from header and JSON body
  17. func RedirectURL(resp http.ResponseWriter) string {
  18. loc := resp.Header().Get("Location")
  19. if loc != "" {
  20. return loc
  21. }
  22. if r, ok := resp.(*httptest.ResponseRecorder); ok {
  23. m := map[string]any{}
  24. err := json.Unmarshal(r.Body.Bytes(), &m)
  25. if err == nil {
  26. if loc, ok := m["redirect"].(string); ok {
  27. return loc
  28. }
  29. }
  30. }
  31. return ""
  32. }
  33. func ParseJSONError(buf []byte) (ret struct {
  34. ErrorMessage string `json:"errorMessage"`
  35. RenderFormat string `json:"renderFormat"`
  36. },
  37. ) {
  38. _ = json.Unmarshal(buf, &ret)
  39. return ret
  40. }
  41. func IsNormalPageCompleted(s string) bool {
  42. return strings.Contains(s, `<footer class="page-footer"`) && strings.Contains(s, `</html>`)
  43. }
  44. func MockVariableValue[T any](p *T, v ...T) (reset func()) {
  45. old := *p
  46. if len(v) > 0 {
  47. *p = v[0]
  48. }
  49. return func() { *p = old }
  50. }
  51. // SetupGiteaRoot Sets GITEA_ROOT if it is not already set and returns the value
  52. func SetupGiteaRoot() string {
  53. giteaRoot := os.Getenv("GITEA_ROOT")
  54. if giteaRoot != "" {
  55. return giteaRoot
  56. }
  57. _, filename, _, _ := runtime.Caller(0)
  58. giteaRoot = filepath.Dir(filepath.Dir(filepath.Dir(filename)))
  59. fixturesDir := filepath.Join(giteaRoot, "models", "fixtures")
  60. if exist, _ := util.IsDir(fixturesDir); !exist {
  61. panic("fixtures directory not found: " + fixturesDir)
  62. }
  63. _ = os.Setenv("GITEA_ROOT", giteaRoot)
  64. return giteaRoot
  65. }