mirror of
https://github.com/gravitl/netmaker.git
synced 2025-02-25 00:24:37 +08:00
addition of responseHttp tests
This commit is contained in:
parent
4c73ff49da
commit
f8d6ca06c7
1 changed files with 57 additions and 0 deletions
57
controllers/responseHttp_test.go
Normal file
57
controllers/responseHttp_test.go
Normal file
|
@ -0,0 +1,57 @@
|
|||
package controller
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/gravitl/netmaker/models"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestFormatError(t *testing.T) {
|
||||
response := formatError(errors.New("this is a sample error"), "badrequest")
|
||||
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) {
|
||||
returnSuccessResponse(rw, r, "This is a test message")
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
func testReturnErrorResponse(t *testing.T) {
|
||||
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) {
|
||||
returnErrorResponse(rw, r, errMessage)
|
||||
}
|
||||
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)
|
||||
}
|
Loading…
Reference in a new issue