request.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package apitest
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/http/httptest"
  9. "strings"
  10. "testing"
  11. "github.com/go-chi/chi"
  12. "github.com/porter-dev/porter/api/server/shared"
  13. "github.com/porter-dev/porter/api/server/shared/apierrors"
  14. "github.com/porter-dev/porter/api/server/shared/config"
  15. )
  16. func GetRequestAndRecorder(t *testing.T, method, route string, requestObj interface{}) (*http.Request, *httptest.ResponseRecorder) {
  17. var reader io.Reader = nil
  18. if requestObj != nil {
  19. data, err := json.Marshal(requestObj)
  20. if err != nil {
  21. t.Fatal(err)
  22. }
  23. reader = strings.NewReader(string(data))
  24. }
  25. // method and route don't actually matter since this is meant to test handlers
  26. req, err := http.NewRequest(method, route, reader)
  27. if err != nil {
  28. t.Fatal(err)
  29. }
  30. rr := httptest.NewRecorder()
  31. return req, rr
  32. }
  33. func WithURLParams(t *testing.T, req *http.Request, params map[string]string) *http.Request {
  34. rctx := chi.NewRouteContext()
  35. routeParams := &chi.RouteParams{}
  36. for key, val := range params {
  37. routeParams.Add(key, val)
  38. }
  39. rctx.URLParams = *routeParams
  40. req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
  41. return req
  42. }
  43. type failingDecoderValidator struct {
  44. config *config.Config
  45. }
  46. func (f *failingDecoderValidator) DecodeAndValidate(
  47. w http.ResponseWriter,
  48. r *http.Request,
  49. v interface{},
  50. ) (ok bool) {
  51. apierrors.HandleAPIError(f.config.Logger, f.config.Alerter, w, r, apierrors.NewErrInternal(fmt.Errorf("fake error")), true)
  52. return false
  53. }
  54. func (f *failingDecoderValidator) DecodeAndValidateNoWrite(
  55. r *http.Request,
  56. v interface{},
  57. ) error {
  58. return fmt.Errorf("fake error")
  59. }
  60. func NewFailingDecoderValidator(config *config.Config) shared.RequestDecoderValidator {
  61. return &failingDecoderValidator{config}
  62. }