helpers_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package api_test
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "strings"
  6. "time"
  7. "github.com/go-chi/chi"
  8. "github.com/porter-dev/porter/internal/config"
  9. "github.com/porter-dev/porter/internal/helm"
  10. "github.com/porter-dev/porter/internal/kubernetes"
  11. lr "github.com/porter-dev/porter/internal/logger"
  12. "github.com/porter-dev/porter/internal/repository"
  13. memory "github.com/porter-dev/porter/internal/repository/memory"
  14. "github.com/porter-dev/porter/server/api"
  15. "github.com/porter-dev/porter/server/router"
  16. "github.com/porter-dev/porter/internal/auth/sessionstore"
  17. )
  18. type tester struct {
  19. app *api.App
  20. repo *repository.Repository
  21. store *sessionstore.PGStore
  22. router *chi.Mux
  23. req *http.Request
  24. rr *httptest.ResponseRecorder
  25. cookie *http.Cookie
  26. }
  27. func (t *tester) execute() {
  28. t.router.ServeHTTP(t.rr, t.req)
  29. }
  30. func (t *tester) reset() {
  31. t.rr = httptest.NewRecorder()
  32. t.req = nil
  33. }
  34. func (t *tester) createUserSession(email string, pw string) {
  35. req, _ := http.NewRequest(
  36. "POST",
  37. "/api/users",
  38. strings.NewReader(`{"email":"`+email+`","password":"`+pw+`"}`),
  39. )
  40. t.req = req
  41. t.execute()
  42. if cookies := t.rr.Result().Cookies(); len(cookies) > 0 {
  43. t.cookie = cookies[0]
  44. }
  45. t.reset()
  46. }
  47. func newTester(canQuery bool) *tester {
  48. appConf := config.Conf{
  49. Debug: true,
  50. Server: config.ServerConf{
  51. Port: 8080,
  52. CookieName: "porter",
  53. CookieSecrets: []string{"secret"},
  54. TimeoutRead: time.Second * 5,
  55. TimeoutWrite: time.Second * 10,
  56. TimeoutIdle: time.Second * 15,
  57. IsTesting: true,
  58. TokenGeneratorSecret: "secret",
  59. },
  60. // unimportant here
  61. Db: config.DBConf{},
  62. // set the helm config to testing
  63. K8s: config.K8sConf{
  64. IsTesting: true,
  65. },
  66. }
  67. logger := lr.NewConsole(appConf.Debug)
  68. repo := memory.NewRepository(canQuery)
  69. store, _ := sessionstore.NewStore(repo, appConf.Server)
  70. app, _ := api.New(&api.AppConfig{
  71. Logger: logger,
  72. Repository: repo,
  73. ServerConf: appConf.Server,
  74. TestAgents: &api.TestAgents{
  75. HelmAgent: helm.GetAgentTesting(&helm.Form{}, nil, logger),
  76. HelmTestStorageDriver: helm.StorageMap["memory"](nil, nil, ""),
  77. K8sAgent: kubernetes.GetAgentTesting(),
  78. },
  79. })
  80. r := router.New(app)
  81. return &tester{
  82. app: app,
  83. repo: repo,
  84. store: store,
  85. router: r,
  86. req: nil,
  87. rr: httptest.NewRecorder(),
  88. cookie: nil,
  89. }
  90. }