response_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package controller
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/http"
  6. "net/http/httptest"
  7. "testing"
  8. "github.com/gravitl/netmaker/models"
  9. "github.com/stretchr/testify/assert"
  10. )
  11. func TestFormatError(t *testing.T) {
  12. response := formatError(errors.New("this is a sample error"), "badrequest")
  13. assert.Equal(t, http.StatusBadRequest, response.Code)
  14. assert.Equal(t, "this is a sample error", response.Message)
  15. }
  16. func TestReturnSuccessResponse(t *testing.T) {
  17. var response models.SuccessResponse
  18. handler := func(rw http.ResponseWriter, r *http.Request) {
  19. returnSuccessResponse(rw, r, "This is a test message")
  20. }
  21. req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
  22. w := httptest.NewRecorder()
  23. handler(w, req)
  24. resp := w.Result()
  25. assert.Equal(t, http.StatusOK, resp.StatusCode)
  26. assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
  27. //body, err := ioutil.ReadAll(resp.Body)
  28. //assert.Nil(t, err)
  29. //t.Log(body, string(body))
  30. err := json.NewDecoder(resp.Body).Decode(&response)
  31. assert.Nil(t, err)
  32. assert.Equal(t, http.StatusOK, response.Code)
  33. assert.Equal(t, "This is a test message", response.Message)
  34. }
  35. func testReturnErrorResponse(t *testing.T) {
  36. var response, errMessage models.ErrorResponse
  37. errMessage.Code = http.StatusUnauthorized
  38. errMessage.Message = "You are not authorized to access this endpoint"
  39. handler := func(rw http.ResponseWriter, r *http.Request) {
  40. returnErrorResponse(rw, r, errMessage)
  41. }
  42. req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
  43. w := httptest.NewRecorder()
  44. handler(w, req)
  45. resp := w.Result()
  46. assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
  47. assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
  48. err := json.NewDecoder(resp.Body).Decode(&response)
  49. assert.Nil(t, err)
  50. assert.Equal(t, http.StatusUnauthorized, response.Code)
  51. assert.Equal(t, "You are not authorized to access this endpoint", response.Message)
  52. }