Adds NewAuthenticateForTest() in common/utilities.go:

- The function must return the token and an error (string, error).
    In case of an error the token is going to be an empty string. The
    assertion for the error __must__ be executed in the body of the
    test. The utility functions __must not__ panic. All of the tests
    must use this function in the future.
This commit is contained in:
smavros 2019-08-04 20:08:27 +02:00
parent e2430cadef
commit 8e185ecba4
2 changed files with 38 additions and 3 deletions

View file

@ -93,6 +93,40 @@ func TestEndpoint(t *testing.T, router *gin.Engine, token string, url string, me
}
func NewAuthenticateForTest(router *gin.Engine, url string,
method string, body []byte, expected_code int) (string, error) {
w := httptest.NewRecorder()
req, _ := http.NewRequest(method, url, bytes.NewBuffer(body))
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(w, req)
// Check the return HTTP Code
if w.Code != expected_code {
return "", fmt.Errorf("HTTP Code: Expected \"%v\". Got \"%v\".",
expected_code, w.Code)
}
var body_data map[string]interface{}
// Get the response
err := json.Unmarshal([]byte(w.Body.String()), &body_data)
if err != nil {
return "", err
}
// Check the response
success := body_data["success"].(bool)
if !success {
fmt.Println("Authentication not successful: ", body_data["message"])
return "", fmt.Errorf("Authentication unsuccessful!")
}
// Return the token and nil error
return body_data["token"].(string), nil
}
func AuthenticateForTest(t *testing.T, router *gin.Engine, url string, method string, body []byte, expected_code int) string {
w := httptest.NewRecorder()

View file

@ -29,11 +29,12 @@ func TestUserEndpoints(t *testing.T) {
credjson, _ := json.Marshal(common.CredAdmin)
msgUsersjson, _ := json.Marshal(msgUsers)
token := common.AuthenticateForTest(t, router, "/api/authenticate",
"POST", credjson, 200)
token, err := common.NewAuthenticateForTest(router,
"/api/authenticate", "POST", credjson, 200)
assert.NoError(t, err)
// test GET user/
err := common.NewTestEndpoint(router, token, "/api/users", "GET",
err = common.NewTestEndpoint(router, token, "/api/users", "GET",
nil, 200, msgUsersjson)
assert.NoError(t, err)
}