chg: backend: error struct

This commit is contained in:
Alex
2024-10-09 18:08:33 +02:00
parent 3b3dc9d251
commit 02d75f0ab1
7 changed files with 275 additions and 74 deletions

View File

@@ -243,6 +243,7 @@ func testCurrentUserHandler(t *testing.T, loginEmail string, loginCookie http.Co
expectedUserMail string
expectedStatus int
expectNewCookie bool
expectedErrors []map[string]string
}{
{
name: "With valid cookie",
@@ -274,6 +275,9 @@ func testCurrentUserHandler(t *testing.T, loginEmail string, loginCookie http.Co
name: "Without cookie",
setupCookie: func(req *http.Request) {},
expectedStatus: http.StatusUnauthorized,
expectedErrors: []map[string]string{
{"field": "general", "key": "server.error.no_auth_token"},
},
},
{
name: "With invalid cookie",
@@ -281,6 +285,9 @@ func testCurrentUserHandler(t *testing.T, loginEmail string, loginCookie http.Co
req.AddCookie(&invalidCookie)
},
expectedStatus: http.StatusUnauthorized,
expectedErrors: []map[string]string{
{"field": "general", "key": "server.error.no_auth_token"},
},
},
}
@@ -327,12 +334,22 @@ func testCurrentUserHandler(t *testing.T, loginEmail string, loginCookie http.Co
assert.Nil(t, newCookie, "No new cookie should be set for non-expired token")
}
} else {
// For unauthorized requests, check for an error message
var errorResponse map[string]string
// For unauthorized requests, check for the new error structure
var errorResponse map[string]interface{}
err := json.Unmarshal(w.Body.Bytes(), &errorResponse)
assert.NoError(t, err)
assert.Contains(t, errorResponse, "error")
assert.NotEmpty(t, errorResponse["error"])
errors, ok := errorResponse["errors"].([]interface{})
assert.True(t, ok, "Expected 'errors' field in response")
assert.Len(t, errors, len(tt.expectedErrors), "Unexpected number of errors")
for i, expectedError := range tt.expectedErrors {
if i < len(errors) {
actualError := errors[i].(map[string]interface{})
assert.Equal(t, expectedError["field"], actualError["field"], "Mismatched error field")
assert.Equal(t, expectedError["key"], actualError["key"], "Mismatched error key")
}
}
}
})
@@ -414,7 +431,7 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
setupCookie func(*http.Request)
updateFunc func(*models.User)
expectedStatus int
expectedError string
expectedErrors []map[string]string
}{
{
name: "Valid Update",
@@ -441,7 +458,9 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.Phone = "01738484994"
},
expectedStatus: http.StatusUnauthorized,
expectedError: "Auth token invalid",
expectedErrors: []map[string]string{
{"field": "general", "key": "server.error.no_auth_token"},
},
},
{
name: "Invalid Email Update",
@@ -456,7 +475,9 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.Email = "invalid-email"
},
expectedStatus: http.StatusBadRequest,
expectedError: "Invalid user data",
expectedErrors: []map[string]string{
{"field": "Email", "key": "server.validation.email"},
},
},
{
name: "Change LicenceNumber",
@@ -491,7 +512,7 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
expectedStatus: http.StatusAccepted,
},
{
name: "Add 2 categories",
name: "Delete 1 and add 1 category",
setupCookie: func(req *http.Request) {
req.AddCookie(&loginCookie)
},
@@ -502,13 +523,31 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.Phone = "01738484994"
u.DriversLicence.LicenceNumber = "B072RRE2I50"
var licenceRepo repositories.DriversLicenceInterface = &repositories.DriversLicenceRepository{}
category, err := licenceRepo.FindCategoryByName("B")
category, err := licenceRepo.FindCategoryByName("A")
category2, err := licenceRepo.FindCategoryByName("BE")
assert.NoError(t, err)
u.DriversLicence.LicenceCategories = []models.LicenceCategory{category, category2}
},
expectedStatus: http.StatusAccepted,
},
{
name: "Delete 1 category",
setupCookie: func(req *http.Request) {
req.AddCookie(&loginCookie)
},
updateFunc: func(u *models.User) {
u.Password = ""
u.FirstName = "John Updated"
u.LastName = "Doe Updated"
u.Phone = "01738484994"
u.DriversLicence.LicenceNumber = "B072RRE2I50"
var licenceRepo repositories.DriversLicenceInterface = &repositories.DriversLicenceRepository{}
category, err := licenceRepo.FindCategoryByName("A")
assert.NoError(t, err)
u.DriversLicence.LicenceCategories = []models.LicenceCategory{category}
},
expectedStatus: http.StatusAccepted,
},
{
name: "Delete all categories",
setupCookie: func(req *http.Request) {
@@ -538,7 +577,9 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
u.FirstName = "John Missing ID"
},
expectedStatus: http.StatusForbidden,
expectedError: "You are not authorized to update this user",
expectedErrors: []map[string]string{
{"field": "general", "key": "server.error.unauthorized_update"},
},
},
{
name: "Password Update",
@@ -582,7 +623,7 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
t.Fatalf("Failed to marshal user data: %v", err)
}
logger.Error.Printf("Updated User: %#v", updatedUser)
// logger.Error.Printf("Updated User: %#v", updatedUser)
// Create request
req, _ := http.NewRequest("PUT", "/users/"+strconv.FormatUint(uint64(user.ID), 10), bytes.NewBuffer(jsonData))
req.Header.Set("Content-Type", "application/json")
@@ -599,18 +640,38 @@ func testUpdateUser(t *testing.T, loginEmail string, loginCookie http.Cookie) {
// Perform request
router.ServeHTTP(w, req)
bodyBytes, _ := io.ReadAll(w.Body)
t.Logf("Response Body: %s", string(bodyBytes))
// Check status code
assert.Equal(t, tt.expectedStatus, w.Code)
// Parse response
var response map[string]interface{}
err = json.Unmarshal(w.Body.Bytes(), &response)
assert.NoError(t, err)
err = json.Unmarshal(bodyBytes, &response)
if err != nil {
t.Fatalf("Failed to unmarshal response body: %v", err)
}
if tt.expectedError != "" {
assert.Equal(t, tt.expectedError, response["error"])
if tt.expectedErrors != nil {
errors, ok := response["errors"].([]interface{})
if !ok {
t.Fatalf("Expected 'errors' field in response, got: %v", response)
}
assert.Len(t, errors, len(tt.expectedErrors), "Unexpected number of errors")
for i, expectedError := range tt.expectedErrors {
if i < len(errors) {
actualError := errors[i].(map[string]interface{})
assert.Equal(t, expectedError["field"], actualError["field"], "Mismatched error field")
assert.Equal(t, expectedError["key"], actualError["key"], "Mismatched error key")
}
}
} else {
assert.Equal(t, "User updated successfully", response["message"])
// Check for success message
message, ok := response["message"].(string)
if !ok {
t.Fatalf("Expected 'message' field in response, got: %v", response)
}
assert.Equal(t, "User updated successfully", message)
// Verify the update in the database
updatedUserFromDB, err := Uc.Service.GetUserByID(user.ID)
@@ -844,7 +905,7 @@ func getTestUsers() []RegisterUserTest {
return []RegisterUserTest{
{
Name: "birthday < 18 should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -854,7 +915,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "FirstName empty, should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -864,7 +925,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "LastName Empty should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -874,7 +935,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "EMail wrong format should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "johnexample.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -884,7 +945,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "Missing Zip Code should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -894,7 +955,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "Missing Address should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -904,7 +965,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "Missing City should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -914,7 +975,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "Missing IBAN should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -924,7 +985,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "Invalid IBAN should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -934,7 +995,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "Missing subscription plan should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -944,7 +1005,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "Invalid subscription plan should fail",
WantResponse: http.StatusNotFound,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -982,7 +1043,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "Subscription constraints not entered; should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.junior.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -993,7 +1054,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "Subscription constraints wrong; should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.junior.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {
@@ -1028,7 +1089,7 @@ func getTestUsers() []RegisterUserTest {
},
{
Name: "wrong driverslicence number, should fail",
WantResponse: http.StatusNotAcceptable,
WantResponse: http.StatusBadRequest,
WantDBData: map[string]interface{}{"email": "john.wronglicence.doe@example.com"},
Assert: false,
Input: GenerateInputJSON(customizeInput(func(user models.User) models.User {