render_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. }
  66. for caseIndex := range cases {
  67. kase := cases[caseIndex]
  68. t.Run(strconv.Itoa(caseIndex), func(t *testing.T) {
  69. rec := httptest.NewRecorder()
  70. kase.fn(rec, kase.err)
  71. ret := rec.Result()
  72. assert.Equal(t, "application/json", ret.Header.Get("Content-Type"))
  73. assert.Equal(t, kase.code, ret.StatusCode)
  74. assert.Equal(t, kase.body, rec.Body.String())
  75. })
  76. }
  77. }