netmaker/controllers/response_test.go

59 lines
2 KiB
Go
Raw Normal View History

2021-05-11 02:29:03 +08:00
package controller
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
2022-09-15 01:26:31 +08:00
"github.com/gravitl/netmaker/logic"
2021-05-11 02:29:03 +08:00
"github.com/gravitl/netmaker/models"
"github.com/stretchr/testify/assert"
)
func TestFormatError(t *testing.T) {
2022-09-15 01:26:31 +08:00
response := logic.FormatError(errors.New("this is a sample error"), "badrequest")
2021-05-11 02:29:03 +08:00
assert.Equal(t, http.StatusBadRequest, response.Code)
assert.Equal(t, "this is a sample error", response.Message)
}
func TestReturnSuccessResponse(t *testing.T) {
var response models.SuccessResponse
handler := func(rw http.ResponseWriter, r *http.Request) {
2022-09-15 01:26:31 +08:00
logic.ReturnSuccessResponse(rw, r, "This is a test message")
2021-05-11 02:29:03 +08:00
}
req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
w := httptest.NewRecorder()
handler(w, req)
resp := w.Result()
assert.Equal(t, http.StatusOK, resp.StatusCode)
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
//body, err := ioutil.ReadAll(resp.Body)
//assert.Nil(t, err)
//t.Log(body, string(body))
err := json.NewDecoder(resp.Body).Decode(&response)
assert.Nil(t, err)
assert.Equal(t, http.StatusOK, response.Code)
assert.Equal(t, "This is a test message", response.Message)
}
2022-06-17 03:42:32 +08:00
func TestReturnErrorResponse(t *testing.T) {
2021-05-11 02:29:03 +08:00
var response, errMessage models.ErrorResponse
errMessage.Code = http.StatusUnauthorized
errMessage.Message = "You are not authorized to access this endpoint"
handler := func(rw http.ResponseWriter, r *http.Request) {
2022-09-15 01:26:31 +08:00
logic.ReturnErrorResponse(rw, r, errMessage)
2021-05-11 02:29:03 +08:00
}
req := httptest.NewRequest(http.MethodGet, "http://example.com", nil)
w := httptest.NewRecorder()
handler(w, req)
resp := w.Result()
assert.Equal(t, http.StatusUnauthorized, resp.StatusCode)
assert.Equal(t, "application/json", resp.Header.Get("Content-Type"))
err := json.NewDecoder(resp.Body).Decode(&response)
assert.Nil(t, err)
assert.Equal(t, http.StatusUnauthorized, response.Code)
assert.Equal(t, "You are not authorized to access this endpoint", response.Message)
}