request.go 1.7 KB

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