utils_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package api
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "reflect"
  6. "testing"
  7. "github.com/pkg/errors"
  8. "github.com/smallstep/certificates/logging"
  9. )
  10. func TestLogError(t *testing.T) {
  11. theError := errors.New("the error")
  12. type args struct {
  13. rw http.ResponseWriter
  14. err error
  15. }
  16. tests := []struct {
  17. name string
  18. args args
  19. withFields bool
  20. }{
  21. {"normalLogger", args{httptest.NewRecorder(), theError}, false},
  22. {"responseLogger", args{logging.NewResponseLogger(httptest.NewRecorder()), theError}, true},
  23. }
  24. for _, tt := range tests {
  25. t.Run(tt.name, func(t *testing.T) {
  26. LogError(tt.args.rw, tt.args.err)
  27. if tt.withFields {
  28. if rl, ok := tt.args.rw.(logging.ResponseLogger); ok {
  29. fields := rl.Fields()
  30. if !reflect.DeepEqual(fields["error"], theError) {
  31. t.Errorf("ResponseLogger[\"error\"] = %s, wants %s", fields["error"], theError)
  32. }
  33. } else {
  34. t.Error("ResponseWriter does not implement logging.ResponseLogger")
  35. }
  36. }
  37. })
  38. }
  39. }
  40. func TestJSON(t *testing.T) {
  41. type args struct {
  42. rw http.ResponseWriter
  43. v interface{}
  44. }
  45. tests := []struct {
  46. name string
  47. args args
  48. ok bool
  49. }{
  50. {"ok", args{httptest.NewRecorder(), map[string]interface{}{"foo": "bar"}}, true},
  51. {"fail", args{httptest.NewRecorder(), make(chan int)}, false},
  52. }
  53. for _, tt := range tests {
  54. t.Run(tt.name, func(t *testing.T) {
  55. rw := logging.NewResponseLogger(tt.args.rw)
  56. JSON(rw, tt.args.v)
  57. rr, ok := tt.args.rw.(*httptest.ResponseRecorder)
  58. if !ok {
  59. t.Error("ResponseWriter does not implement *httptest.ResponseRecorder")
  60. return
  61. }
  62. fields := rw.Fields()
  63. if tt.ok {
  64. if body := rr.Body.String(); body != "{\"foo\":\"bar\"}\n" {
  65. t.Errorf(`Unexpected body = %v, want {"foo":"bar"}`, body)
  66. }
  67. if len(fields) != 0 {
  68. t.Errorf("ResponseLogger fields = %v, wants 0 elements", fields)
  69. }
  70. } else {
  71. if body := rr.Body.String(); body != "" {
  72. t.Errorf("Unexpected body = %s, want empty string", body)
  73. }
  74. if len(fields) != 1 {
  75. t.Errorf("ResponseLogger fields = %v, wants 1 element", fields)
  76. }
  77. }
  78. })
  79. }
  80. }