response_test.go 2.0 KB

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