request.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package apitest
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "net/http/httptest"
  8. "strings"
  9. "testing"
  10. "github.com/porter-dev/porter/api/server/shared"
  11. "github.com/porter-dev/porter/api/server/shared/apierrors"
  12. )
  13. func GetRequestAndRecorder(t *testing.T, requestObj interface{}) (*http.Request, *httptest.ResponseRecorder) {
  14. var reader io.Reader = nil
  15. if requestObj != nil {
  16. data, err := json.Marshal(requestObj)
  17. if err != nil {
  18. t.Fatal(err)
  19. }
  20. reader = strings.NewReader(string(data))
  21. }
  22. // method and route don't actually matter since this is meant to test handlers
  23. req, err := http.NewRequest("POST", "/fake-route", reader)
  24. if err != nil {
  25. t.Fatal(err)
  26. }
  27. rr := httptest.NewRecorder()
  28. return req, rr
  29. }
  30. type failingDecoderValidator struct {
  31. config *shared.Config
  32. }
  33. func (f *failingDecoderValidator) DecodeAndValidate(
  34. w http.ResponseWriter,
  35. r *http.Request,
  36. v interface{},
  37. ) (ok bool) {
  38. apierrors.HandleAPIError(w, f.config.Logger, apierrors.NewErrInternal(fmt.Errorf("fake error")))
  39. return false
  40. }
  41. func NewFailingDecoderValidator(config *shared.Config) shared.RequestDecoderValidator {
  42. return &failingDecoderValidator{config}
  43. }