api_test.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package api
  2. import (
  3. "encoding/base64"
  4. "net/http"
  5. "net/http/httptest"
  6. "testing"
  7. "github.com/stretchr/testify/assert"
  8. )
  9. func Test_writeResponse(t *testing.T) {
  10. type args struct {
  11. w http.ResponseWriter
  12. r *http.Request
  13. data []byte
  14. contentType string
  15. status int
  16. }
  17. tests := []struct {
  18. name string
  19. args args
  20. wantBody string
  21. wantHeaders map[string]string
  22. }{
  23. {
  24. name: "ok",
  25. args: args{
  26. w: httptest.NewRecorder(),
  27. r: httptest.NewRequest("GET", "/", nil),
  28. data: []byte("hello world"),
  29. contentType: "application/pkcs7-mime; smime-type=certs-only",
  30. status: http.StatusOK,
  31. },
  32. wantBody: base64.StdEncoding.EncodeToString([]byte("hello world")),
  33. wantHeaders: map[string]string{
  34. "Content-Type": "application/pkcs7-mime; smime-type=certs-only",
  35. "Content-Transfer-Encoding": "base64",
  36. },
  37. },
  38. {
  39. name: "ok/csrattrs",
  40. args: args{
  41. w: httptest.NewRecorder(),
  42. r: httptest.NewRequest("GET", "/", nil),
  43. data: []byte("attribute data"),
  44. contentType: "application/csrattrs",
  45. status: http.StatusOK,
  46. },
  47. wantBody: base64.StdEncoding.EncodeToString([]byte("attribute data")),
  48. wantHeaders: map[string]string{
  49. "Content-Type": "application/csrattrs",
  50. "Content-Transfer-Encoding": "base64",
  51. },
  52. },
  53. }
  54. for _, tt := range tests {
  55. t.Run(tt.name, func(t *testing.T) {
  56. writeResponse(tt.args.w, tt.args.r, tt.args.data, tt.args.contentType, tt.args.status)
  57. resp := tt.args.w.(*httptest.ResponseRecorder)
  58. assert.Equal(t, tt.args.status, resp.Code)
  59. assert.Equal(t, tt.wantBody, resp.Body.String())
  60. for k, v := range tt.wantHeaders {
  61. assert.Equal(t, v, resp.Header().Get(k))
  62. }
  63. })
  64. }
  65. }