render_test.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. package render
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "math"
  7. "net/http"
  8. "net/http/httptest"
  9. "strconv"
  10. "testing"
  11. "github.com/stretchr/testify/assert"
  12. "github.com/smallstep/certificates/logging"
  13. )
  14. func TestJSON(t *testing.T) {
  15. rec := httptest.NewRecorder()
  16. rw := logging.NewResponseLogger(rec)
  17. r := httptest.NewRequest("POST", "/test", http.NoBody)
  18. JSON(rw, r, map[string]any{"foo": "bar"})
  19. assert.Equal(t, http.StatusOK, rec.Result().StatusCode)
  20. assert.Equal(t, "application/json", rec.Header().Get("Content-Type"))
  21. assert.Equal(t, "{\"foo\":\"bar\"}\n", rec.Body.String())
  22. assert.Empty(t, rw.Fields())
  23. }
  24. func TestJSONPanicsOnUnsupportedType(t *testing.T) {
  25. jsonPanicTest[json.UnsupportedTypeError](t, make(chan struct{}))
  26. }
  27. func TestJSONPanicsOnUnsupportedValue(t *testing.T) {
  28. jsonPanicTest[json.UnsupportedValueError](t, math.NaN())
  29. }
  30. func TestJSONPanicsOnMarshalerError(t *testing.T) {
  31. var v erroneousJSONMarshaler
  32. jsonPanicTest[json.MarshalerError](t, v)
  33. }
  34. type erroneousJSONMarshaler struct{}
  35. func (erroneousJSONMarshaler) MarshalJSON() ([]byte, error) {
  36. return nil, assert.AnError
  37. }
  38. func jsonPanicTest[T json.UnsupportedTypeError | json.UnsupportedValueError | json.MarshalerError](t *testing.T, v any) {
  39. t.Helper()
  40. defer func() {
  41. var err error
  42. if r := recover(); r == nil {
  43. t.Fatal("expected panic")
  44. } else if e, ok := r.(error); !ok {
  45. t.Fatalf("did not panic with an error (%T)", r)
  46. } else {
  47. err = e
  48. }
  49. var e *T
  50. assert.ErrorAs(t, err, &e)
  51. }()
  52. r := httptest.NewRequest("POST", "/test", http.NoBody)
  53. JSON(httptest.NewRecorder(), r, v)
  54. }
  55. type renderableError struct {
  56. Code int `json:"-"`
  57. Message string `json:"message"`
  58. }
  59. func (err renderableError) Error() string {
  60. return err.Message
  61. }
  62. func (err renderableError) Render(w http.ResponseWriter, r *http.Request) {
  63. w.Header().Set("Content-Type", "something/custom")
  64. JSONStatus(w, r, err, err.Code)
  65. }
  66. type statusedError struct {
  67. Contents string
  68. }
  69. func (err statusedError) Error() string { return err.Contents }
  70. func (statusedError) StatusCode() int { return 432 }
  71. func TestError(t *testing.T) {
  72. cases := []struct {
  73. err error
  74. code int
  75. body string
  76. header string
  77. }{
  78. 0: {
  79. err: renderableError{532, "some string"},
  80. code: 532,
  81. body: "{\"message\":\"some string\"}\n",
  82. header: "something/custom",
  83. },
  84. 1: {
  85. err: statusedError{"123"},
  86. code: 432,
  87. body: "{\"Contents\":\"123\"}\n",
  88. header: "application/json",
  89. },
  90. }
  91. for caseIndex := range cases {
  92. kase := cases[caseIndex]
  93. t.Run(strconv.Itoa(caseIndex), func(t *testing.T) {
  94. rec := httptest.NewRecorder()
  95. r := httptest.NewRequest("POST", "/test", http.NoBody)
  96. Error(rec, r, kase.err)
  97. assert.Equal(t, kase.code, rec.Result().StatusCode)
  98. assert.Equal(t, kase.body, rec.Body.String())
  99. assert.Equal(t, kase.header, rec.Header().Get("Content-Type"))
  100. })
  101. }
  102. }
  103. type causedError struct {
  104. cause error
  105. }
  106. func (err causedError) Error() string { return fmt.Sprintf("cause: %s", err.cause) }
  107. func (err causedError) Cause() error { return err.cause }
  108. func TestStatusCodeFromError(t *testing.T) {
  109. cases := []struct {
  110. err error
  111. exp int
  112. }{
  113. 0: {nil, http.StatusInternalServerError},
  114. 1: {io.EOF, http.StatusInternalServerError},
  115. 2: {statusedError{"123"}, 432},
  116. 3: {causedError{statusedError{"432"}}, 432},
  117. }
  118. for caseIndex, kase := range cases {
  119. assert.Equal(t, kase.exp, statusCodeFromError(kase.err), "case: %d", caseIndex)
  120. }
  121. }