render_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package render
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "strconv"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. "github.com/smallstep/certificates/logging"
  9. )
  10. func TestJSON(t *testing.T) {
  11. type args struct {
  12. rw http.ResponseWriter
  13. v interface{}
  14. }
  15. tests := []struct {
  16. name string
  17. args args
  18. ok bool
  19. }{
  20. {"ok", args{httptest.NewRecorder(), map[string]interface{}{"foo": "bar"}}, true},
  21. {"fail", args{httptest.NewRecorder(), make(chan int)}, false},
  22. }
  23. for _, tt := range tests {
  24. t.Run(tt.name, func(t *testing.T) {
  25. rw := logging.NewResponseLogger(tt.args.rw)
  26. JSON(rw, tt.args.v)
  27. rr, ok := tt.args.rw.(*httptest.ResponseRecorder)
  28. if !ok {
  29. t.Error("ResponseWriter does not implement *httptest.ResponseRecorder")
  30. return
  31. }
  32. fields := rw.Fields()
  33. if tt.ok {
  34. if body := rr.Body.String(); body != "{\"foo\":\"bar\"}\n" {
  35. t.Errorf(`Unexpected body = %v, want {"foo":"bar"}`, body)
  36. }
  37. if len(fields) != 0 {
  38. t.Errorf("ResponseLogger fields = %v, wants 0 elements", fields)
  39. }
  40. } else {
  41. if body := rr.Body.String(); body != "" {
  42. t.Errorf("Unexpected body = %s, want empty string", body)
  43. }
  44. if len(fields) != 1 {
  45. t.Errorf("ResponseLogger fields = %v, wants 1 element", fields)
  46. }
  47. }
  48. })
  49. }
  50. }
  51. func TestErrors(t *testing.T) {
  52. cases := []struct {
  53. fn func(http.ResponseWriter, error) // helper
  54. err error // error being render
  55. code int // expected status code
  56. body string // expected body
  57. }{
  58. // --- BadRequest
  59. 0: {
  60. fn: BadRequest,
  61. err: assert.AnError,
  62. code: http.StatusBadRequest,
  63. body: `{"status":400,"message":"assert.AnError general error for testing"}`,
  64. },
  65. 1: {
  66. fn: BadRequest,
  67. code: http.StatusBadRequest,
  68. body: `{"status":400,"message":"Bad Request"}`,
  69. },
  70. }
  71. for caseIndex := range cases {
  72. kase := cases[caseIndex]
  73. t.Run(strconv.Itoa(caseIndex), func(t *testing.T) {
  74. rec := httptest.NewRecorder()
  75. kase.fn(rec, kase.err)
  76. ret := rec.Result()
  77. assert.Equal(t, "application/json", ret.Header.Get("Content-Type"))
  78. assert.Equal(t, kase.code, ret.StatusCode)
  79. assert.Equal(t, kase.body, rec.Body.String())
  80. })
  81. }
  82. }