render_test.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package render
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/smallstep/certificates/logging"
  7. )
  8. func TestJSON(t *testing.T) {
  9. type args struct {
  10. rw http.ResponseWriter
  11. v interface{}
  12. }
  13. tests := []struct {
  14. name string
  15. args args
  16. ok bool
  17. }{
  18. {"ok", args{httptest.NewRecorder(), map[string]interface{}{"foo": "bar"}}, true},
  19. {"fail", args{httptest.NewRecorder(), make(chan int)}, false},
  20. }
  21. for _, tt := range tests {
  22. t.Run(tt.name, func(t *testing.T) {
  23. rw := logging.NewResponseLogger(tt.args.rw)
  24. JSON(rw, tt.args.v)
  25. rr, ok := tt.args.rw.(*httptest.ResponseRecorder)
  26. if !ok {
  27. t.Error("ResponseWriter does not implement *httptest.ResponseRecorder")
  28. return
  29. }
  30. fields := rw.Fields()
  31. if tt.ok {
  32. if body := rr.Body.String(); body != "{\"foo\":\"bar\"}\n" {
  33. t.Errorf(`Unexpected body = %v, want {"foo":"bar"}`, body)
  34. }
  35. if len(fields) != 0 {
  36. t.Errorf("ResponseLogger fields = %v, wants 0 elements", fields)
  37. }
  38. } else {
  39. if body := rr.Body.String(); body != "" {
  40. t.Errorf("Unexpected body = %s, want empty string", body)
  41. }
  42. if len(fields) != 1 {
  43. t.Errorf("ResponseLogger fields = %v, wants 1 element", fields)
  44. }
  45. }
  46. })
  47. }
  48. }