response.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package apitest
  2. import (
  3. "encoding/json"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. "github.com/porter-dev/porter/api/types"
  8. "github.com/stretchr/testify/assert"
  9. )
  10. // AssertResponseExpected asserts that the expected http response matches the actual response
  11. //
  12. // Note that arguments need to be passed as pointer values due to how testify/assert handles serialization
  13. func AssertResponseExpected(t *testing.T, rr *httptest.ResponseRecorder, expResponse interface{}, gotTarget interface{}) {
  14. err := json.NewDecoder(rr.Body).Decode(gotTarget)
  15. if err != nil {
  16. t.Fatal(err)
  17. }
  18. assert.Equal(
  19. t,
  20. expResponse,
  21. gotTarget,
  22. "incorrect response data",
  23. )
  24. }
  25. func AssertResponseForbidden(t *testing.T, rr *httptest.ResponseRecorder) {
  26. reqErr := &types.ExternalError{}
  27. err := json.NewDecoder(rr.Result().Body).Decode(reqErr)
  28. if err != nil {
  29. t.Fatal(err)
  30. }
  31. expReqErr := &types.ExternalError{
  32. Error: "Forbidden",
  33. }
  34. assert.Equal(t, http.StatusForbidden, rr.Result().StatusCode, "status code should be forbidden")
  35. assert.Equal(t, expReqErr, reqErr, "body should be forbidden error")
  36. }
  37. func AssertResponseInternalServerError(t *testing.T, rr *httptest.ResponseRecorder) {
  38. reqErr := &types.ExternalError{}
  39. err := json.NewDecoder(rr.Result().Body).Decode(reqErr)
  40. if err != nil {
  41. t.Fatal(err)
  42. }
  43. expReqErr := &types.ExternalError{
  44. Error: "An internal error occurred.",
  45. }
  46. assert.Equal(t, http.StatusInternalServerError, rr.Result().StatusCode, "status code should be internal server error")
  47. assert.Equal(t, expReqErr, reqErr, "body should be internal server error")
  48. }
  49. func AssertResponseError(t *testing.T, rr *httptest.ResponseRecorder, statusCode int, expReqErr *types.ExternalError) {
  50. reqErr := &types.ExternalError{}
  51. err := json.NewDecoder(rr.Result().Body).Decode(reqErr)
  52. if err != nil {
  53. t.Fatal(err)
  54. }
  55. assert.Equal(t, statusCode, rr.Result().StatusCode, "status code should match")
  56. assert.Equal(t, expReqErr, reqErr, "body should be matching error")
  57. }